Repository navigation
Expand file tree
/
Copy pathimp-auth
More file actions
executable file
·318 lines (286 loc) · 11.5 KB
/
Copy pathimp-auth
File metadata and controls
executable file
·318 lines (286 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!/bin/bash
# imp-auth — mint and keep the Claude Max token that imp-proxy lends out.
#
# This mints a long-lived, INFERENCE-ONLY OAuth token from your Max
# subscription (via `claude setup-token`) and keeps it in the macOS keychain,
# where imp-proxy finds it first. That is the part you want.
#
# `push` is the earlier design, and Fly Sprites only: it installs the token
# into a sprite's ~/.claude/settings.json "env" block and LEAVES IT THERE --
# on disk, in every checkpoint, valid after you disconnect. imp-proxy exists
# so that nothing has to. Use push only for a sprite that must keep working
# while you are not connected.
#
# Why settings.json and not an env var: `sprite exec` runs with a bare
# environment — no ~/.bashrc, no /etc/environment — so exported vars do not
# reach `sprite exec -- claude`. The settings.json "env" block is read by
# Claude Code itself, so it works for exec, console, and survives self-update.
#
# Why setup-token and not mirroring ~/.claude/.credentials.json: your Mac's
# session token refreshes and ROTATES. A sprite refreshing the same credential
# invalidates your local session. setup-token is an independent credential,
# scoped to inference only, revocable on its own.
set -euo pipefail
KEYCHAIN_SERVICE="imp-oauth"
STATE_DIR="$HOME/.config/imp"
die() { printf 'error: %s\n' "$*" >&2; exit 1; }
info() { printf '%s\n' "$*" >&2; }
usage() {
cat <<'USAGE'
imp-auth <command> [options]
Commands:
mint Instructions + run `claude setup-token`, then store
store Read a token from a hidden prompt into the keychain
forget Delete the token from the local keychain
Fly Sprites only, and the earlier design -- these leave the real token on
the sprite. imp-proxy lends it without doing that:
push [-s NAME|--all] Install the stored token into a sprite
verify [-s NAME|--all] Make a real inference call on the sprite
status [-s NAME|--all] Show local + remote credential state
remove [-s NAME|--all] Strip the token from a sprite
With no -s and no --all, the sprite active for this directory is used
(`sprite use`), matching plain `sprite exec` behavior.
USAGE
}
have_token() { security find-generic-password -s "$KEYCHAIN_SERVICE" -a "$USER" >/dev/null 2>&1; }
# Resolve target sprites into $TARGETS (newline separated). Empty = default sprite.
TARGETS=""
parse_targets() {
local all=0 name=""
while [ $# -gt 0 ]; do
case "$1" in
--all) all=1; shift ;;
-s|--sprite) name="${2:-}"; [ -n "$name" ] || die "-s needs a sprite name"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) die "unexpected argument: $1" ;;
esac
done
if [ "$all" -eq 1 ]; then
[ -z "$name" ] || die "--all and -s are mutually exclusive"
TARGETS=$(sprite list 2>/dev/null | sed -e 's/[[:space:]]*$//' -e '/^$/d')
[ -n "$TARGETS" ] || die "no sprites found"
else
TARGETS="$name" # empty string means "whatever sprite is active here"
fi
}
# sprite CLI args for a target ("" -> no -s flag, use the active sprite).
# Callers use $sf UNQUOTED on purpose: the word split is what turns "" into no
# argument at all. An array would be the tidy alternative, but bash 3.2 (what
# macOS ships) errors on "${arr[@]}" for an empty array under `set -u`.
sflag() { if [ -n "$1" ]; then printf '%s' "-s $1"; fi; return 0; }
label() { [ -n "$1" ] && printf '%s' "$1" || printf '%s' "(active sprite)"; }
cmd_mint() {
cat >&2 <<'MSG'
Minting a long-lived Claude Code token from your Max subscription.
`claude setup-token` opens a browser, and prints a token starting with
sk-ant-oat01-. It is INFERENCE ONLY: it cannot drive Remote Control or account
actions, which is exactly what you want sitting on a remote VM.
Copy the token when it appears, then paste it at the prompt that follows.
MSG
claude setup-token || die "setup-token failed"
cmd_store
}
cmd_store() {
local token=""
printf 'Paste the sk-ant-oat01-... token (input hidden): ' >&2
IFS= read -rs token || true
printf '\n' >&2
[ -n "$token" ] || die "no token entered"
case "$token" in
sk-ant-oat01-*) ;;
*) info "warning: token does not start with sk-ant-oat01- — storing anyway" ;;
esac
# Note: the token transits argv here, briefly visible to `ps` on this Mac
# only. The alternative (security's own prompt) would make you retype it.
security add-generic-password -U -s "$KEYCHAIN_SERVICE" -a "$USER" \
-D "Claude Max token for imp" -T /usr/bin/security -w "$token"
mkdir -p "$STATE_DIR"
date -u '+%Y-%m-%dT%H:%M:%SZ' > "$STATE_DIR/minted"
info "stored in keychain as '$KEYCHAIN_SERVICE'"
info "setup-token credentials are long-lived; re-mint if inference starts 401ing."
}
cmd_forget() {
if security delete-generic-password -s "$KEYCHAIN_SERVICE" -a "$USER" >/dev/null 2>&1; then
info "removed from keychain"
else
info "nothing stored in keychain"
fi
rm -f "$STATE_DIR/minted"
}
# shellcheck disable=SC2086 # $sf must word-split; see sflag()
push_one() {
local s="$1" sf rhome tokfile mergefile
sf=$(sflag "$s")
rhome=$(sprite exec $sf -- printenv HOME 2>/dev/null | tr -d '\r\n') || true
[ -n "$rhome" ] || die "$(label "$s"): could not determine remote HOME"
# `set -e` does NOT apply in here. for_each calls this as `"$fn" "$t" || rc=1`,
# and bash disables errexit for the whole of a function whose status is
# tested. Every fallible command below is therefore checked by hand -- and
# must stay that way. Without it a failed push of the merge script would
# fall through to executing whatever stale copy is at that path.
tokfile=$(mktemp "${TMPDIR:-/tmp}/imp-auth-tok.XXXXXX") \
|| die "$(label "$s"): could not create a temp file"
mergefile=$(mktemp "${TMPDIR:-/tmp}/imp-auth-merge.XXXXXX") \
|| die "$(label "$s"): could not create a temp file"
# EXIT does the cleanup; INT/TERM must exit rather than fall through, or a
# signal between commands deletes the files and carries on without them.
trap 'rm -f "$tokfile" "$mergefile"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
chmod 600 "$tokfile" || die "$(label "$s"): could not secure the temp file"
# The token goes over as a file, never as argv, so it stays out of the
# sprite's process list and out of any control-plane command logging.
security find-generic-password -s "$KEYCHAIN_SERVICE" -a "$USER" -w > "$tokfile" \
|| die "$(label "$s"): could not read the token from the keychain"
[ -s "$tokfile" ] || die "$(label "$s"): keychain returned an empty token"
cat > "$mergefile" <<'PY_EOF'
import json, os, sys, tempfile
home = os.path.expanduser("~")
settings = os.path.join(home, ".claude", "settings.json")
stage = os.path.join(home, ".claude", ".max-token.stage")
with open(stage) as f:
token = f.read().strip()
os.remove(stage)
if not token:
sys.exit("staged token was empty")
try:
with open(settings) as f:
data = json.load(f)
except (IOError, OSError):
data = {}
except ValueError:
sys.exit("existing settings.json is not valid JSON; refusing to overwrite")
data.setdefault("env", {})["CLAUDE_CODE_OAUTH_TOKEN"] = token
d = os.path.dirname(settings)
os.makedirs(d, exist_ok=True)
# mkstemp, not open(tmp, "w"): a fixed name follows a pre-existing symlink and
# is created with the default mode, so the token would be readable in the
# window before chmod. This descriptor is 0600 from the start.
fd, tmp = tempfile.mkstemp(prefix=".imp-auth.", suffix=".tmp", dir=d)
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
os.replace(tmp, settings)
except BaseException:
try:
os.remove(tmp)
except OSError:
pass
raise
print("installed")
PY_EOF
sprite exec $sf -- mkdir -p "$rhome/.claude" >/dev/null \
|| die "$(label "$s"): could not create ~/.claude on the sprite"
# Merge script first: if the token push fails after this, there is no stale
# script waiting to be run against a leftover stage file.
sprite file push $sf "$mergefile" "/tmp/imp-auth-merge.py" >/dev/null \
|| die "$(label "$s"): could not push the merge script"
sprite file push $sf "$tokfile" "$rhome/.claude/.max-token.stage" >/dev/null || {
sprite exec $sf -- rm -f /tmp/imp-auth-merge.py >/dev/null 2>&1 || true
die "$(label "$s"): could not push the token"
}
local out
out=$(sprite exec $sf -- python3 /tmp/imp-auth-merge.py 2>&1) || {
sprite exec $sf -- rm -f /tmp/imp-auth-merge.py "$rhome/.claude/.max-token.stage" >/dev/null 2>&1 || true
die "$(label "$s"): $out"
}
sprite exec $sf -- rm -f /tmp/imp-auth-merge.py >/dev/null 2>&1 || true
rm -f "$tokfile" "$mergefile"
trap - EXIT INT TERM
info "$(label "$s"): $out"
}
# shellcheck disable=SC2086 # $sf must word-split; see sflag()
verify_one() {
local s="$1" sf out
sf=$(sflag "$s")
# Branch on captured output, not exit status: `claude -p` reports auth
# failures on stdout and still exits 0.
out=$(sprite exec $sf --dir /tmp -- claude -p 'Reply with exactly: SPRITE_AUTH_OK' 2>&1 || true)
case "$out" in
*SPRITE_AUTH_OK*) info "$(label "$s"): OK — Max inference working"; return 0 ;;
*) info "$(label "$s"): FAILED — $(printf '%s' "$out" | head -3)"; return 1 ;;
esac
}
# shellcheck disable=SC2086 # $sf must word-split; see sflag()
status_one() {
local s="$1" sf out
sf=$(sflag "$s")
out=$(sprite exec $sf -- python3 -c '
import json, os, stat
p = os.path.expanduser("~/.claude/settings.json")
try:
d = json.load(open(p))
except Exception:
print("no readable settings.json"); raise SystemExit
tok = d.get("env", {}).get("CLAUDE_CODE_OAUTH_TOKEN")
mode = stat.S_IMODE(os.stat(p).st_mode)
print("token installed (%d chars), settings.json mode %o" % (len(tok), mode) if tok
else "no token installed")
' 2>&1 || true)
info "$(label "$s"): $out"
}
for_each() {
local fn="$1" rc=0 t
if [ -z "$TARGETS" ]; then
"$fn" "" || rc=1
else
while IFS= read -r t; do
[ -n "$t" ] || continue
"$fn" "$t" || rc=1
done <<< "$TARGETS"
fi
return $rc
}
main() {
local cmd="${1:-}"
if [ $# -gt 0 ]; then shift; fi
case "$cmd" in
mint) cmd_mint ;;
store) cmd_store ;;
forget) cmd_forget ;;
push)
have_token || die "no token stored — run: $0 mint"
parse_targets "$@"; for_each push_one ;;
verify) parse_targets "$@"; for_each verify_one ;;
status)
if have_token; then
info "local: token present in keychain ($(cat "$STATE_DIR/minted" 2>/dev/null || echo 'mint date unknown'))"
else
info "local: no token in keychain"
fi
parse_targets "$@"; for_each status_one ;;
remove)
parse_targets "$@"
# shellcheck disable=SC2086 # $sf must word-split; see sflag()
remove_one() {
local sf; sf=$(sflag "$1")
sprite exec $sf -- python3 -c '
import json, os, tempfile
p = os.path.expanduser("~/.claude/settings.json")
with open(p) as f:
d = json.load(f)
env = d.get("env", {})
if env.pop("CLAUDE_CODE_OAUTH_TOKEN", None) is None:
print("no token present"); raise SystemExit
if not env: d.pop("env", None)
# open(p, "w") truncates before serialising: an interruption there destroys
# settings unrelated to us. Write beside it and rename.
fd, tmp = tempfile.mkstemp(prefix=".imp-auth.", suffix=".tmp", dir=os.path.dirname(p))
try:
with os.fdopen(fd, "w") as f:
json.dump(d, f, indent=2)
f.write("\n")
os.replace(tmp, p)
except BaseException:
try: os.remove(tmp)
except OSError: pass
raise
print("token removed")' 2>&1 | while IFS= read -r l; do info "$(label "$1"): $l"; done
}
for_each remove_one ;;
""|-h|--help|help) usage ;;
*) usage; exit 1 ;;
esac
}
main "$@"