@shieldfive/cli 0.3.0 → 0.4.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 CHANGED
@@ -7,6 +7,90 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.4.0 — 2026-10-12
11
+
12
+ ### Behaviour changes
13
+
14
+ - `sf push` now skips dotfiles (`.env`, `.git`, ...) by default; pass
15
+ `--include-dotfiles` to upload them as before.
16
+ - Sign-in refuses a server answer of auth version 1 for an account previously
17
+ signed in with version 2; pass `--allow-legacy-login` to override.
18
+ - Symlinks are skipped instead of followed.
19
+
20
+ ### Security
21
+
22
+ - **Symlinks are not followed.** `push`, `sync` and the agent list files with
23
+ `lstat` and skip symlinks, and files are opened with `O_NOFOLLOW`, so a link
24
+ inside the folder can no longer upload a file from outside it.
25
+ - **`push` skips dotfiles by default** (`.env`, `.git`, ...), as `sync` already
26
+ did. `sf push --include-dotfiles` restores the old behaviour.
27
+ - **Sync manifest written 0600.** `.shieldfive-sync.json` lists file names and
28
+ vault ids; it is no longer world-readable.
29
+ - **README and npm description** now state the scheme precisely: contents are
30
+ AES-256-GCM under a post-quantum hybrid key, names are AES-256-GCM under the
31
+ vault key, and size, part hashes and timestamps are visible to the server.
32
+
33
+ ### Fixed
34
+
35
+ - A failed upload cancels its pending session (`POST /api/files/delete`, as the
36
+ web app does) instead of leaving a row holding quota until the reaper runs.
37
+ Not done when only the finalize answer was lost, since the file may be in.
38
+ - 0-byte files: uploaded as a header-only cipher-v3 object with the server's
39
+ empty-file proof when `/api/files/upload-capabilities` says `emptyCipherV3`;
40
+ otherwise skipped with a clear message (exit code 2) before any session.
41
+ - New uploads send a v6 row-bound encrypted name from upload start (#14).
42
+ - **Downgrade pin for sign-in.** After a sign-in with a login secret (auth
43
+ version 2), the CLI records the account (a SHA-256 of the email) in
44
+ `~/.shieldfive/auth-pins.json` (mode 0600). A later server answer of
45
+ version 1 for that account is refused before the raw password is sent.
46
+ `--allow-legacy-login` on `sf login`, `sf push` or `sf sync` overrides it.
47
+
48
+ ## 0.3.1 - 2026-10-01
49
+
50
+ ### Security
51
+
52
+ - **`sf push` and `sf sync` write the web's default format.** They wrote the
53
+ deprecated v0 format (AES-GCM chunks, no header), which the format spec
54
+ forbids for new writes: a server could drop trailing chunks and the file
55
+ still decrypted, could move a file's bytes onto another row, and there was no
56
+ post-quantum layer despite the description. Uploads are now `cipher_version`
57
+ 3 (suite 0x03, ML-KEM-1024 + X25519 hybrid, v1 wire format) written by
58
+ `@shieldfive/crypto`'s stream encoder, with the row id as the header's
59
+ `file_id` and the filename re-sealed bound to the row (v6) at finalize. The
60
+ recipient key is derived locally from the root key, never fetched. Files
61
+ uploaded by earlier versions still open in the apps. Shared decrypt vectors:
62
+ `test/vectors/v3-upload.json`.
63
+ - `@shieldfive/crypto` is pinned to `~1.0.1` (was `^1.0.0-beta.1`, which a
64
+ global install could float to any 1.x).
65
+
66
+ ### Fixed
67
+
68
+ - `sf sync --watch` refreshes its session before the access token expires.
69
+ It signed in once, so after about an hour every pass failed every changed
70
+ file while the process kept running. If the session cannot be refreshed, sync
71
+ now stops with an error. A single `sf sync` pass with failed files exits
72
+ non-zero.
73
+
74
+ - **Sign-in works for accounts on ShieldFive's current sign-in scheme.** 0.3.0
75
+ posted your password straight to Supabase, which fails for every account that
76
+ signs in with a client-derived login secret (all new accounts, and every
77
+ account migrated on its next web or app sign-in), and sent the password to
78
+ the server on each failed attempt. `sf login`, `sf push` and `sf sync` now ask
79
+ ShieldFive how the account signs in, derive the login secret locally
80
+ (Argon2id, the same parameters and bytes as the web and Android apps) and
81
+ send only that. The raw password is sent only for an account the server
82
+ reports as not yet migrated, and only to ShieldFive's sign-in route. If that
83
+ lookup fails for any reason, sign-in stops before anything is sent.
84
+ - A vault password typed with leading or trailing spaces now unlocks a vault
85
+ created on the web, which trims them.
86
+
87
+ ### Changed
88
+
89
+ - Argon2id runs natively (the `argon2` package, off the main thread) when it
90
+ installs, and falls back to the bundled WebAssembly implementation when it
91
+ does not, so installation never fails on a platform without a prebuilt
92
+ binary. Both produce identical keys; parameters are unchanged.
93
+
10
94
  ## 0.3.0 - 2026-09-16
11
95
 
12
96
  ### Added
package/README.md CHANGED
@@ -1,23 +1,35 @@
1
1
  # @shieldfive/cli
2
2
 
3
3
  > Command-line client for [ShieldFive](https://shieldfive.com). Encrypt a folder
4
- > on your machine, then push or continuously sync it to your EU-hosted,
5
- > post-quantum vault. Everything is encrypted locally before it leaves your
6
- > machine. Read the code and verify that for yourself.
4
+ > on your machine, then push or continuously sync it to your EU-hosted vault.
5
+ > File contents and names are encrypted locally before they leave your machine
6
+ > (contents with a post-quantum hybrid key). Read the code and verify that for
7
+ > yourself.
7
8
 
8
9
  [![CI](https://github.com/shieldfive/cli/actions/workflows/ci.yml/badge.svg)](https://github.com/shieldfive/cli/actions/workflows/ci.yml)
9
10
  [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
10
11
  [![Status](https://img.shields.io/badge/status-early-yellow.svg)](#honest-scope)
11
12
 
12
13
  The point of this tool being open source is that you do not have to trust a
13
- marketing claim. The plaintext of your files is never sent to a ShieldFive
14
- server. The only bytes that leave your machine are AES-GCM ciphertext and a
15
- short cryptographic proof. Two files carry the whole story:
14
+ marketing claim. The plaintext of your files and their names is never sent to a
15
+ ShieldFive server:
16
+
17
+ - **File contents** — AES-256-GCM chunks under a per-file key that combines a
18
+ random envelope key (wrapped by your vault root key) with an ML-KEM-1024 +
19
+ X25519 hybrid encapsulation to your vault identity.
20
+ - **File names** — AES-256-GCM under a key derived from your vault root key
21
+ (not the post-quantum layer), plus a keyed HMAC of the lowercased name so the
22
+ server can spot duplicates without reading it.
23
+
24
+ What the server does see, by design: the plaintext size of each file, part
25
+ hashes (SHA-1 of ciphertext), the wrapped keys, an upload proof, timestamps and
26
+ your account. Sign-in sends a secret derived from your password, never the
27
+ password itself. Two files carry the whole story:
16
28
 
17
29
  - [`src/uploadCrypto.mjs`](src/uploadCrypto.mjs) — the encryption applied to
18
30
  every chunk and to the filename.
19
- - [`src/upload.mjs`](src/upload.mjs) — the only place bytes are sent over the
20
- network. Every request body is ciphertext.
31
+ - [`src/upload.mjs`](src/upload.mjs) — the only place file bytes are sent over
32
+ the network. Every file body it sends is ciphertext.
21
33
 
22
34
  If you want to see encryption happen without an account at all, run
23
35
  `sf encrypt <folder>` — it encrypts each file locally and prints the ciphertext
@@ -80,14 +92,28 @@ npm test # 107 tests
80
92
  sf login [--idle=<hours>] sign in once; an agent holds the session in memory (locks after 8 h idle)
81
93
  sf status is an agent running, and for which account
82
94
  sf logout [--everywhere] revoke the session and stop the agent; --everywhere signs out every device
83
- sf push <folder> encrypt and upload every file once
95
+ sf push <folder> [--include-dotfiles] encrypt and upload every file once (skips dotfiles unless asked; never follows symlinks)
84
96
  sf sync <folder> [--watch] [--interval=N] upload new/changed files; --watch keeps a poll loop (N seconds, default 5)
85
97
  sf verify <file>... report whether each file is safely stored in your vault
86
98
  sf encrypt <folder> encrypt each file locally, upload nothing (no account needed)
99
+ sf inspect <folder> read-only recursive migration inventory; upload nothing
87
100
  ```
88
101
 
89
102
  `sf push` and `sf sync` pick the direct or multipart upload path automatically
90
- from the file size.
103
+ from the file size. Both read only regular files directly inside the folder:
104
+ symlinks are skipped (and files are opened with `O_NOFOLLOW`), and names
105
+ starting with `.` are skipped unless you pass `sf push --include-dotfiles`.
106
+ An empty (0-byte) file is uploaded only when the server says it accepts empty
107
+ files; otherwise it is reported as skipped and the exit code is 2. If an upload
108
+ fails after its session was created, the pending session is cancelled so it
109
+ does not hold quota. `sf sync` writes its manifest (`.shieldfive-sync.json`)
110
+ with mode 0600.
111
+
112
+ `sf inspect` reports JSON counts of files, directories, bytes and skipped entries.
113
+ It includes nested/hidden files and empty folders, reads metadata only, and
114
+ does not follow symbolic links. Exit code 2 means entries were skipped. It does
115
+ not upload anything or prove that a migration has completed. Current push/sync
116
+ remain top-level only; do not use their completion as proof of a whole-tree copy.
91
117
 
92
118
  With an agent running, `sf sync` records uploads in the agent's ledger (see
93
119
  [What the agent can and cannot do](#what-the-agent-can-and-cannot-do)) and
@@ -216,24 +242,36 @@ The full design, including the threat model, is in
216
242
 
217
243
  ## How the upload works (for auditors)
218
244
 
219
- The upload uses **chunked AES-GCM** for file content and issues a
220
- server-verified HMAC proof. (The `sf encrypt` demo uses the post-quantum hybrid
221
- suite; the sync/push path uses AES-GCM, which is what the vault's upload
222
- protocol and server-side proof expect.)
245
+ Uploads are written in the format the web app writes by default:
246
+ `cipher_version` 3, suite `0x03` (post-quantum hybrid) in the v1 wire format
247
+ (`@shieldfive/crypto` `spec/format-v1.md`), using the library's own stream
248
+ encoder.
223
249
 
224
250
  - **Filename** — encrypted with AES-GCM under a key derived from your vault root
225
- key via Argon2id (`encryptMetadataV4`). The server stores ciphertext; it never
226
- sees the name. A keyed HMAC of the lowercased name (`hashMetadataV4`) lets the
227
- server deduplicate without learning the name.
228
- - **File content** — each chunk is AES-GCM encrypted under a per-file content
229
- key (itself wrapped by your root key). The nonce is a 4-byte random prefix
230
- followed by an 8-byte big-endian chunk counter, so every chunk has a distinct
231
- nonce.
232
- - **Upload proof** — `HMAC-SHA256(proofKey, prefix || ciphertext)` over the first
233
- chunk, where `prefix = [version=1][cipherVersion=1][chunkSize u32 BE][noncePrefix 4]`.
234
- The server issues `proofKey` when it creates the session and verifies the proof
235
- when finalizing. It ties the stored ciphertext to the session without the
236
- server ever seeing plaintext.
251
+ key via Argon2id (`encryptMetadataV4`), then, at finalize, re-sealed with the
252
+ file's row id as additional data (v6, `encryptNameV6`), so the server cannot
253
+ move one file's name onto another row. A keyed HMAC of the lowercased name
254
+ (`hashMetadataV4`) lets the server deduplicate without learning the name.
255
+ - **File content** — a MAC'd header carries the file's `file_id` (the row id the
256
+ server assigned, so the stored object is bound to its row), the plaintext size
257
+ and the chunk count. The content key combines a per-file envelope key (wrapped
258
+ by your root key in `csk_wrapped`) with an ML-KEM-1024 + X25519 encapsulation
259
+ to your vault identity, which is derived on this machine from your root key,
260
+ as the web app derives it; the server cannot substitute a recipient. Each 5 MiB
261
+ chunk is AES-256-GCM with its index, the total and an is-final flag in the
262
+ additional data, so a dropped, reordered or truncated chunk fails to decrypt.
263
+ - **Upload proof** — base64 of `[3][3] || HMAC-SHA256(proofKey, [3][3] || header
264
+ || frame_0)` (`buildUploadProofV3` in `@shieldfive/crypto`, the same function
265
+ the web and the MCP server use). The server issues `proofKey` when it creates
266
+ the session and verifies the proof against the stored object when finalizing.
267
+ - **Parts** — each storage part is exactly one encrypted chunk frame; part 1 also
268
+ carries the header.
269
+
270
+ Versions up to 0.3.0 wrote the legacy v0 format (AES-GCM chunks under a random
271
+ nonce prefix, no header): no truncation detection, no row binding and no
272
+ post-quantum layer. Files already uploaded that way still open in the apps;
273
+ this client no longer writes it.
274
+
237
275
  - **Direct** (≤ 5 MiB) — the single encrypted chunk is `PUT` at a presigned S3
238
276
  URL the server issues with the session. The URL's SigV4 signature is the only
239
277
  credential and it authorises exactly one object key, so the request carries no
@@ -242,25 +280,33 @@ protocol and server-side proof expect.)
242
280
  Because the signature covers `host` only, nothing on this path binds the body:
243
281
  the server compares the client's `ciphertextHash` against the client's own
244
282
  `partSha1Array[0]`, so they always agree. Integrity here rests on the upload
245
- proof and on AES-GCM's tag at download, not on a wire checksum.
283
+ proof and on the header MAC and chunk tags at download, not on a wire checksum.
246
284
  - **Multipart** (> 5 MiB) — the file is streamed one 5 MiB chunk at a time (never
247
285
  loaded whole into memory), each chunk uploaded as a Backblaze part. The
248
286
  ciphertext hash the server checks is SHA-1 over the concatenated raw part
249
287
  digests; the server finishes the large file with the ordered part list.
250
288
 
251
289
  The mock end-to-end test in [`test/upload.flow.test.mjs`](test/upload.flow.test.mjs)
252
- captures every byte this client would send, decrypts each part with the key
253
- recovered from the session envelope, and asserts the result equals the original
254
- file — a machine-checked demonstration that only ciphertext is uploaded.
290
+ captures every byte this client would send, opens the stored object with
291
+ `@shieldfive/crypto`'s reference reader from nothing but the session fields and
292
+ the root key, and asserts the result equals the original file and the header's
293
+ `file_id` equals the row id. [`test/v1Format.test.mjs`](test/v1Format.test.mjs)
294
+ checks the shared vectors in [`test/vectors/v3-upload.json`](test/vectors/v3-upload.json)
295
+ (regenerate with `node scripts/generate-vectors.mjs`) against the library's
296
+ blob and streaming readers.
255
297
 
256
298
  ## Layout
257
299
 
258
300
  - `src/cli.mjs` — the `sf` entry point (argument parsing, command dispatch)
259
- - `src/auth.mjs` — Supabase sign-in to a Bearer token
301
+ - `src/auth.mjs` — sign-in to a Bearer token through ShieldFive's sign-in route,
302
+ with two-factor step-up
303
+ - `src/loginSecret.mjs` — the login secret derived from your password; for
304
+ accounts on the current scheme the password itself is never sent
305
+ - `src/argon2.mjs` — Argon2id, native when available, WebAssembly otherwise
260
306
  - `src/vault.mjs` / `src/unlock.mjs` — fetch the wrapped vault key, unwrap the
261
307
  root key from your password (Argon2id / PBKDF2)
262
- - `src/uploadCrypto.mjs` — filename and chunk encryption, upload proof, multipart
263
- ciphertext hash
308
+ - `src/uploadCrypto.mjs` — filename encryption, the suite-0x03 part writer,
309
+ upload proof, multipart ciphertext hash
264
310
  - `src/upload.mjs` — create session, encrypt, upload (direct + multipart),
265
311
  finalize; the streaming chunk reader
266
312
  - `src/sync.mjs` — `sf sync`: manifest, change detection, reconcile pass, watch
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@shieldfive/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
- "description": "Open-source command-line client for ShieldFive: encrypt a folder on your machine and sync it to your EU-hosted, post-quantum vault. Read the code; it encrypts before upload.",
5
+ "description": "Open-source command-line client for ShieldFive: encrypts files on your machine before upload (contents: AES-256-GCM under an ML-KEM-1024 + X25519 hybrid key; names: AES-256-GCM under your vault key) and pushes or syncs them to your vault. Read the code.",
6
6
  "license": "Apache-2.0",
7
7
  "author": "Cho Garcia <security@shieldfive.com>",
8
8
  "homepage": "https://github.com/shieldfive/cli",
@@ -46,8 +46,11 @@
46
46
  "dependencies": {
47
47
  "@noble/ciphers": "^2.1.1",
48
48
  "@noble/hashes": "^2.0.1",
49
- "@shieldfive/crypto": "^1.0.0-beta.1",
49
+ "@shieldfive/crypto": "~1.0.1",
50
50
  "@supabase/supabase-js": "^2",
51
51
  "libsodium-wrappers-sumo": "^0.8.2"
52
+ },
53
+ "optionalDependencies": {
54
+ "argon2": "0.45.1"
52
55
  }
53
56
  }
@@ -5,7 +5,7 @@
5
5
  // See docs/agent-design.md for why it exists and what it will never do.
6
6
 
7
7
  import { createHmac, randomUUID } from 'node:crypto'
8
- import { chmod, open, readFile, rm, stat } from 'node:fs/promises'
8
+ import { chmod, lstat, open, readFile, rm, stat } from 'node:fs/promises'
9
9
  import { connect, createServer } from 'node:net'
10
10
  import { basename, dirname, join } from 'node:path'
11
11
 
@@ -189,7 +189,9 @@ export function createAgent({
189
189
  }
190
190
 
191
191
  async function upload(path) {
192
- const before = await stat(path)
192
+ // lstat: a symlink is refused, not followed (and readFileChunks opens with
193
+ // O_NOFOLLOW, so a swap after this check fails too).
194
+ const before = await lstat(path)
193
195
  if (!before.isFile()) throw new AgentError('not_a_file', `${path} is not a regular file.`)
194
196
  const token = await accessToken()
195
197
 
package/src/argon2.mjs ADDED
@@ -0,0 +1,69 @@
1
+ import { hkdfSync } from 'node:crypto'
2
+
3
+ // Argon2id master-secret derivation, byte-identical to
4
+ // @shieldfive/crypto/kdf/argon2id deriveMasterSecret (the web's and the
5
+ // vault's reference implementation): libsodium presets, Argon2id v0x13,
6
+ // parallelism 1, 32-byte output, and salts longer than 16 bytes compressed
7
+ // through HKDF-SHA-256 (zero salt, info 'shieldfive/v1/argon2id/salt-compression').
8
+ //
9
+ // Two backends, same bytes:
10
+ //
11
+ // - native `argon2` (an optionalDependency): async, runs on the libuv thread
12
+ // pool so the event loop keeps turning, and several times faster.
13
+ // - @shieldfive/crypto over libsodium WASM: always installed. Used when the
14
+ // native module is missing, which is expected on platforms `argon2` ships no
15
+ // prebuilt binary for (Intel macOS, Windows on ARM) and where compiling it
16
+ // failed. npm drops a failed optional dependency instead of failing the
17
+ // install, so `npm i -g @shieldfive/cli` never hard-fails on it.
18
+ //
19
+ // Parameters are never reduced on either path. test/argon2.backends.test.mjs
20
+ // pins the two backends against each other and against web-produced vectors.
21
+
22
+ const PRESETS = {
23
+ moderate: { timeCost: 3, memoryCost: 262144 }, // OPSLIMIT/MEMLIMIT_MODERATE (256 MiB)
24
+ sensitive: { timeCost: 4, memoryCost: 1048576 }, // OPSLIMIT/MEMLIMIT_SENSITIVE (1 GiB)
25
+ }
26
+
27
+ let nativePromise
28
+ async function loadNative() {
29
+ if (process.env.SF_ARGON2_BACKEND === 'wasm') return null
30
+ nativePromise ??= import('argon2').then(
31
+ (m) => (typeof m.hash === 'function' ? m : m.default ?? null),
32
+ () => null,
33
+ )
34
+ return nativePromise
35
+ }
36
+
37
+ /** 'native' or 'wasm': which backend the next derivation will use. */
38
+ export async function argon2Backend() {
39
+ return (await loadNative()) ? 'native' : 'wasm'
40
+ }
41
+
42
+ function validate({ passphrase, salt, preset }) {
43
+ if (typeof passphrase !== 'string' || !passphrase) throw new Error('Passphrase is required')
44
+ if (!(salt instanceof Uint8Array) || salt.length < 16) throw new Error('Argon2id salt must be at least 16 bytes')
45
+ const params = Object.hasOwn(PRESETS, preset) ? PRESETS[preset] : null
46
+ if (!params) throw new Error(`Unsupported Argon2id preset: ${preset}`)
47
+ return params
48
+ }
49
+
50
+ export async function deriveMasterSecret({ passphrase, salt, preset = 'moderate' }) {
51
+ const params = validate({ passphrase, salt, preset })
52
+ const native = await loadNative()
53
+ if (!native) {
54
+ const { deriveMasterSecret: wasmDerive } = await import('@shieldfive/crypto/kdf/argon2id')
55
+ const { masterSecret } = await wasmDerive({ passphrase, salt, preset })
56
+ return { masterSecret, salt, preset }
57
+ }
58
+ const usableSalt = salt.length === 16 ? Buffer.from(salt) : Buffer.from(hkdfSync(
59
+ 'sha256', salt, Buffer.alloc(32), 'shieldfive/v1/argon2id/salt-compression', 16,
60
+ ))
61
+ const input = Buffer.from(passphrase, 'utf8')
62
+ try {
63
+ const masterSecret = await native.hash(input, {
64
+ ...params, salt: usableSalt, type: native.argon2id, version: 0x13,
65
+ parallelism: 1, hashLength: 32, raw: true,
66
+ })
67
+ return { masterSecret, salt, preset } // a Buffer, i.e. a Uint8Array the caller zeroes
68
+ } finally { input.fill(0); usableSalt.fill(0) }
69
+ }
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,30 +79,68 @@ 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,
90
+ // { isPinned(email), pin(email) } -- src/authPin.mjs fileAuthPin(). Null
91
+ // means no pin (tests, embedders); the sf commands always pass one.
92
+ authPin = null,
93
+ allowLegacyLogin = false,
85
94
  }) {
86
- const supabase = createClient(supabaseUrl, anonKey, {
95
+ // The raw password is never handed to Supabase directly. The salt lookup
96
+ // decides what the version-aware login route receives: only the derived
97
+ // login secret for a version-2 account; the password only for an account the
98
+ // server affirmatively reported as version 1. test/auth.noPasswordLeak.test.mjs
99
+ // pins this across every path.
100
+ email = String(email ?? '').trim().toLowerCase()
101
+ const pinnedV2 = authPin ? await authPin.isPinned(email) : false
102
+ const credentials = await buildSignInCredentials({
103
+ apiBaseUrl, email, password, fetchImpl, pinnedV2, allowLegacyLogin,
104
+ })
105
+ let response
106
+ try {
107
+ response = await fetchImpl(new URL('/api/mobile/auth/login', apiBaseUrl), {
108
+ method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
109
+ body: JSON.stringify({ email, ...credentials }), signal: AbortSignal.timeout(30_000),
110
+ })
111
+ } catch {
112
+ throw new Error('Sign-in failed: could not reach ShieldFive. Check your connection and try again.')
113
+ }
114
+ const payload = await response.json().catch(() => null)
115
+ if (!response.ok || typeof payload?.accessToken !== 'string' || !payload.accessToken ||
116
+ typeof payload?.refreshToken !== 'string' || !payload.refreshToken) {
117
+ throw new Error(response.status === 429 ? 'Too many sign-in attempts. Try again shortly.' : 'Sign-in failed. Check your credentials and try again.')
118
+ }
119
+ const supabase = createClientImpl(supabaseUrl, anonKey, {
87
120
  auth: {
88
121
  persistSession: false,
89
122
  autoRefreshToken: false,
90
123
  detectSessionInUrl: false,
91
124
  },
92
125
  })
93
- const { data, error } = await supabase.auth.signInWithPassword({
94
- email,
95
- password,
126
+ const { data, error } = await supabase.auth.setSession({
127
+ access_token: payload.accessToken,
128
+ refresh_token: payload.refreshToken,
96
129
  })
97
- if (error) throw new Error(`Sign-in failed: ${error.message}`)
130
+ if (error) throw new Error('Could not establish the sign-in session. Please try again.')
98
131
 
99
132
  const aal1Token = data.session?.access_token
100
133
  if (!aal1Token) {
101
134
  throw new Error('Sign-in returned no access token.')
102
135
  }
103
136
 
137
+ // Signed in with only the login secret: the account is version 2. Remember
138
+ // it so a later version-1 answer is refused (src/authPin.mjs). A failed
139
+ // write does not fail the sign-in; the next one retries it.
140
+ if (authPin && !('password' in credentials)) {
141
+ try { await authPin.pin(email) } catch { /* retried on the next sign-in */ }
142
+ }
143
+
104
144
  const aal2Token = await stepUpMfaIfRequired({ supabase, getTotpCode })
105
145
 
106
146
  // The refresh token has to come from the session that was stepped up.
@@ -0,0 +1,95 @@
1
+ // "This account signs in with a login secret" -- remembered on this computer.
2
+ //
3
+ // /api/auth/salt is the server telling the CLI how to sign in: version 2 means
4
+ // send only the derived login secret, version 1 means send the raw password.
5
+ // A server that has been tampered with (or an account a stolen session
6
+ // downgraded) can answer version 1 for an account that is really version 2,
7
+ // and a CLI that obeys sends the raw password -- the one thing version 2
8
+ // promises never leaves this machine. The mobile app and the web already pin;
9
+ // this is the CLI's pin.
10
+ //
11
+ // Once a sign-in has gone through with the server saying version 2, the
12
+ // account is recorded here. Afterwards a version-1 answer for it is refused
13
+ // unless the user passes --allow-legacy-login.
14
+ //
15
+ // File: ~/.shieldfive/auth-pins.json, mode 0600 in a 0700 directory. It holds
16
+ // SHA-256 hashes of lower-cased email addresses, not the addresses, so the file
17
+ // does not list which accounts this computer uses.
18
+
19
+ import { createHash } from 'node:crypto'
20
+ import { chmod, readFile, rename, writeFile } from 'node:fs/promises'
21
+ import { homedir } from 'node:os'
22
+ import { join } from 'node:path'
23
+
24
+ import { ensurePrivateDir, shieldfiveHome } from './agent/paths.mjs'
25
+
26
+ export const AUTH_PIN_FILE = 'auth-pins.json'
27
+
28
+ export class LegacyLoginRefusedError extends Error {
29
+ constructor() {
30
+ super(
31
+ 'Refusing to sign in: this computer has signed in to this account with a ' +
32
+ 'login secret before, but the server now asks for the raw password ' +
33
+ '(auth version 1). That should not happen to an account that has moved ' +
34
+ 'to version 2, so the password was not sent. If you know why (for ' +
35
+ 'example ShieldFive support reset the account), run the command again ' +
36
+ 'with --allow-legacy-login.',
37
+ )
38
+ this.name = 'LegacyLoginRefusedError'
39
+ this.code = 'legacy_login_refused'
40
+ }
41
+ }
42
+
43
+ function emailKey(email) {
44
+ return createHash('sha256')
45
+ .update(String(email ?? '').trim().toLowerCase())
46
+ .digest('hex')
47
+ }
48
+
49
+ /**
50
+ * The pin store backed by ~/.shieldfive/auth-pins.json. `home` is injectable
51
+ * for tests. A file that cannot be read as a pin list is treated as holding
52
+ * no pins for reads, and is replaced on the next write.
53
+ */
54
+ export function fileAuthPin({ home = homedir() } = {}) {
55
+ const dir = shieldfiveHome(home)
56
+ const file = join(dir, AUTH_PIN_FILE)
57
+
58
+ const readKeys = async () => {
59
+ let raw
60
+ try {
61
+ raw = await readFile(file, 'utf8')
62
+ } catch (err) {
63
+ if (err.code === 'ENOENT') return []
64
+ throw err
65
+ }
66
+ try {
67
+ const parsed = JSON.parse(raw)
68
+ return Array.isArray(parsed?.v2)
69
+ ? parsed.v2.filter((k) => typeof k === 'string' && /^[0-9a-f]{64}$/.test(k))
70
+ : []
71
+ } catch {
72
+ return []
73
+ }
74
+ }
75
+
76
+ return {
77
+ file,
78
+ async isPinned(email) {
79
+ return (await readKeys()).includes(emailKey(email))
80
+ },
81
+ async pin(email) {
82
+ await ensurePrivateDir(dir)
83
+ const keys = await readKeys()
84
+ const key = emailKey(email)
85
+ if (keys.includes(key)) return
86
+ keys.push(key)
87
+ // Write-then-rename so a crash never leaves a half-written file, and
88
+ // chmod after rename in case an older file had looser bits.
89
+ const tmp = `${file}.${process.pid}.tmp`
90
+ await writeFile(tmp, JSON.stringify({ v2: keys }) + '\n', { mode: 0o600 })
91
+ await rename(tmp, file)
92
+ await chmod(file, 0o600)
93
+ },
94
+ }
95
+ }