baa-conductor


baa-conductor / scripts / runtime
im_wower  ·  2026-03-23

generate-shared-token.sh

 1#!/usr/bin/env bash
 2set -euo pipefail
 3
 4SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
 5# shellcheck source=./common.sh
 6source "${SCRIPT_DIR}/common.sh"
 7
 8usage() {
 9  cat <<'EOF'
10Usage:
11  scripts/runtime/generate-shared-token.sh [options]
12
13Options:
14  --output PATH     Target file. Defaults to ~/.config/baa-conductor/shared-token.txt
15  --bytes N         Random byte length before encoding. Defaults to 32.
16  --hex             Write hex output. This is the default.
17  --base64          Write base64 output.
18  --help            Show this help text.
19
20Notes:
21  The generated token is written with mode 600.
22  Re-run install-mini.sh or install-launchd.sh after rotating this file so launchd
23  services pick up the new BAA_SHARED_TOKEN value.
24EOF
25}
26
27require_command chmod
28require_command mkdir
29require_command openssl
30
31output_path="${HOME:-$(default_home_dir)}/.config/baa-conductor/shared-token.txt"
32byte_length="32"
33encoding="hex"
34
35while [[ $# -gt 0 ]]; do
36  case "$1" in
37    --output)
38      output_path="$2"
39      shift 2
40      ;;
41    --bytes)
42      byte_length="$2"
43      shift 2
44      ;;
45    --hex)
46      encoding="hex"
47      shift
48      ;;
49    --base64)
50      encoding="base64"
51      shift
52      ;;
53    --help)
54      usage
55      exit 0
56      ;;
57    *)
58      die "Unknown option: $1"
59      ;;
60  esac
61done
62
63if ! [[ "$byte_length" =~ ^[0-9]+$ ]] || [[ "$byte_length" -le 0 ]]; then
64  die "--bytes must be a positive integer."
65fi
66
67ensure_directory "$(dirname "$output_path")" "700"
68
69case "$encoding" in
70  hex)
71    token="$(openssl rand -hex "$byte_length")"
72    ;;
73  base64)
74    token="$(openssl rand -base64 "$byte_length" | tr -d '\n')"
75    ;;
76  *)
77    die "Unsupported encoding: $encoding"
78    ;;
79esac
80
81printf '%s\n' "$token" >"$output_path"
82chmod 600 "$output_path"
83
84runtime_log "generated BAA_SHARED_TOKEN at ${output_path}"
85runtime_log "encoding=${encoding} bytes=${byte_length}"