@shieldfive/cli 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +113 -9
- package/SECURITY.md +9 -5
- package/package.json +1 -1
- package/src/agent/client.mjs +102 -0
- package/src/agent/ledger.mjs +254 -0
- package/src/agent/main.mjs +72 -0
- package/src/agent/paths.mjs +132 -0
- package/src/agent/protocol.mjs +125 -0
- package/src/agent/server.mjs +525 -0
- package/src/auth.mjs +79 -1
- package/src/cli.mjs +365 -36
- package/src/prompt.mjs +79 -0
- package/src/upload.mjs +11 -5
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
// ShieldFive CLI — the agent process.
|
|
2
|
+
//
|
|
3
|
+
// Holds one signed-in session and the unwrapped vault root key, in memory only,
|
|
4
|
+
// and serves the write-only protocol in protocol.mjs on a Unix domain socket.
|
|
5
|
+
// See docs/agent-design.md for why it exists and what it will never do.
|
|
6
|
+
|
|
7
|
+
import { createHmac, randomUUID } from 'node:crypto'
|
|
8
|
+
import { chmod, open, readFile, rm, stat } from 'node:fs/promises'
|
|
9
|
+
import { connect, createServer } from 'node:net'
|
|
10
|
+
import { basename, dirname, join } from 'node:path'
|
|
11
|
+
|
|
12
|
+
import { refreshAccessToken, revokeSession } from '../auth.mjs'
|
|
13
|
+
import { MANIFEST_NAME, scanFiles } from '../sync.mjs'
|
|
14
|
+
import { appendEntry, classify, deriveLedgerKey, ledgerPath, macFile, readEntries } from './ledger.mjs'
|
|
15
|
+
import { ensurePrivateDir, ledgerDir } from './paths.mjs'
|
|
16
|
+
import { encode, fail, lineSplitter, ok, parseRequest } from './protocol.mjs'
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_IDLE_MS = 8 * 60 * 60 * 1000
|
|
19
|
+
|
|
20
|
+
// Refresh a little before expiry rather than on a 401, so a long upload does
|
|
21
|
+
// not start with a token that dies halfway through.
|
|
22
|
+
const REFRESH_MARGIN_S = 120
|
|
23
|
+
const REFRESH_TIMEOUT_MS = 15_000
|
|
24
|
+
|
|
25
|
+
// Everything stop() does on the network — refreshing an expired token and
|
|
26
|
+
// revoking the session — shares one budget. Keys are wiped before it starts.
|
|
27
|
+
const STOP_NETWORK_BUDGET_MS = 5_000
|
|
28
|
+
|
|
29
|
+
// Only these count as use for the idle lock. A status probe does no work; if it
|
|
30
|
+
// counted, a shell prompt or a health check polling `sf status` would keep the
|
|
31
|
+
// agent unlocked forever.
|
|
32
|
+
const USE_OPS = new Set(['upload', 'sync', 'verify'])
|
|
33
|
+
|
|
34
|
+
class AgentError extends Error {
|
|
35
|
+
constructor(code, message) {
|
|
36
|
+
super(message)
|
|
37
|
+
this.code = code
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Resolve true when something accepts a connection on `path`. */
|
|
42
|
+
export function socketAnswers(path, { timeoutMs = 500 } = {}) {
|
|
43
|
+
return new Promise((resolve) => {
|
|
44
|
+
const s = connect({ path })
|
|
45
|
+
const timer = setTimeout(() => {
|
|
46
|
+
s.destroy()
|
|
47
|
+
resolve(false)
|
|
48
|
+
}, timeoutMs)
|
|
49
|
+
s.on('connect', () => {
|
|
50
|
+
clearTimeout(timer)
|
|
51
|
+
s.destroy()
|
|
52
|
+
resolve(true)
|
|
53
|
+
})
|
|
54
|
+
s.on('error', () => {
|
|
55
|
+
clearTimeout(timer)
|
|
56
|
+
resolve(false)
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function pidAlive(pid) {
|
|
62
|
+
try {
|
|
63
|
+
process.kill(pid, 0)
|
|
64
|
+
return true
|
|
65
|
+
} catch (err) {
|
|
66
|
+
// EPERM: the process exists but belongs to someone else. Treat it as alive.
|
|
67
|
+
return err.code === 'EPERM'
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function createAgent({
|
|
72
|
+
session,
|
|
73
|
+
rootKey,
|
|
74
|
+
config,
|
|
75
|
+
socket,
|
|
76
|
+
home,
|
|
77
|
+
device,
|
|
78
|
+
idleMs = DEFAULT_IDLE_MS,
|
|
79
|
+
uploadFile,
|
|
80
|
+
fetchImpl = fetch,
|
|
81
|
+
now = () => Date.now(),
|
|
82
|
+
log = () => {},
|
|
83
|
+
onStop = () => {},
|
|
84
|
+
stopBudgetMs = STOP_NETWORK_BUDGET_MS,
|
|
85
|
+
}) {
|
|
86
|
+
if (!session?.refreshToken) {
|
|
87
|
+
throw new AgentError(
|
|
88
|
+
'no_refresh_token',
|
|
89
|
+
'Sign-in did not produce a refresh token for the stepped-up session, so ' +
|
|
90
|
+
'the agent would stop working within the hour. Run sf login again.',
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
if (!session.userId) throw new AgentError('no_account', 'Sign-in did not report an account id.')
|
|
94
|
+
if (!(rootKey instanceof Uint8Array) || rootKey.length !== 32) {
|
|
95
|
+
throw new AgentError('bad_key', 'The agent needs the 32-byte vault root key.')
|
|
96
|
+
}
|
|
97
|
+
if (typeof uploadFile !== 'function') throw new AgentError('bad_config', 'uploadFile is required.')
|
|
98
|
+
if (typeof device !== 'string' || !device) throw new AgentError('bad_config', 'A device id is required.')
|
|
99
|
+
|
|
100
|
+
// Copies this agent owns and overwrites on stop.
|
|
101
|
+
const key = Buffer.from(rootKey)
|
|
102
|
+
const ledgerKey = deriveLedgerKey(key)
|
|
103
|
+
const ledgerFile = ledgerPath(ledgerDir(home), session.userId)
|
|
104
|
+
const lockFile = join(dirname(socket), 'agent.lock')
|
|
105
|
+
const lockToken = `${process.pid}:${randomUUID()}`
|
|
106
|
+
|
|
107
|
+
let tokens = {
|
|
108
|
+
access: session.accessToken,
|
|
109
|
+
refresh: session.refreshToken,
|
|
110
|
+
expiresAt: session.expiresAt,
|
|
111
|
+
}
|
|
112
|
+
let refreshing = null
|
|
113
|
+
let server = null
|
|
114
|
+
let idleTimer = null
|
|
115
|
+
let inFlight = 0
|
|
116
|
+
let stopping = null
|
|
117
|
+
let idleDeadline = 0
|
|
118
|
+
|
|
119
|
+
function touch() {
|
|
120
|
+
clearTimeout(idleTimer)
|
|
121
|
+
idleDeadline = now() + idleMs
|
|
122
|
+
idleTimer = setTimeout(() => {
|
|
123
|
+
if (inFlight > 0) return touch()
|
|
124
|
+
stop('idle')
|
|
125
|
+
}, idleMs)
|
|
126
|
+
idleTimer.unref?.()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function assertRunning(what) {
|
|
130
|
+
if (stopping) {
|
|
131
|
+
throw new AgentError('locked', `The agent was locked or logged out ${what}.`)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function accessToken() {
|
|
136
|
+
assertRunning('before this request could run')
|
|
137
|
+
if (tokens.expiresAt && now() / 1000 < tokens.expiresAt - REFRESH_MARGIN_S) {
|
|
138
|
+
return tokens.access
|
|
139
|
+
}
|
|
140
|
+
// Single flight. Supabase rotates refresh tokens, and presenting the same
|
|
141
|
+
// one twice outside its short grace window revokes the whole session, so
|
|
142
|
+
// three requests arriving at an expired token must share one refresh.
|
|
143
|
+
refreshing ??= refreshAccessToken({
|
|
144
|
+
supabaseUrl: config.supabaseUrl,
|
|
145
|
+
anonKey: config.anonKey,
|
|
146
|
+
refreshToken: tokens.refresh,
|
|
147
|
+
fetchImpl,
|
|
148
|
+
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
|
|
149
|
+
})
|
|
150
|
+
.then((s) => {
|
|
151
|
+
// A refresh that lands after stop() wiped the tokens must not put them
|
|
152
|
+
// back.
|
|
153
|
+
if (!stopping) tokens = { access: s.accessToken, refresh: s.refreshToken, expiresAt: s.expiresAt }
|
|
154
|
+
return s.accessToken
|
|
155
|
+
})
|
|
156
|
+
.catch((err) => {
|
|
157
|
+
if (err.status === 400 || err.status === 401) {
|
|
158
|
+
// Revoked elsewhere, or reused. Nothing this agent holds will work
|
|
159
|
+
// again, so stop instead of failing every request until idle.
|
|
160
|
+
stop('session_revoked', { revoke: false })
|
|
161
|
+
throw new AgentError('session_revoked', 'This session was signed out. Run sf login again.')
|
|
162
|
+
}
|
|
163
|
+
throw err
|
|
164
|
+
})
|
|
165
|
+
.finally(() => {
|
|
166
|
+
refreshing = null
|
|
167
|
+
})
|
|
168
|
+
return refreshing
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function verifyFileIds(ids) {
|
|
172
|
+
const token = await accessToken()
|
|
173
|
+
const res = await fetchImpl(new URL('/api/mobile/media/verify', config.apiBaseUrl), {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
176
|
+
body: JSON.stringify({ fileIds: ids }),
|
|
177
|
+
})
|
|
178
|
+
const body = await res.json().catch(() => ({}))
|
|
179
|
+
if (!res.ok) {
|
|
180
|
+
// Fail the whole request rather than reporting everything `missing`. A
|
|
181
|
+
// verification that did not happen is not an answer of either kind.
|
|
182
|
+
throw new AgentError(
|
|
183
|
+
'verify_failed',
|
|
184
|
+
`The server could not verify backups (HTTP ${res.status}${body.code ? `, ${body.code}` : ''}). ` +
|
|
185
|
+
'Nothing was classified.',
|
|
186
|
+
)
|
|
187
|
+
}
|
|
188
|
+
return Array.isArray(body.verified) ? body.verified : []
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function upload(path) {
|
|
192
|
+
const before = await stat(path)
|
|
193
|
+
if (!before.isFile()) throw new AgentError('not_a_file', `${path} is not a regular file.`)
|
|
194
|
+
const token = await accessToken()
|
|
195
|
+
|
|
196
|
+
// The MAC recorded is the MAC of exactly the bytes that were encrypted, fed
|
|
197
|
+
// in chunk by chunk as uploadFile reads them. Hashing the file before and
|
|
198
|
+
// after the upload cannot see a change that is made and undone while it is
|
|
199
|
+
// being read: both reads agree, and the vault holds something else.
|
|
200
|
+
const hmac = createHmac('sha256', ledgerKey)
|
|
201
|
+
let streamed = 0
|
|
202
|
+
|
|
203
|
+
// uploadFile gets its own copy of the key, wiped when it returns. If a
|
|
204
|
+
// logout zeroed the agent's copy while an upload was still wrapping the
|
|
205
|
+
// file's content key, that key would be wrapped under zeros and the file in
|
|
206
|
+
// the vault would never decrypt.
|
|
207
|
+
const uploadKey = Buffer.from(key)
|
|
208
|
+
let fileId
|
|
209
|
+
try {
|
|
210
|
+
;({ fileId } = await uploadFile({
|
|
211
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
212
|
+
accessToken: token,
|
|
213
|
+
rootKey: uploadKey,
|
|
214
|
+
name: basename(path),
|
|
215
|
+
path,
|
|
216
|
+
size: before.size,
|
|
217
|
+
onPlaintextChunk: (chunk) => {
|
|
218
|
+
hmac.update(chunk)
|
|
219
|
+
streamed += chunk.length
|
|
220
|
+
},
|
|
221
|
+
}))
|
|
222
|
+
} finally {
|
|
223
|
+
uploadKey.fill(0)
|
|
224
|
+
}
|
|
225
|
+
const mac = hmac.digest('hex')
|
|
226
|
+
|
|
227
|
+
assertRunning(`while ${path} was uploading. It reached the vault but is not recorded, so sf verify will not vouch for it`)
|
|
228
|
+
if (streamed !== before.size) {
|
|
229
|
+
throw new AgentError(
|
|
230
|
+
'not_recorded',
|
|
231
|
+
`${path} changed size while it was uploading (${before.size} bytes expected, ${streamed} read). ` +
|
|
232
|
+
'It is not recorded as a backup.',
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
await appendEntry(
|
|
237
|
+
ledgerFile,
|
|
238
|
+
{
|
|
239
|
+
path,
|
|
240
|
+
size: streamed,
|
|
241
|
+
mtimeMs: before.mtimeMs,
|
|
242
|
+
mac,
|
|
243
|
+
fileId,
|
|
244
|
+
uploadedAt: new Date(now()).toISOString(),
|
|
245
|
+
device,
|
|
246
|
+
},
|
|
247
|
+
{ ledgerKey },
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
// Whether the file on disk now is the one that was uploaded. It does not
|
|
251
|
+
// change what was recorded, which describes the upload; it tells push and
|
|
252
|
+
// sync whether this file needs uploading again.
|
|
253
|
+
let matchesFileNow = false
|
|
254
|
+
if (!stopping) {
|
|
255
|
+
try {
|
|
256
|
+
matchesFileNow = (await macFile(path, ledgerKey)) === mac
|
|
257
|
+
} catch {
|
|
258
|
+
// Unreadable now: leave it false.
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return { fileId, size: streamed, matchesFileNow, mac }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function sync(folder) {
|
|
265
|
+
const st = await stat(folder)
|
|
266
|
+
if (!st.isDirectory()) throw new AgentError('not_a_directory', `${folder} is not a directory.`)
|
|
267
|
+
|
|
268
|
+
const files = await scanFiles(folder, { exclude: [MANIFEST_NAME] })
|
|
269
|
+
const { entries } = await readEntries(ledgerFile, { ledgerKey })
|
|
270
|
+
const done = new Set(entries.filter((e) => e.device === device).map((e) => `${e.path}\u0000${e.mac}`))
|
|
271
|
+
|
|
272
|
+
let uploaded = 0
|
|
273
|
+
let skipped = 0
|
|
274
|
+
let failed = 0
|
|
275
|
+
let changed = 0
|
|
276
|
+
const errors = []
|
|
277
|
+
for (const f of files) {
|
|
278
|
+
assertRunning(`during sync, after uploading ${uploaded} file(s)`)
|
|
279
|
+
try {
|
|
280
|
+
const mac = await macFile(f.path, ledgerKey)
|
|
281
|
+
if (done.has(`${f.path}\u0000${mac}`)) {
|
|
282
|
+
skipped++
|
|
283
|
+
continue
|
|
284
|
+
}
|
|
285
|
+
const r = await upload(f.path)
|
|
286
|
+
uploaded++
|
|
287
|
+
done.add(`${f.path}\u0000${r.mac}`)
|
|
288
|
+
if (!r.matchesFileNow) changed++
|
|
289
|
+
} catch (err) {
|
|
290
|
+
if (err.code === 'session_revoked' || err.code === 'locked') throw err
|
|
291
|
+
failed++
|
|
292
|
+
errors.push({ path: f.path, message: err.message })
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return { uploaded, skipped, failed, changed, errors }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function handle(req) {
|
|
299
|
+
switch (req.op) {
|
|
300
|
+
case 'status':
|
|
301
|
+
return {
|
|
302
|
+
unlocked: !stopping,
|
|
303
|
+
account: session.userId,
|
|
304
|
+
idleLocksInSec: Math.max(0, Math.round((idleDeadline - now()) / 1000)),
|
|
305
|
+
pid: process.pid,
|
|
306
|
+
}
|
|
307
|
+
case 'upload': {
|
|
308
|
+
// The MAC stays in the ledger. A process on the socket has no use for a
|
|
309
|
+
// keyed digest.
|
|
310
|
+
const { fileId, size, matchesFileNow } = await upload(req.args.path)
|
|
311
|
+
return { fileId, size, matchesFileNow }
|
|
312
|
+
}
|
|
313
|
+
case 'sync':
|
|
314
|
+
return sync(req.args.folder)
|
|
315
|
+
case 'verify': {
|
|
316
|
+
const { entries } = await readEntries(ledgerFile, { ledgerKey })
|
|
317
|
+
return classify(req.args.paths, { entries, ledgerKey, verifyFileIds, device })
|
|
318
|
+
}
|
|
319
|
+
case 'lock': {
|
|
320
|
+
const { revoked, status } = await stop('lock')
|
|
321
|
+
return { locked: true, sessionRevoked: revoked, revokeStatus: status }
|
|
322
|
+
}
|
|
323
|
+
case 'logout': {
|
|
324
|
+
const everywhere = req.args.everywhere === true
|
|
325
|
+
const { revoked, status } = await stop('logout', { everywhere })
|
|
326
|
+
return { loggedOut: true, everywhere, sessionRevoked: revoked, revokeStatus: status }
|
|
327
|
+
}
|
|
328
|
+
default:
|
|
329
|
+
throw new AgentError('unknown_op', `Unknown operation ${req.op}.`)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function onConnection(conn) {
|
|
334
|
+
conn.setEncoding('utf8')
|
|
335
|
+
conn.on('error', () => {})
|
|
336
|
+
let handled = false
|
|
337
|
+
|
|
338
|
+
const reply = (message) => {
|
|
339
|
+
if (!conn.destroyed) conn.end(encode(message))
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const feed = lineSplitter(async (line) => {
|
|
343
|
+
// One request per connection. Anything after the first line is ignored.
|
|
344
|
+
if (handled) return
|
|
345
|
+
handled = true
|
|
346
|
+
|
|
347
|
+
let req
|
|
348
|
+
try {
|
|
349
|
+
req = parseRequest(line)
|
|
350
|
+
} catch (err) {
|
|
351
|
+
return reply(fail(null, err.code ?? 'bad_request', err.message))
|
|
352
|
+
}
|
|
353
|
+
if (stopping && req.op !== 'status') {
|
|
354
|
+
return reply(fail(req.id, 'locked', 'The agent is locked. Run sf login.'))
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
inFlight++
|
|
358
|
+
let succeeded = false
|
|
359
|
+
try {
|
|
360
|
+
reply(ok(req.id, await handle(req)))
|
|
361
|
+
succeeded = true
|
|
362
|
+
} catch (err) {
|
|
363
|
+
reply(fail(req.id, err.code ?? 'error', err.message))
|
|
364
|
+
} finally {
|
|
365
|
+
inFlight--
|
|
366
|
+
if (!stopping && succeeded && USE_OPS.has(req.op)) touch()
|
|
367
|
+
}
|
|
368
|
+
})
|
|
369
|
+
|
|
370
|
+
conn.on('data', (chunk) => {
|
|
371
|
+
try {
|
|
372
|
+
feed(chunk)
|
|
373
|
+
} catch (err) {
|
|
374
|
+
reply(fail(null, err.code ?? 'bad_request', err.message))
|
|
375
|
+
}
|
|
376
|
+
})
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function acquireLock() {
|
|
380
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
381
|
+
try {
|
|
382
|
+
const handle = await open(lockFile, 'wx', 0o600)
|
|
383
|
+
try {
|
|
384
|
+
await handle.writeFile(lockToken)
|
|
385
|
+
} finally {
|
|
386
|
+
await handle.close()
|
|
387
|
+
}
|
|
388
|
+
return
|
|
389
|
+
} catch (err) {
|
|
390
|
+
if (err.code !== 'EEXIST') throw err
|
|
391
|
+
}
|
|
392
|
+
const held = (await readFile(lockFile, 'utf8').catch(() => '')).trim()
|
|
393
|
+
const [pidText] = held.split(':')
|
|
394
|
+
const pid = Number(pidText)
|
|
395
|
+
// Same process, different agent (tests do this): alive. Another process:
|
|
396
|
+
// alive if it still runs. Anything else was left by an agent that died.
|
|
397
|
+
const alive = pid === process.pid ? held !== lockToken : pid > 0 && pidAlive(pid)
|
|
398
|
+
if (alive) {
|
|
399
|
+
throw new AgentError('already_running', 'An agent is already running. Run sf status or sf logout.')
|
|
400
|
+
}
|
|
401
|
+
await rm(lockFile, { force: true })
|
|
402
|
+
}
|
|
403
|
+
throw new AgentError('already_running', 'Another agent is starting at the same moment. Try again.')
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async function releaseLock() {
|
|
407
|
+
const held = (await readFile(lockFile, 'utf8').catch(() => '')).trim()
|
|
408
|
+
// Only ever remove our own lock. A lock that belongs to a newer agent is not
|
|
409
|
+
// ours to release.
|
|
410
|
+
if (held === lockToken) await rm(lockFile, { force: true })
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async function revokeHeld(held, everywhere, signal) {
|
|
414
|
+
let access = held.access
|
|
415
|
+
const expired = !held.expiresAt || now() / 1000 >= held.expiresAt - REFRESH_MARGIN_S
|
|
416
|
+
if (expired && held.refresh) {
|
|
417
|
+
try {
|
|
418
|
+
access = (
|
|
419
|
+
await refreshAccessToken({
|
|
420
|
+
supabaseUrl: config.supabaseUrl,
|
|
421
|
+
anonKey: config.anonKey,
|
|
422
|
+
refreshToken: held.refresh,
|
|
423
|
+
fetchImpl,
|
|
424
|
+
signal,
|
|
425
|
+
})
|
|
426
|
+
).accessToken
|
|
427
|
+
} catch {
|
|
428
|
+
// Fall back to the token we hold; the revoke says whether it worked.
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return revokeSession({
|
|
432
|
+
supabaseUrl: config.supabaseUrl,
|
|
433
|
+
anonKey: config.anonKey,
|
|
434
|
+
accessToken: access,
|
|
435
|
+
scope: everywhere ? 'global' : 'local',
|
|
436
|
+
fetchImpl,
|
|
437
|
+
signal,
|
|
438
|
+
})
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function stop(reason, { revoke = true, everywhere = false } = {}) {
|
|
442
|
+
if (stopping) return stopping
|
|
443
|
+
stopping = (async () => {
|
|
444
|
+
clearTimeout(idleTimer)
|
|
445
|
+
// Stop accepting connections. Node removes the socket file when a Unix
|
|
446
|
+
// server closes; nothing here deletes that path by name, because by the
|
|
447
|
+
// time a slow revoke finishes a newer agent may be listening there.
|
|
448
|
+
server?.close()
|
|
449
|
+
|
|
450
|
+
// Decryption material first, before anything touches the network, so a
|
|
451
|
+
// revoke that hangs cannot keep the vault key alive while it waits. An
|
|
452
|
+
// upload already running has its own copy, wiped when it returns.
|
|
453
|
+
key.fill(0)
|
|
454
|
+
ledgerKey.fill(0)
|
|
455
|
+
const held = tokens
|
|
456
|
+
tokens = { access: null, refresh: null, expiresAt: null }
|
|
457
|
+
|
|
458
|
+
let result = { revoked: false, status: 0 }
|
|
459
|
+
if (revoke) {
|
|
460
|
+
// A plain timer rather than AbortSignal.timeout: that one does not keep
|
|
461
|
+
// the process alive, and with the server closed nothing else might. The
|
|
462
|
+
// race means a request that ignores the signal cannot hold stop() open.
|
|
463
|
+
const controller = new AbortController()
|
|
464
|
+
const timer = setTimeout(() => controller.abort(), stopBudgetMs)
|
|
465
|
+
const outOfTime = new Promise((resolve) =>
|
|
466
|
+
controller.signal.addEventListener('abort', () => resolve({ revoked: false, status: 0 }), { once: true }),
|
|
467
|
+
)
|
|
468
|
+
try {
|
|
469
|
+
result = await Promise.race([revokeHeld(held, everywhere, controller.signal), outOfTime])
|
|
470
|
+
} catch {
|
|
471
|
+
// Unreachable. status stays 0, which callers report as "could not reach
|
|
472
|
+
// the server", distinct from a refusal.
|
|
473
|
+
} finally {
|
|
474
|
+
clearTimeout(timer)
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
await releaseLock()
|
|
479
|
+
log(`agent stopped (${reason})`)
|
|
480
|
+
onStop(reason, result)
|
|
481
|
+
return result
|
|
482
|
+
})()
|
|
483
|
+
return stopping
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return {
|
|
487
|
+
async start() {
|
|
488
|
+
await ensurePrivateDir(dirname(socket))
|
|
489
|
+
await ensurePrivateDir(ledgerDir(home))
|
|
490
|
+
// The lock, not the socket, decides who may start. Checking the socket and
|
|
491
|
+
// then removing a stale one left a window in which two agents could both
|
|
492
|
+
// conclude nothing was listening.
|
|
493
|
+
await acquireLock()
|
|
494
|
+
try {
|
|
495
|
+
if (await socketAnswers(socket)) {
|
|
496
|
+
throw new AgentError('already_running', 'An agent is already running. Run sf status or sf logout.')
|
|
497
|
+
}
|
|
498
|
+
// We hold the lock and nothing answered, so whatever is at this path is
|
|
499
|
+
// a leftover from an agent that died.
|
|
500
|
+
await rm(socket, { force: true })
|
|
501
|
+
|
|
502
|
+
server = createServer(onConnection)
|
|
503
|
+
await new Promise((resolve, reject) => {
|
|
504
|
+
server.once('error', reject)
|
|
505
|
+
server.listen(socket, () => {
|
|
506
|
+
server.off('error', reject)
|
|
507
|
+
resolve()
|
|
508
|
+
})
|
|
509
|
+
})
|
|
510
|
+
// The directory is already 0700; this is the second lock on the same door.
|
|
511
|
+
await chmod(socket, 0o600)
|
|
512
|
+
} catch (err) {
|
|
513
|
+
server?.close()
|
|
514
|
+
await releaseLock()
|
|
515
|
+
throw err
|
|
516
|
+
}
|
|
517
|
+
touch()
|
|
518
|
+
log(`agent listening on ${socket}`)
|
|
519
|
+
},
|
|
520
|
+
stop,
|
|
521
|
+
get stopped() {
|
|
522
|
+
return Boolean(stopping)
|
|
523
|
+
},
|
|
524
|
+
}
|
|
525
|
+
}
|
package/src/auth.mjs
CHANGED
|
@@ -102,5 +102,83 @@ export async function signIn({
|
|
|
102
102
|
}
|
|
103
103
|
|
|
104
104
|
const aal2Token = await stepUpMfaIfRequired({ supabase, getTotpCode })
|
|
105
|
-
|
|
105
|
+
|
|
106
|
+
// The refresh token has to come from the session that was stepped up.
|
|
107
|
+
// Refreshing the pre-step-up session mints aal1 tokens, and every upload
|
|
108
|
+
// route would start answering 403 once the first access token expired.
|
|
109
|
+
// supabase-js replaces its in-memory session on mfa.verify, so read it back
|
|
110
|
+
// and only trust it if it is the session that produced the aal2 token. If it
|
|
111
|
+
// is not, return no refresh token: the agent refuses to start rather than
|
|
112
|
+
// running on a credential that will fail an hour later.
|
|
113
|
+
let session = data.session
|
|
114
|
+
if (aal2Token) {
|
|
115
|
+
const { data: current } = await supabase.auth.getSession()
|
|
116
|
+
session = current?.session?.access_token === aal2Token ? current.session : null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
accessToken: aal2Token ?? aal1Token,
|
|
121
|
+
refreshToken: session?.refresh_token ?? null,
|
|
122
|
+
expiresAt: session?.expires_at ?? null,
|
|
123
|
+
userId: session?.user?.id ?? data.user?.id ?? null,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Exchange a refresh token for a new session. Supabase rotates refresh tokens,
|
|
128
|
+
// so the caller must replace the one it holds with the one returned, and must
|
|
129
|
+
// never run two refreshes with the same token at once: reuse outside the
|
|
130
|
+
// server's short grace window revokes the whole session.
|
|
131
|
+
export async function refreshAccessToken({
|
|
132
|
+
supabaseUrl,
|
|
133
|
+
anonKey,
|
|
134
|
+
refreshToken,
|
|
135
|
+
fetchImpl = fetch,
|
|
136
|
+
signal,
|
|
137
|
+
}) {
|
|
138
|
+
if (!refreshToken) {
|
|
139
|
+
throw new Error('No refresh token is held. Run sf login again.')
|
|
140
|
+
}
|
|
141
|
+
const res = await fetchImpl(new URL('/auth/v1/token?grant_type=refresh_token', supabaseUrl), {
|
|
142
|
+
method: 'POST',
|
|
143
|
+
headers: { apikey: anonKey, 'Content-Type': 'application/json' },
|
|
144
|
+
body: JSON.stringify({ refresh_token: refreshToken }),
|
|
145
|
+
signal,
|
|
146
|
+
})
|
|
147
|
+
const body = await res.json().catch(() => ({}))
|
|
148
|
+
if (!res.ok || !body.access_token || !body.refresh_token) {
|
|
149
|
+
const reason = body.error_description ?? body.msg ?? body.error ?? 'no session returned'
|
|
150
|
+
const err = new Error(`Session refresh failed (HTTP ${res.status}): ${reason}`)
|
|
151
|
+
err.status = res.status
|
|
152
|
+
throw err
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
accessToken: body.access_token,
|
|
156
|
+
refreshToken: body.refresh_token,
|
|
157
|
+
expiresAt: body.expires_at ?? Math.floor(Date.now() / 1000) + (body.expires_in ?? 3600),
|
|
158
|
+
userId: body.user?.id ?? null,
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Sign a session out on the server. Sessions on the production project are not
|
|
163
|
+
// time-boxed, so a refresh token that is merely forgotten stays valid until
|
|
164
|
+
// someone revokes it; this is that revocation. `scope: 'local'` ends only this
|
|
165
|
+
// session. `scope: 'global'` ends every session on the account, including the
|
|
166
|
+
// user's browser and phone, and is the only way to end a session this client no
|
|
167
|
+
// longer holds a token for.
|
|
168
|
+
export async function revokeSession({
|
|
169
|
+
supabaseUrl,
|
|
170
|
+
anonKey,
|
|
171
|
+
accessToken,
|
|
172
|
+
scope = 'local',
|
|
173
|
+
fetchImpl = fetch,
|
|
174
|
+
signal,
|
|
175
|
+
}) {
|
|
176
|
+
if (scope !== 'local' && scope !== 'global') throw new Error(`Unknown sign-out scope ${scope}`)
|
|
177
|
+
if (!accessToken) return { revoked: false, status: 0 }
|
|
178
|
+
const res = await fetchImpl(new URL(`/auth/v1/logout?scope=${scope}`, supabaseUrl), {
|
|
179
|
+
method: 'POST',
|
|
180
|
+
headers: { apikey: anonKey, Authorization: `Bearer ${accessToken}` },
|
|
181
|
+
signal,
|
|
182
|
+
})
|
|
183
|
+
return { revoked: res.status === 204 || res.status === 200, status: res.status }
|
|
106
184
|
}
|