Wraps openssl rand -hex 32 (with /dev/urandom fallback) so operators don't have to remember the incantation. Defaults to printing the secret; --write [path] sets/replaces CM_AUTH_SECRET in the target .env (./.env by default) and prints the restart command.
82 lines
2.4 KiB
Bash
Executable File
82 lines
2.4 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Generate a 32-byte (64 hex chars) CM_AUTH_SECRET for cm-web-next session
|
|
# signing. Prints the value to stdout, or appends/replaces it in a target
|
|
# .env file with --write.
|
|
set -euo pipefail
|
|
|
|
usage() {
|
|
cat <<'EOF'
|
|
Generate a CM_AUTH_SECRET for cm-web-next.
|
|
|
|
Usage:
|
|
scripts/gen_auth_secret.sh Print a fresh secret to stdout.
|
|
scripts/gen_auth_secret.sh --write Set CM_AUTH_SECRET= in ./.env
|
|
(creates the file if missing,
|
|
replaces the line if present).
|
|
scripts/gen_auth_secret.sh --write PATH Same, against an explicit .env path.
|
|
|
|
Notes:
|
|
- Requires `openssl` (falls back to /dev/urandom if missing).
|
|
- Rotating the secret invalidates every existing session — every signed-in
|
|
operator gets bounced to /cm-auth on the next request.
|
|
EOF
|
|
}
|
|
|
|
generate() {
|
|
if command -v openssl >/dev/null 2>&1; then
|
|
openssl rand -hex 32
|
|
else
|
|
head -c 32 /dev/urandom | xxd -p -c 64
|
|
fi
|
|
}
|
|
|
|
write_into() {
|
|
local target="$1"
|
|
local secret
|
|
secret="$(generate)"
|
|
if [[ -f "${target}" ]] && grep -q '^CM_AUTH_SECRET=' "${target}"; then
|
|
# Replace in place. Use a tmp file so we don't truncate on failure.
|
|
local tmp
|
|
tmp="$(mktemp)"
|
|
awk -v s="${secret}" '
|
|
/^CM_AUTH_SECRET=/ { print "CM_AUTH_SECRET=" s; next }
|
|
{ print }
|
|
' "${target}" >"${tmp}"
|
|
mv "${tmp}" "${target}"
|
|
echo "Replaced CM_AUTH_SECRET in ${target}"
|
|
else
|
|
[[ -f "${target}" ]] || touch "${target}"
|
|
# Add a leading newline only if the file already has content and doesn't
|
|
# end with a newline.
|
|
if [[ -s "${target}" && -n "$(tail -c 1 "${target}")" ]]; then
|
|
printf '\n' >>"${target}"
|
|
fi
|
|
printf 'CM_AUTH_SECRET=%s\n' "${secret}" >>"${target}"
|
|
echo "Appended CM_AUTH_SECRET to ${target}"
|
|
fi
|
|
echo "Restart web-next to pick up the new secret:"
|
|
echo " bash scripts/dev.sh down && bash scripts/dev.sh up"
|
|
echo " # or, in production: docker compose restart web-next"
|
|
}
|
|
|
|
case "${1:-}" in
|
|
-h|--help)
|
|
usage
|
|
;;
|
|
--write)
|
|
target="${2:-.env}"
|
|
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
# Resolve relative paths against the repo root, not CWD.
|
|
[[ "${target}" = /* ]] || target="${ROOT_DIR}/${target}"
|
|
write_into "${target}"
|
|
;;
|
|
"")
|
|
generate
|
|
;;
|
|
*)
|
|
echo "Unknown option: $1" >&2
|
|
usage >&2
|
|
exit 2
|
|
;;
|
|
esac
|