@shieldfive/cli 0.2.1 → 0.3.1

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/src/auth.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // ShieldFive CLI — authentication.
2
2
  //
3
- // Signs in via Supabase to obtain a Bearer access token, elevating to AAL2 when
3
+ // Signs in through ShieldFive's version-aware login route to obtain a Bearer
4
+ // session, then installs it in Supabase and elevates to AAL2 when
4
5
  // the account has two-factor authentication (TOTP) enabled. The upload routes
5
6
  // accept this token, and their server-side MFA gate requires an AAL2 token for
6
7
  // enrolled accounts — so the step-up here is what makes `sf push` / `sf sync`
@@ -11,6 +12,7 @@
11
12
  // via getAuthenticatorAssuranceLevel.
12
13
 
13
14
  import { createClient } from '@supabase/supabase-js'
15
+ import { buildSignInCredentials } from './loginSecret.mjs'
14
16
 
15
17
  // If the account requires an AAL2 step-up, run the TOTP challenge/verify flow
16
18
  // and return the elevated access token. Returns null when no step-up is needed
@@ -77,24 +79,48 @@ export async function stepUpMfaIfRequired({ supabase, getTotpCode }) {
77
79
  }
78
80
 
79
81
  export async function signIn({
82
+ apiBaseUrl,
80
83
  supabaseUrl,
81
84
  anonKey,
82
85
  email,
83
86
  password,
84
87
  getTotpCode,
88
+ fetchImpl = fetch,
89
+ createClientImpl = createClient,
85
90
  }) {
86
- const supabase = createClient(supabaseUrl, anonKey, {
91
+ // The raw password is never handed to Supabase directly. The salt lookup
92
+ // decides what the version-aware login route receives: only the derived
93
+ // login secret for a version-2 account; the password only for an account the
94
+ // server affirmatively reported as version 1. test/auth.noPasswordLeak.test.mjs
95
+ // pins this across every path.
96
+ email = String(email ?? '').trim().toLowerCase()
97
+ const credentials = await buildSignInCredentials({ apiBaseUrl, email, password, fetchImpl })
98
+ let response
99
+ try {
100
+ response = await fetchImpl(new URL('/api/mobile/auth/login', apiBaseUrl), {
101
+ method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
102
+ body: JSON.stringify({ email, ...credentials }), signal: AbortSignal.timeout(30_000),
103
+ })
104
+ } catch {
105
+ throw new Error('Sign-in failed: could not reach ShieldFive. Check your connection and try again.')
106
+ }
107
+ const payload = await response.json().catch(() => null)
108
+ if (!response.ok || typeof payload?.accessToken !== 'string' || !payload.accessToken ||
109
+ typeof payload?.refreshToken !== 'string' || !payload.refreshToken) {
110
+ throw new Error(response.status === 429 ? 'Too many sign-in attempts. Try again shortly.' : 'Sign-in failed. Check your credentials and try again.')
111
+ }
112
+ const supabase = createClientImpl(supabaseUrl, anonKey, {
87
113
  auth: {
88
114
  persistSession: false,
89
115
  autoRefreshToken: false,
90
116
  detectSessionInUrl: false,
91
117
  },
92
118
  })
93
- const { data, error } = await supabase.auth.signInWithPassword({
94
- email,
95
- password,
119
+ const { data, error } = await supabase.auth.setSession({
120
+ access_token: payload.accessToken,
121
+ refresh_token: payload.refreshToken,
96
122
  })
97
- if (error) throw new Error(`Sign-in failed: ${error.message}`)
123
+ if (error) throw new Error('Could not establish the sign-in session. Please try again.')
98
124
 
99
125
  const aal1Token = data.session?.access_token
100
126
  if (!aal1Token) {
@@ -102,5 +128,83 @@ export async function signIn({
102
128
  }
103
129
 
104
130
  const aal2Token = await stepUpMfaIfRequired({ supabase, getTotpCode })
105
- return { accessToken: aal2Token ?? aal1Token }
131
+
132
+ // The refresh token has to come from the session that was stepped up.
133
+ // Refreshing the pre-step-up session mints aal1 tokens, and every upload
134
+ // route would start answering 403 once the first access token expired.
135
+ // supabase-js replaces its in-memory session on mfa.verify, so read it back
136
+ // and only trust it if it is the session that produced the aal2 token. If it
137
+ // is not, return no refresh token: the agent refuses to start rather than
138
+ // running on a credential that will fail an hour later.
139
+ let session = data.session
140
+ if (aal2Token) {
141
+ const { data: current } = await supabase.auth.getSession()
142
+ session = current?.session?.access_token === aal2Token ? current.session : null
143
+ }
144
+
145
+ return {
146
+ accessToken: aal2Token ?? aal1Token,
147
+ refreshToken: session?.refresh_token ?? null,
148
+ expiresAt: session?.expires_at ?? null,
149
+ userId: session?.user?.id ?? data.user?.id ?? null,
150
+ }
151
+ }
152
+
153
+ // Exchange a refresh token for a new session. Supabase rotates refresh tokens,
154
+ // so the caller must replace the one it holds with the one returned, and must
155
+ // never run two refreshes with the same token at once: reuse outside the
156
+ // server's short grace window revokes the whole session.
157
+ export async function refreshAccessToken({
158
+ supabaseUrl,
159
+ anonKey,
160
+ refreshToken,
161
+ fetchImpl = fetch,
162
+ signal,
163
+ }) {
164
+ if (!refreshToken) {
165
+ throw new Error('No refresh token is held. Run sf login again.')
166
+ }
167
+ const res = await fetchImpl(new URL('/auth/v1/token?grant_type=refresh_token', supabaseUrl), {
168
+ method: 'POST',
169
+ headers: { apikey: anonKey, 'Content-Type': 'application/json' },
170
+ body: JSON.stringify({ refresh_token: refreshToken }),
171
+ signal,
172
+ })
173
+ const body = await res.json().catch(() => ({}))
174
+ if (!res.ok || !body.access_token || !body.refresh_token) {
175
+ const reason = body.error_description ?? body.msg ?? body.error ?? 'no session returned'
176
+ const err = new Error(`Session refresh failed (HTTP ${res.status}): ${reason}`)
177
+ err.status = res.status
178
+ throw err
179
+ }
180
+ return {
181
+ accessToken: body.access_token,
182
+ refreshToken: body.refresh_token,
183
+ expiresAt: body.expires_at ?? Math.floor(Date.now() / 1000) + (body.expires_in ?? 3600),
184
+ userId: body.user?.id ?? null,
185
+ }
186
+ }
187
+
188
+ // Sign a session out on the server. Sessions on the production project are not
189
+ // time-boxed, so a refresh token that is merely forgotten stays valid until
190
+ // someone revokes it; this is that revocation. `scope: 'local'` ends only this
191
+ // session. `scope: 'global'` ends every session on the account, including the
192
+ // user's browser and phone, and is the only way to end a session this client no
193
+ // longer holds a token for.
194
+ export async function revokeSession({
195
+ supabaseUrl,
196
+ anonKey,
197
+ accessToken,
198
+ scope = 'local',
199
+ fetchImpl = fetch,
200
+ signal,
201
+ }) {
202
+ if (scope !== 'local' && scope !== 'global') throw new Error(`Unknown sign-out scope ${scope}`)
203
+ if (!accessToken) return { revoked: false, status: 0 }
204
+ const res = await fetchImpl(new URL(`/auth/v1/logout?scope=${scope}`, supabaseUrl), {
205
+ method: 'POST',
206
+ headers: { apikey: anonKey, Authorization: `Bearer ${accessToken}` },
207
+ signal,
208
+ })
209
+ return { revoked: res.status === 204 || res.status === 200, status: res.status }
106
210
  }
package/src/cli.mjs CHANGED
@@ -1,20 +1,24 @@
1
1
  #!/usr/bin/env node
2
- // ShieldFive CLI (`sf`) — scaffold.
2
+ // ShieldFive CLI (`sf`).
3
3
  //
4
4
  // sf encrypt <folder> encrypt each file locally (verified core demo)
5
- // sf push <folder> login -> unlock -> encrypt -> upload once
6
- // sf sync <folder> [--watch] keep the folder mirrored into your vault
5
+ // sf login [--idle=<hours>] sign in once; an agent holds the session in memory
6
+ // sf status is an agent running, and for which account
7
+ // sf logout [--everywhere] revoke the session and stop the agent
8
+ // sf push <folder> encrypt and upload every file, once
9
+ // sf sync <folder> [--watch] upload new and changed files
10
+ // sf verify <file>... is each file safely stored in your vault
7
11
  //
8
- // The offline crypto chain (unlock -> identity -> encrypt) is VERIFIED
9
- // (`npm test`), and the full upload pipeline (direct + multipart) is wired and
10
- // tested. Configure the live commands with env vars (see README) and run them
11
- // against your own ShieldFive account.
12
+ // push and sync use a running agent when there is one. When SF_EMAIL and
13
+ // SF_PASSWORD are set they sign in from those instead, exactly as before, so a
14
+ // script written for one account is never quietly redirected to an agent
15
+ // signed in as another. See docs/agent-design.md.
12
16
 
13
17
  import { webcrypto } from 'node:crypto'
14
18
  import { readFile, readdir, stat } from 'node:fs/promises'
15
- import { join } from 'node:path'
16
- import { createInterface } from 'node:readline'
19
+ import { join, resolve } from 'node:path'
17
20
 
21
+ import { promptHidden, promptLine } from './prompt.mjs'
18
22
  import { deriveVaultIdentity, encryptFileForVault } from './sfCrypto.mjs'
19
23
 
20
24
  function usage() {
@@ -22,16 +26,22 @@ function usage() {
22
26
  [
23
27
  'sf <command>',
24
28
  '',
25
- ' encrypt <folder> encrypt each file in <folder> locally (verified core)',
26
- ' push <folder> login -> unlock -> encrypt -> upload to your vault',
27
- ' sync <folder> [--watch] mirror new/changed files into your vault',
29
+ ' login [--idle=<hours>] sign in once and start an agent (default: locks after 8 h without use)',
30
+ ' status show whether an agent is running',
31
+ ' logout [--everywhere] revoke the session and stop the agent',
32
+ ' --everywhere also signs out your browser and phone',
33
+ ' push <folder> encrypt and upload every file in <folder>',
34
+ ' sync <folder> [--watch] upload new and changed files',
28
35
  ' [--interval=<seconds>] poll interval for --watch (default 5)',
36
+ ' verify <file>... report whether each file is safely in your vault',
37
+ ' encrypt <folder> encrypt each file locally, upload nothing',
38
+ ' inspect <folder> count a migration source recursively; upload nothing',
29
39
  ' --help',
30
40
  '',
31
- 'push / sync need only your ShieldFive account:',
32
- ' SF_EMAIL, SF_PASSWORD [SF_VAULT_PASSWORD if your vault password differs]',
33
- 'If two-factor (TOTP) is enabled, you are prompted for a 6-digit code',
34
- '(or set SF_TOTP_CODE). SF_API_BASE_URL, SF_SUPABASE_URL, SF_SUPABASE_ANON_KEY',
41
+ 'After sf login, push / sync / verify go through the agent and need nothing',
42
+ 'in the environment. Without an agent, or when SF_EMAIL and SF_PASSWORD are',
43
+ 'set, push and sync sign in from those [SF_VAULT_PASSWORD if your vault',
44
+ 'password differs]. SF_API_BASE_URL, SF_SUPABASE_URL, SF_SUPABASE_ANON_KEY',
35
45
  'default to ShieldFive (override only for a development backend).',
36
46
  '',
37
47
  ].join('\n') + '\n',
@@ -76,6 +86,19 @@ const DEFAULTS = {
76
86
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRza2JtanBhbmVoY2tocXprY2xwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzAxMTc3MzEsImV4cCI6MjA4NTY5MzczMX0.AK7K8tyrAWFWgfaa6vvTveqmKiMrL2nY1m7qS9TII9U',
77
87
  }
78
88
 
89
+ function backendConfig() {
90
+ const e = process.env
91
+ return {
92
+ apiBaseUrl: e.SF_API_BASE_URL || DEFAULTS.apiBaseUrl,
93
+ supabaseUrl: e.SF_SUPABASE_URL || DEFAULTS.supabaseUrl,
94
+ anonKey: e.SF_SUPABASE_ANON_KEY || DEFAULTS.anonKey,
95
+ }
96
+ }
97
+
98
+ function envCredentialsSet() {
99
+ return Boolean(process.env.SF_EMAIL && process.env.SF_PASSWORD)
100
+ }
101
+
79
102
  function readLiveConfig() {
80
103
  const e = process.env
81
104
  const email = e.SF_EMAIL
@@ -85,34 +108,20 @@ function readLiveConfig() {
85
108
  if (!password) missing.push('SF_PASSWORD')
86
109
  if (missing.length) {
87
110
  throw new Error(
88
- `this command needs your ShieldFive account: set ${missing.join(' and ')}. ` +
89
- '(SF_API_BASE_URL, SF_SUPABASE_URL, and SF_SUPABASE_ANON_KEY default to ' +
90
- 'ShieldFive; override them only for a development backend.)',
111
+ `this command needs your ShieldFive account: run sf login, or set ` +
112
+ `${missing.join(' and ')}. (SF_API_BASE_URL, SF_SUPABASE_URL, and ` +
113
+ 'SF_SUPABASE_ANON_KEY default to ShieldFive; override them only for a ' +
114
+ 'development backend.)',
91
115
  )
92
116
  }
93
117
  return {
94
- apiBaseUrl: e.SF_API_BASE_URL || DEFAULTS.apiBaseUrl,
95
- supabaseUrl: e.SF_SUPABASE_URL || DEFAULTS.supabaseUrl,
96
- anonKey: e.SF_SUPABASE_ANON_KEY || DEFAULTS.anonKey,
118
+ ...backendConfig(),
97
119
  email,
98
120
  password,
99
121
  vaultPassword: e.SF_VAULT_PASSWORD || password,
100
122
  }
101
123
  }
102
124
 
103
- // Prompt for a single line on the terminal. A TOTP code is short-lived, not a
104
- // long-term secret, so echoing it is fine (unlike the password).
105
- function promptLine(question) {
106
- return new Promise((resolve, reject) => {
107
- const rl = createInterface({ input: process.stdin, output: process.stderr })
108
- rl.question(question, (answer) => {
109
- rl.close()
110
- resolve(answer)
111
- })
112
- rl.on('error', reject)
113
- })
114
- }
115
-
116
125
  // Source a TOTP code for the 2FA step-up: SF_TOTP_CODE if set (handy for
117
126
  // scripting), otherwise prompt interactively. Only invoked when the account
118
127
  // actually requires a step-up.
@@ -135,7 +144,8 @@ async function authAndUnlock(cfg) {
135
144
  const { fetchAndUnlockVault } = await import('./vault.mjs')
136
145
 
137
146
  process.stderr.write('signing in…\n')
138
- const { accessToken } = await signIn({
147
+ const { accessToken, refreshToken, expiresAt } = await signIn({
148
+ apiBaseUrl: cfg.apiBaseUrl,
139
149
  supabaseUrl: cfg.supabaseUrl,
140
150
  anonKey: cfg.anonKey,
141
151
  email: cfg.email,
@@ -149,11 +159,249 @@ async function authAndUnlock(cfg) {
149
159
  accessToken,
150
160
  password: cfg.vaultPassword,
151
161
  })
152
- return { accessToken, rootKey }
162
+ // `sf sync --watch` outlives the access token (about an hour); it refreshes
163
+ // through this, the same exchange the agent uses.
164
+ const refreshSession = async (token) => {
165
+ const { refreshAccessToken } = await import('./auth.mjs')
166
+ return refreshAccessToken({ supabaseUrl: cfg.supabaseUrl, anonKey: cfg.anonKey, refreshToken: token })
167
+ }
168
+ return { accessToken, refreshToken, expiresAt, refreshSession, rootKey }
169
+ }
170
+
171
+ async function runningAgent() {
172
+ const { agentStatus } = await import('./agent/client.mjs')
173
+ const status = await agentStatus()
174
+ return status?.unlocked ? status : null
175
+ }
176
+
177
+ /**
178
+ * Decide how push and sync authenticate. Environment credentials win when both
179
+ * are set: that is how these commands behaved before the agent existed, and it
180
+ * keeps a script that names an account from being redirected to whichever
181
+ * account the agent happens to hold.
182
+ */
183
+ async function chooseAuth() {
184
+ const agent = await runningAgent()
185
+ if (envCredentialsSet()) {
186
+ if (agent) {
187
+ process.stderr.write(
188
+ `SF_EMAIL and SF_PASSWORD are set, so this signs in with them rather than ` +
189
+ `through the running agent (account ${agent.account}). Unset them to use the agent.\n`,
190
+ )
191
+ }
192
+ return { agent: null }
193
+ }
194
+ return { agent }
195
+ }
196
+
197
+ // Start the agent as a detached child and hand it the session over stdin.
198
+ async function launchAgent({ session, rootKey, config, idleMs }) {
199
+ const { spawn } = await import('node:child_process')
200
+ const { fileURLToPath } = await import('node:url')
201
+
202
+ // Only what the agent needs to find its home directory and reach the
203
+ // network. Not SF_PASSWORD, not SF_TOTP_CODE, and nothing else the shell
204
+ // happened to export.
205
+ const env = {}
206
+ for (const name of [
207
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'LANG',
208
+ 'SF_API_BASE_URL', 'SF_SUPABASE_URL', 'SF_SUPABASE_ANON_KEY',
209
+ 'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'NODE_EXTRA_CA_CERTS',
210
+ ]) {
211
+ if (process.env[name]) env[name] = process.env[name]
212
+ }
213
+
214
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '__agent'], {
215
+ detached: true,
216
+ stdio: ['pipe', 'pipe', 'pipe'],
217
+ env,
218
+ })
219
+
220
+ const ready = await new Promise((resolveReady, reject) => {
221
+ let out = ''
222
+ let err = ''
223
+ const timer = setTimeout(() => {
224
+ child.kill()
225
+ reject(new Error(`The agent did not start within 15 s.${err ? ` ${err.trim()}` : ''}`))
226
+ }, 15_000)
227
+
228
+ child.stdout.setEncoding('utf8')
229
+ child.stderr.setEncoding('utf8')
230
+ child.stdout.on('data', (chunk) => {
231
+ out += chunk
232
+ const newline = out.indexOf('\n')
233
+ if (newline === -1) return
234
+ clearTimeout(timer)
235
+ try {
236
+ resolveReady(JSON.parse(out.slice(0, newline)))
237
+ } catch {
238
+ reject(new Error('The agent sent an unreadable start signal.'))
239
+ }
240
+ })
241
+ child.stderr.on('data', (chunk) => {
242
+ err += chunk
243
+ })
244
+ child.on('exit', (code) => {
245
+ clearTimeout(timer)
246
+ reject(new Error(`The agent exited before it was ready (code ${code}).${err ? ` ${err.trim()}` : ''}`))
247
+ })
248
+
249
+ child.stdin.end(
250
+ JSON.stringify({
251
+ session,
252
+ rootKey: Buffer.from(rootKey).toString('base64'),
253
+ config,
254
+ idleMs,
255
+ }),
256
+ )
257
+ })
258
+
259
+ child.stdout.destroy()
260
+ child.stderr.destroy()
261
+ child.unref()
262
+ return ready
263
+ }
264
+
265
+ function readIdle(flags) {
266
+ if (flags.idle === true) {
267
+ throw new Error('--idle needs a value: sf login --idle=<hours>')
268
+ }
269
+ const hours = flags.idle === undefined ? 8 : Number(flags.idle)
270
+ if (!Number.isFinite(hours) || hours * 60 < 1 || hours > 168) {
271
+ throw new Error('--idle must be a number of hours from 1 minute (0.0167) to 168')
272
+ }
273
+ return { hours, ms: Math.round(hours * 3_600_000) }
274
+ }
275
+
276
+ async function cmdLogin(flags) {
277
+ const idle = readIdle(flags)
278
+
279
+ const existing = await runningAgent()
280
+ if (existing) {
281
+ process.stdout.write(
282
+ `Already logged in (account ${existing.account}, agent pid ${existing.pid}). ` +
283
+ 'Run sf logout first to use another account.\n',
284
+ )
285
+ return
286
+ }
287
+ if (!process.stdin.isTTY) {
288
+ throw new Error(
289
+ 'sf login needs an interactive terminal. It prompts for your password ' +
290
+ 'instead of reading it from the environment.',
291
+ )
292
+ }
293
+
294
+ const cfg = backendConfig()
295
+ const email = process.env.SF_EMAIL || (await promptLine('Email: ')).trim()
296
+ const password = await promptHidden('Password: ')
297
+ const vaultPassword =
298
+ (await promptHidden('Vault password (press Enter if it is the same): ')) || password
299
+
300
+ const { signIn } = await import('./auth.mjs')
301
+ const { fetchAndUnlockVault } = await import('./vault.mjs')
302
+
303
+ process.stderr.write('signing in…\n')
304
+ const session = await signIn({ ...cfg, email, password, getTotpCode: readTotpCode })
305
+
306
+ process.stderr.write('unlocking vault…\n')
307
+ const rootKey = await fetchAndUnlockVault({
308
+ apiBaseUrl: cfg.apiBaseUrl,
309
+ accessToken: session.accessToken,
310
+ password: vaultPassword,
311
+ })
312
+
313
+ const started = await launchAgent({ session, rootKey, config: cfg, idleMs: idle.ms })
314
+ rootKey.fill(0)
315
+
316
+ process.stdout.write(
317
+ `Logged in as ${email}. The agent (pid ${started.pid}) holds the session in memory ` +
318
+ `only and locks after ${idle.hours} h without an upload, sync or verify. ` +
319
+ 'Run sf logout to end it.\n',
320
+ )
321
+ }
322
+
323
+ async function cmdStatus() {
324
+ const status = await runningAgent()
325
+ if (!status) {
326
+ process.stdout.write('Not logged in: no agent is running.\n')
327
+ return
328
+ }
329
+ const totalMinutes = Math.round(status.idleLocksInSec / 60)
330
+ const hours = Math.floor(totalMinutes / 60)
331
+ const minutes = totalMinutes % 60
332
+ process.stdout.write(
333
+ `Logged in (account ${status.account}). Agent pid ${status.pid}; locks after ` +
334
+ `${hours} h ${minutes} min without an upload, sync or verify.\n`,
335
+ )
336
+ }
337
+
338
+ async function cmdLogout(flags) {
339
+ const { AgentUnavailableError, request } = await import('./agent/client.mjs')
340
+ const everywhere = flags.everywhere === true
341
+ let result
342
+ try {
343
+ result = await request('logout', { everywhere }, { timeoutMs: 15_000 })
344
+ } catch (err) {
345
+ if (err instanceof AgentUnavailableError) {
346
+ process.stdout.write('Not logged in: no agent is running.\n')
347
+ return
348
+ }
349
+ throw err
350
+ }
351
+
352
+ if (result.sessionRevoked) {
353
+ process.stdout.write(
354
+ everywhere
355
+ ? 'Logged out. Every ShieldFive session on this account was signed out, including your browser and phone.\n'
356
+ : 'Logged out. The session was revoked on the server.\n',
357
+ )
358
+ return
359
+ }
360
+
361
+ // Both failures leave the key wiped here. They differ in what is known about
362
+ // the session, and in what the user can do about it.
363
+ process.exitCode = 1
364
+ if (result.revokeStatus === 0) {
365
+ process.stdout.write(
366
+ 'Logged out on this machine, but the server could not be reached, so the ' +
367
+ 'session is still valid there. Once you are online, run sf login and then ' +
368
+ 'sf logout --everywhere to end it.\n',
369
+ )
370
+ } else {
371
+ process.stdout.write(
372
+ `Logged out on this machine, but the server did not accept the sign-out ` +
373
+ `(HTTP ${result.revokeStatus}). The session may already have ended. To be ` +
374
+ 'certain, run sf login and then sf logout --everywhere, which ends every ' +
375
+ 'session on this account, including your browser.\n',
376
+ )
377
+ }
153
378
  }
154
379
 
155
380
  // login -> unlock -> encrypt -> upload every file in the folder, once.
156
381
  async function cmdPush(folder) {
382
+ const { agent } = await chooseAuth()
383
+ if (agent) {
384
+ const { request } = await import('./agent/client.mjs')
385
+ process.stderr.write(`pushing to account ${agent.account} through the agent\n`)
386
+ let differs = 0
387
+ for await (const { name, path } of filesIn(resolve(folder))) {
388
+ const result = await request('upload', { path }, { timeoutMs: 0 })
389
+ if (result.matchesFileNow) {
390
+ process.stdout.write(`pushed ${name}\n`)
391
+ } else {
392
+ differs++
393
+ process.stdout.write(
394
+ `pushed ${name}, but it changed while uploading: the vault holds the ` +
395
+ 'version that was read, not the file as it is now\n',
396
+ )
397
+ }
398
+ }
399
+ // Non-zero so a script does not treat a file whose current contents are not
400
+ // in the vault as pushed.
401
+ if (differs) process.exitCode = 2
402
+ return
403
+ }
404
+
157
405
  const cfg = readLiveConfig()
158
406
  const { uploadFile } = await import('./upload.mjs')
159
407
  const { accessToken, rootKey } = await authAndUnlock(cfg)
@@ -171,8 +419,57 @@ async function cmdPush(folder) {
171
419
  }
172
420
  }
173
421
 
422
+ async function syncViaAgent(folder, { watch, intervalMs }, agent) {
423
+ const { AgentUnavailableError, request } = await import('./agent/client.mjs')
424
+ const controller = new AbortController()
425
+ const onSigint = () => {
426
+ process.stderr.write('\nstopping…\n')
427
+ controller.abort()
428
+ }
429
+ if (watch) process.on('SIGINT', onSigint)
430
+ process.stderr.write(`syncing to account ${agent.account} through the agent\n`)
431
+
432
+ try {
433
+ do {
434
+ let summary
435
+ try {
436
+ summary = await request('sync', { folder }, { timeoutMs: 0 })
437
+ } catch (err) {
438
+ if (err instanceof AgentUnavailableError || err.code === 'locked') {
439
+ throw new Error('The agent was locked or logged out. Run sf login to continue.')
440
+ }
441
+ throw err
442
+ }
443
+ for (const e of summary.errors) process.stdout.write(`failed ${e.path}: ${e.message}\n`)
444
+ process.stderr.write(
445
+ `pass: ${summary.uploaded} synced, ${summary.skipped} unchanged` +
446
+ (summary.changed ? `, ${summary.changed} changed while uploading (uploaded again on the next pass)` : '') +
447
+ (summary.failed ? `, ${summary.failed} failed` : '') +
448
+ '\n',
449
+ )
450
+ if (!watch || controller.signal.aborted) break
451
+ await new Promise((r) => {
452
+ const timer = setTimeout(r, intervalMs)
453
+ controller.signal.addEventListener(
454
+ 'abort',
455
+ () => {
456
+ clearTimeout(timer)
457
+ r()
458
+ },
459
+ { once: true },
460
+ )
461
+ })
462
+ } while (!controller.signal.aborted)
463
+ } finally {
464
+ if (watch) process.off('SIGINT', onSigint)
465
+ }
466
+ }
467
+
174
468
  // login -> unlock -> mirror new/changed files into the vault, once or on a loop.
175
469
  async function cmdSync(folder, { watch, intervalMs }) {
470
+ const { agent } = await chooseAuth()
471
+ if (agent) return syncViaAgent(resolve(folder), { watch, intervalMs }, agent)
472
+
176
473
  const cfg = readLiveConfig()
177
474
  const { uploadFile } = await import('./upload.mjs')
178
475
  const { runSync } = await import('./sync.mjs')
@@ -187,6 +484,28 @@ async function cmdSync(folder, { watch, intervalMs }) {
187
484
  })
188
485
  }
189
486
 
487
+ const STATE_LABELS = {
488
+ verified: 'backed up',
489
+ missing: 'NOT confirmed',
490
+ changed_since_upload: 'changed since upload',
491
+ not_in_ledger: 'no upload record',
492
+ unreadable: 'unreadable',
493
+ }
494
+
495
+ async function cmdVerify(paths) {
496
+ if (!paths.length) throw new Error('verify needs at least one file')
497
+ const { request } = await import('./agent/client.mjs')
498
+ const results = await request('verify', { paths: paths.map((p) => resolve(p)) }, { timeoutMs: 0 })
499
+
500
+ for (const r of results) {
501
+ const label = STATE_LABELS[r.state] ?? r.state
502
+ const note = r.matchedPath ? ` (same bytes as ${r.matchedPath})` : r.reason ? ` (${r.reason})` : ''
503
+ process.stdout.write(`${label.padEnd(22)} ${r.path}${note}\n`)
504
+ }
505
+ // Exit 0 only when every file is confirmed, so a script can gate on it.
506
+ if (!results.every((r) => r.state === 'verified')) process.exitCode = 2
507
+ }
508
+
190
509
  // Minimal parse: first non-flag arg after the command is the positional; --flag
191
510
  // and --flag=value are collected. Enough for `sf sync <folder> --watch
192
511
  // --interval=10`.
@@ -211,16 +530,38 @@ async function main() {
211
530
  const { positionals, flags } = parseArgs(argv.slice(1))
212
531
  const folder = positionals[0]
213
532
 
214
- if (!cmd || cmd === '--help' || cmd === '-h') {
533
+ if (cmd === '__agent') {
534
+ // A detached agent outlives the terminal that started it; writing to a
535
+ // closed pipe must not take it down.
536
+ process.stdout.on('error', () => {})
537
+ process.stderr.on('error', () => {})
538
+ const { runAgent } = await import('./agent/main.mjs')
539
+ await runAgent()
540
+ } else if (!cmd || cmd === '--help' || cmd === '-h') {
215
541
  usage()
542
+ } else if (cmd === 'login') {
543
+ await cmdLogin(flags)
544
+ } else if (cmd === 'status') {
545
+ await cmdStatus()
546
+ } else if (cmd === 'logout') {
547
+ await cmdLogout(flags)
216
548
  } else if (cmd === 'encrypt') {
217
549
  if (!folder) throw new Error('encrypt needs a <folder>')
218
550
  await cmdEncrypt(folder)
551
+ } else if (cmd === 'inspect') {
552
+ if (!folder) throw new Error('inspect needs a <folder>')
553
+ const { inspectMigrationSource } = await import('./migrationInventory.mjs')
554
+ const result = await inspectMigrationSource(folder)
555
+ process.stdout.write(JSON.stringify(result) + '\n')
556
+ if (result.skipped) process.exitCode = 2
219
557
  } else if (cmd === 'push') {
220
558
  if (!folder) throw new Error('push needs a <folder>')
221
559
  await cmdPush(folder)
222
560
  } else if (cmd === 'sync') {
223
561
  if (!folder) throw new Error('sync needs a <folder>')
562
+ // `--interval 10` (space-separated) would otherwise parse as a bare flag and
563
+ // quietly become a one-second interval.
564
+ if (flags.interval === true) throw new Error('--interval needs a value: --interval=<seconds>')
224
565
  const intervalSec = flags.interval ? Number(flags.interval) : 5
225
566
  if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
226
567
  throw new Error('--interval must be a positive number of seconds')
@@ -229,6 +570,8 @@ async function main() {
229
570
  watch: Boolean(flags.watch),
230
571
  intervalMs: Math.round(intervalSec * 1000),
231
572
  })
573
+ } else if (cmd === 'verify') {
574
+ await cmdVerify(positionals)
232
575
  } else {
233
576
  usage()
234
577
  process.exitCode = 1