@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/CHANGELOG.md CHANGED
@@ -5,6 +5,115 @@ All notable changes to `@shieldfive/cli` will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## 0.3.1 - 2026-10-01
9
+
10
+ ### Security
11
+
12
+ - **`sf push` and `sf sync` write the web's default format.** They wrote the
13
+ deprecated v0 format (AES-GCM chunks, no header), which the format spec
14
+ forbids for new writes: a server could drop trailing chunks and the file
15
+ still decrypted, could move a file's bytes onto another row, and there was no
16
+ post-quantum layer despite the description. Uploads are now `cipher_version`
17
+ 3 (suite 0x03, ML-KEM-1024 + X25519 hybrid, v1 wire format) written by
18
+ `@shieldfive/crypto`'s stream encoder, with the row id as the header's
19
+ `file_id` and the filename re-sealed bound to the row (v6) at finalize. The
20
+ recipient key is derived locally from the root key, never fetched. Files
21
+ uploaded by earlier versions still open in the apps. Shared decrypt vectors:
22
+ `test/vectors/v3-upload.json`.
23
+ - `@shieldfive/crypto` is pinned to `~1.0.1` (was `^1.0.0-beta.1`, which a
24
+ global install could float to any 1.x).
25
+
26
+ ### Fixed
27
+
28
+ - `sf sync --watch` refreshes its session before the access token expires.
29
+ It signed in once, so after about an hour every pass failed every changed
30
+ file while the process kept running. If the session cannot be refreshed, sync
31
+ now stops with an error. A single `sf sync` pass with failed files exits
32
+ non-zero.
33
+
34
+ - **Sign-in works for accounts on ShieldFive's current sign-in scheme.** 0.3.0
35
+ posted your password straight to Supabase, which fails for every account that
36
+ signs in with a client-derived login secret (all new accounts, and every
37
+ account migrated on its next web or app sign-in), and sent the password to
38
+ the server on each failed attempt. `sf login`, `sf push` and `sf sync` now ask
39
+ ShieldFive how the account signs in, derive the login secret locally
40
+ (Argon2id, the same parameters and bytes as the web and Android apps) and
41
+ send only that. The raw password is sent only for an account the server
42
+ reports as not yet migrated, and only to ShieldFive's sign-in route. If that
43
+ lookup fails for any reason, sign-in stops before anything is sent.
44
+ - A vault password typed with leading or trailing spaces now unlocks a vault
45
+ created on the web, which trims them.
46
+
47
+ ### Changed
48
+
49
+ - Argon2id runs natively (the `argon2` package, off the main thread) when it
50
+ installs, and falls back to the bundled WebAssembly implementation when it
51
+ does not, so installation never fails on a platform without a prebuilt
52
+ binary. Both produce identical keys; parameters are unchanged.
53
+
54
+ ## 0.3.0 - 2026-09-16
55
+
56
+ ### Added
57
+
58
+ - **`sf login`, `sf status`, `sf logout`.** `sf login` prompts for your password
59
+ and, if two-factor is enabled, a code, then starts an agent that holds the
60
+ signed-in session and the unlocked vault key in memory only. `sf push` and
61
+ `sf sync` use it when it is running and need nothing in the environment. The
62
+ agent locks itself after 8 hours without use (`--idle=<hours>` to change it),
63
+ and `sf logout` revokes the session on the server.
64
+ - **`sf verify <file>...`** reports whether each file is safely stored in your
65
+ vault. The bytes on disk now must match an upload the agent performed, and the
66
+ server must confirm that upload at the moment of asking. Names and sizes play
67
+ no part. Exits 0 only when every file is confirmed, so a script can gate on it.
68
+ - **Unattended sync on two-factor accounts.** One interactive `sf login` is
69
+ enough: the agent refreshes the session without prompting again until it locks
70
+ or you log out.
71
+
72
+ - **`sf logout --everywhere`** signs out every session on the account, including
73
+ the browser and phone.
74
+
75
+ ### Security
76
+
77
+ - The agent's socket accepts six operations: `status`, `upload`, `sync`,
78
+ `verify`, `lock`, `logout`. None lists, downloads or decrypts vault contents,
79
+ or returns key material, and a test pins the list.
80
+ - `sf login` never reads `SF_PASSWORD`. The agent is started with an explicit
81
+ environment allowlist, so a password exported for the older flow does not
82
+ reach it.
83
+ - Uploads are recorded in `~/.shieldfive/ledger/<account>.jsonl` with an HMAC of
84
+ each file's contents under a key derived from the vault key rather than a
85
+ plain hash, so the ledger cannot confirm which documents you hold to anyone
86
+ without that key.
87
+ - Hardened before release after a security review:
88
+ - The ledger records the MAC of the bytes actually encrypted, read in the
89
+ same pass as the upload. Hashing the file before and after could not see a
90
+ change made and undone mid-upload, and `sf verify` would then have called a
91
+ file backed up that the vault did not hold.
92
+ - Ledger records carry a tag under the vault-derived key and a device id;
93
+ forged lines, and lines copied from another machine, are ignored.
94
+ - `SF_EMAIL` and `SF_PASSWORD` take precedence over a running agent, so a
95
+ script cannot be redirected to a different account.
96
+ - A lock file stops two agents from starting at once, and an agent that is
97
+ still revoking its session cannot delete the socket of the one that replaced
98
+ it.
99
+ - `sf status` no longer postpones the idle lock.
100
+ - Stopping wipes keys before touching the network, and its token refresh and
101
+ revoke share a 5 second budget, so an unreachable server cannot keep the
102
+ agent alive. An upload already running keeps its own copy of the key.
103
+ - The socket lives in `~/.shieldfive/run` everywhere, so cron jobs and other
104
+ minimal environments find the agent.
105
+
106
+ ### Notes
107
+
108
+ - `sf login` has not been run against production. The pieces are covered by
109
+ offline tests, including one that runs the agent as its own process against a
110
+ local stub of the auth and verify endpoints. Sign-in, unlock and session
111
+ refresh against the live backend are not.
112
+ - The agent does not run on Windows. `SF_EMAIL` and `SF_PASSWORD` keep working
113
+ there, and everywhere, exactly as before.
114
+ - The ledger starts empty. Existing `.shieldfive-sync.json` manifests are not
115
+ imported: they hold no content hash to check a claim against.
116
+
8
117
  ## 0.2.1 - 2026-09-14
9
118
 
10
119
  ### Fixed
package/README.md CHANGED
@@ -11,8 +11,9 @@
11
11
 
12
12
  The point of this tool being open source is that you do not have to trust a
13
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
+ server. The only bytes that leave your machine are ciphertext (post-quantum
15
+ hybrid: ML-KEM-1024 + X25519 key encapsulation, AES-256-GCM chunks) and a short
16
+ cryptographic proof. Two files carry the whole story:
16
17
 
17
18
  - [`src/uploadCrypto.mjs`](src/uploadCrypto.mjs) — the encryption applied to
18
19
  every chunk and to the filename.
@@ -41,6 +42,11 @@ size, uploading nothing.
41
42
  large file.
42
43
  - `sf sync` is **append-only**: it uploads new and changed files; it does not
43
44
  yet mirror local deletions or renames into the vault.
45
+ - **`sf login` and the agent have not been run against production.** They are
46
+ covered by offline tests, including one that runs the agent as its own process
47
+ and reaches it from separate `sf` processes against a local stub of the auth
48
+ and verify endpoints. Sign-in, unlock and session refresh against the live
49
+ backend are not covered.
44
50
 
45
51
  ## Requirements
46
52
 
@@ -66,27 +72,65 @@ trust it):
66
72
  git clone https://github.com/shieldfive/cli.git
67
73
  cd cli
68
74
  npm install # @shieldfive/crypto (+ libsodium), @supabase/supabase-js, @noble/*
69
- npm test # 40/40
75
+ npm test # 107 tests
70
76
  ```
71
77
 
72
78
  ## Commands
73
79
 
74
80
  ```
75
- sf encrypt <folder> encrypt each file locally, upload nothing (no account needed)
76
- sf push <folder> sign in, unlock, encrypt, upload every file once
81
+ sf login [--idle=<hours>] sign in once; an agent holds the session in memory (locks after 8 h idle)
82
+ sf status is an agent running, and for which account
83
+ sf logout [--everywhere] revoke the session and stop the agent; --everywhere signs out every device
84
+ sf push <folder> encrypt and upload every file once
77
85
  sf sync <folder> [--watch] [--interval=N] upload new/changed files; --watch keeps a poll loop (N seconds, default 5)
86
+ sf verify <file>... report whether each file is safely stored in your vault
87
+ sf encrypt <folder> encrypt each file locally, upload nothing (no account needed)
88
+ sf inspect <folder> read-only recursive migration inventory; upload nothing
78
89
  ```
79
90
 
80
91
  `sf push` and `sf sync` pick the direct or multipart upload path automatically
81
- from the file size. `sf sync` writes a `.shieldfive-sync.json` manifest in the
82
- target folder that records what has already been uploaded (by size and mtime),
83
- so unchanged files are skipped and an interrupted run does not re-upload
84
- everything.
92
+ from the file size.
93
+
94
+ `sf inspect` reports JSON counts of files, directories, bytes and skipped entries.
95
+ It includes nested/hidden files and empty folders, reads metadata only, and
96
+ does not follow symbolic links. Exit code 2 means entries were skipped. It does
97
+ not upload anything or prove that a migration has completed. Current push/sync
98
+ remain top-level only; do not use their completion as proof of a whole-tree copy.
99
+
100
+ With an agent running, `sf sync` records uploads in the agent's ledger (see
101
+ [What the agent can and cannot do](#what-the-agent-can-and-cannot-do)) and
102
+ `sf verify` works. Without one, `sf sync` writes a `.shieldfive-sync.json`
103
+ manifest in the target folder that records what has already been uploaded (by
104
+ size and mtime), so unchanged files are skipped and an interrupted run does not
105
+ re-upload everything; `sf verify` needs the agent.
85
106
 
86
107
  ## Running the live commands
87
108
 
88
- `sf push` and `sf sync` need only your ShieldFive account. Your password is
89
- typed, never passed on the command line:
109
+ ### With `sf login`
110
+
111
+ ```sh
112
+ sf login
113
+ sf push ./my-folder
114
+ sf sync ./my-folder --watch
115
+ sf verify ./my-folder/tax-return-2025.pdf
116
+ sf logout
117
+ ```
118
+
119
+ `sf login` prompts for your email, your password and, if it differs, your vault
120
+ password. It never reads them from the environment and there is no flag for
121
+ them. It then starts an agent in the background and exits; every later command
122
+ talks to that agent and needs nothing exported.
123
+
124
+ If `SF_EMAIL` and `SF_PASSWORD` are also set, `sf push` and `sf sync` sign in
125
+ with those instead and tell you an agent is running, so a script written for one
126
+ account is never sent to another. `sf push` exits 2 if a file changed while it
127
+ was being uploaded: the vault then holds the version that was read, not the file
128
+ as it is now.
129
+
130
+ ### Without an agent
131
+
132
+ `sf push` and `sf sync` still work from environment variables, exactly as
133
+ before. Your password is typed, never passed on the command line:
90
134
 
91
135
  ```sh
92
136
  export SF_EMAIL=you@example.com
@@ -116,26 +160,100 @@ Enter the current code from your authenticator. In a non-interactive context
116
160
  (scripts, CI) set `SF_TOTP_CODE` to the current code instead of being prompted.
117
161
  Only TOTP is supported; SMS and other factors are not.
118
162
 
163
+ With `sf login` you are asked once. The agent refreshes the stepped-up session
164
+ on its own, so `sf sync --watch` keeps working on a two-factor account until the
165
+ agent locks or you log out.
166
+
167
+ ## What the agent can and cannot do
168
+
169
+ The agent keeps two things in memory: your signed-in session and your unlocked
170
+ vault key. Neither is written to disk. It listens on a Unix socket in
171
+ `~/.shieldfive/run`, a directory only your user can enter, and refuses to start
172
+ if that directory is a symlink, owned by someone else or open to other users.
173
+ Only one agent runs at a time.
174
+
175
+ It accepts six requests: `status`, `upload`, `sync`, `verify`, `lock` and
176
+ `logout`. It cannot list what is in your vault, download a file, decrypt
177
+ anything, or hand out the key, because there is no request for any of those. A
178
+ process that reaches the socket can put files into your vault and ask whether
179
+ files are backed up. It cannot read your vault through the agent.
180
+
181
+ Uploads are recorded in `~/.shieldfive/ledger/<account>.jsonl`: the path, size,
182
+ time, vault file id, and an HMAC of the bytes that were actually encrypted, under
183
+ a key derived from your vault key. A plain hash would let anyone holding the
184
+ ledger confirm whether you have a particular known document; the HMAC does not,
185
+ without your vault key. Each record also carries a tag under that key, so a line
186
+ added to the ledger by anything other than the agent is ignored, and records
187
+ made on another machine do not count on this one.
188
+
189
+ `sf verify` reports a file as **backed up** only when the bytes on disk now
190
+ match an upload in the ledger and the server confirms, at that moment, that the
191
+ upload is stored, complete, intact and not in your Bin. It never decides by name
192
+ or size. The other answers:
193
+
194
+ | Answer | Meaning |
195
+ |---|---|
196
+ | `NOT confirmed` | these bytes were uploaded, but the server cannot confirm they are still safely stored |
197
+ | `changed since upload` | this path was uploaded, but the file has changed since |
198
+ | `no upload record` | this agent never uploaded these bytes; they may still be in your vault from another device |
199
+ | `unreadable` | the local file could not be read |
200
+
201
+ `no upload record` does not mean the file is missing from your vault. Do not
202
+ delete anything on the strength of that answer.
203
+
204
+ The agent locks itself after 8 hours without an upload, sync or verify
205
+ (`sf login --idle=<hours>` to change it; `sf status` does not count). Locking and
206
+ `sf logout` both overwrite the key in memory first and then sign the session out
207
+ on the server. Sessions on ShieldFive do not expire on their own, so a session
208
+ that is forgotten rather than signed out would stay valid. If the server cannot
209
+ be reached when you log out, `sf logout` says the session is still valid and
210
+ exits 1; run `sf login` and then `sf logout --everywhere` once you are online.
211
+
212
+ Limits:
213
+
214
+ - Windows is not supported. Use `SF_EMAIL` and `SF_PASSWORD` there.
215
+ - Node cannot see which process connected to the socket, so directory
216
+ permissions are the only gate. This is also how `ssh-agent` works on macOS.
217
+ - Overwriting the key in memory is best-effort. A garbage-collected runtime can
218
+ copy key material during crypto operations.
219
+ - The ledger is per device. A file uploaded from another machine shows as
220
+ `no upload record` here.
221
+
222
+ The full design, including the threat model, is in
223
+ [`docs/agent-design.md`](docs/agent-design.md).
224
+
119
225
  ## How the upload works (for auditors)
120
226
 
121
- The upload uses **chunked AES-GCM** for file content and issues a
122
- server-verified HMAC proof. (The `sf encrypt` demo uses the post-quantum hybrid
123
- suite; the sync/push path uses AES-GCM, which is what the vault's upload
124
- protocol and server-side proof expect.)
227
+ Uploads are written in the format the web app writes by default:
228
+ `cipher_version` 3, suite `0x03` (post-quantum hybrid) in the v1 wire format
229
+ (`@shieldfive/crypto` `spec/format-v1.md`), using the library's own stream
230
+ encoder.
125
231
 
126
232
  - **Filename** — encrypted with AES-GCM under a key derived from your vault root
127
- key via Argon2id (`encryptMetadataV4`). The server stores ciphertext; it never
128
- sees the name. A keyed HMAC of the lowercased name (`hashMetadataV4`) lets the
129
- server deduplicate without learning the name.
130
- - **File content** — each chunk is AES-GCM encrypted under a per-file content
131
- key (itself wrapped by your root key). The nonce is a 4-byte random prefix
132
- followed by an 8-byte big-endian chunk counter, so every chunk has a distinct
133
- nonce.
134
- - **Upload proof** — `HMAC-SHA256(proofKey, prefix || ciphertext)` over the first
135
- chunk, where `prefix = [version=1][cipherVersion=1][chunkSize u32 BE][noncePrefix 4]`.
136
- The server issues `proofKey` when it creates the session and verifies the proof
137
- when finalizing. It ties the stored ciphertext to the session without the
138
- server ever seeing plaintext.
233
+ key via Argon2id (`encryptMetadataV4`), then, at finalize, re-sealed with the
234
+ file's row id as additional data (v6, `encryptNameV6`), so the server cannot
235
+ move one file's name onto another row. A keyed HMAC of the lowercased name
236
+ (`hashMetadataV4`) lets the server deduplicate without learning the name.
237
+ - **File content** — a MAC'd header carries the file's `file_id` (the row id the
238
+ server assigned, so the stored object is bound to its row), the plaintext size
239
+ and the chunk count. The content key combines a per-file envelope key (wrapped
240
+ by your root key in `csk_wrapped`) with an ML-KEM-1024 + X25519 encapsulation
241
+ to your vault identity, which is derived on this machine from your root key,
242
+ as the web app derives it; the server cannot substitute a recipient. Each 5 MiB
243
+ chunk is AES-256-GCM with its index, the total and an is-final flag in the
244
+ additional data, so a dropped, reordered or truncated chunk fails to decrypt.
245
+ - **Upload proof** — base64 of `[3][3] || HMAC-SHA256(proofKey, [3][3] || header
246
+ || frame_0)` (`buildUploadProofV3` in `@shieldfive/crypto`, the same function
247
+ the web and the MCP server use). The server issues `proofKey` when it creates
248
+ the session and verifies the proof against the stored object when finalizing.
249
+ - **Parts** — each storage part is exactly one encrypted chunk frame; part 1 also
250
+ carries the header.
251
+
252
+ Versions up to 0.3.0 wrote the legacy v0 format (AES-GCM chunks under a random
253
+ nonce prefix, no header): no truncation detection, no row binding and no
254
+ post-quantum layer. Files already uploaded that way still open in the apps;
255
+ this client no longer writes it.
256
+
139
257
  - **Direct** (≤ 5 MiB) — the single encrypted chunk is `PUT` at a presigned S3
140
258
  URL the server issues with the session. The URL's SigV4 signature is the only
141
259
  credential and it authorises exactly one object key, so the request carries no
@@ -144,29 +262,43 @@ protocol and server-side proof expect.)
144
262
  Because the signature covers `host` only, nothing on this path binds the body:
145
263
  the server compares the client's `ciphertextHash` against the client's own
146
264
  `partSha1Array[0]`, so they always agree. Integrity here rests on the upload
147
- proof and on AES-GCM's tag at download, not on a wire checksum.
265
+ proof and on the header MAC and chunk tags at download, not on a wire checksum.
148
266
  - **Multipart** (> 5 MiB) — the file is streamed one 5 MiB chunk at a time (never
149
267
  loaded whole into memory), each chunk uploaded as a Backblaze part. The
150
268
  ciphertext hash the server checks is SHA-1 over the concatenated raw part
151
269
  digests; the server finishes the large file with the ordered part list.
152
270
 
153
271
  The mock end-to-end test in [`test/upload.flow.test.mjs`](test/upload.flow.test.mjs)
154
- captures every byte this client would send, decrypts each part with the key
155
- recovered from the session envelope, and asserts the result equals the original
156
- file — a machine-checked demonstration that only ciphertext is uploaded.
272
+ captures every byte this client would send, opens the stored object with
273
+ `@shieldfive/crypto`'s reference reader from nothing but the session fields and
274
+ the root key, and asserts the result equals the original file and the header's
275
+ `file_id` equals the row id. [`test/v1Format.test.mjs`](test/v1Format.test.mjs)
276
+ checks the shared vectors in [`test/vectors/v3-upload.json`](test/vectors/v3-upload.json)
277
+ (regenerate with `node scripts/generate-vectors.mjs`) against the library's
278
+ blob and streaming readers.
157
279
 
158
280
  ## Layout
159
281
 
160
282
  - `src/cli.mjs` — the `sf` entry point (argument parsing, command dispatch)
161
- - `src/auth.mjs` — Supabase sign-in to a Bearer token
283
+ - `src/auth.mjs` — sign-in to a Bearer token through ShieldFive's sign-in route,
284
+ with two-factor step-up
285
+ - `src/loginSecret.mjs` — the login secret derived from your password; for
286
+ accounts on the current scheme the password itself is never sent
287
+ - `src/argon2.mjs` — Argon2id, native when available, WebAssembly otherwise
162
288
  - `src/vault.mjs` / `src/unlock.mjs` — fetch the wrapped vault key, unwrap the
163
289
  root key from your password (Argon2id / PBKDF2)
164
- - `src/uploadCrypto.mjs` — filename and chunk encryption, upload proof, multipart
165
- ciphertext hash
290
+ - `src/uploadCrypto.mjs` — filename encryption, the suite-0x03 part writer,
291
+ upload proof, multipart ciphertext hash
166
292
  - `src/upload.mjs` — create session, encrypt, upload (direct + multipart),
167
293
  finalize; the streaming chunk reader
168
294
  - `src/sync.mjs` — `sf sync`: manifest, change detection, reconcile pass, watch
169
295
  loop (reuses `upload.mjs`)
296
+ - `src/prompt.mjs` — terminal prompts; the password prompt echoes nothing
297
+ - `src/agent/` — `sf login`'s agent: `server.mjs` (the process and its six
298
+ requests), `client.mjs`, `protocol.mjs` (the request allowlist), `ledger.mjs`
299
+ (HMAC upload ledger and `verify` classification), `paths.mjs` (socket
300
+ directory checks), `main.mjs` (entry point and session handoff)
301
+ - `docs/agent-design.md` — design record and threat model for the agent
170
302
  - `src/sfCrypto.mjs` — the post-quantum hybrid encrypt/decrypt used by the
171
303
  `sf encrypt` demo
172
304
  - `test/*.test.mjs` — round-trip guarantees plus the mock end-to-end upload and
package/SECURITY.md CHANGED
@@ -63,9 +63,13 @@ not pursue civil claims or refer law enforcement against researchers who:
63
63
 
64
64
  ## Bug bounty
65
65
 
66
- ShieldFive operates a paid bug bounty program. For current scope, reward tiers,
67
- rules of engagement, and submission instructions, see
68
- https://shieldfive.com/security/bug-bounty.
66
+ **There is no bug bounty.** ShieldFive ran one until 2026-07; it closed, and
67
+ `/security/bug-bounty` now redirects to the security page. Reports are answered
68
+ on the timelines above, and credited if you want credit. They are not paid.
69
+
70
+ This section previously said the opposite and pointed at that redirected URL.
71
+ It is corrected here rather than removed, so anyone who read the old text finds
72
+ out what changed.
69
73
 
70
74
  ## Scope
71
75
 
@@ -79,6 +83,6 @@ Out of scope for *this* repository (report elsewhere or not at all):
79
83
  [`@shieldfive/crypto`](https://github.com/shieldfive/crypto).
80
84
  - Vulnerabilities in dependencies (`@noble/*`, `@supabase/supabase-js`) — report
81
85
  those upstream.
82
- - Server-side issues in the ShieldFive backend — report via the bug bounty
83
- program above.
86
+ - Server-side issues in the ShieldFive backend — same address,
87
+ `security@shieldfive.com`, different codebase.
84
88
  - Attacks that require an attacker to already control the user's device.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@shieldfive/cli",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
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: encrypt a folder on your machine and sync it to your EU-hosted vault with post-quantum hybrid encryption (ML-KEM-1024 + X25519). Read the code; it encrypts before upload.",
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
  }
@@ -0,0 +1,102 @@
1
+ // ShieldFive CLI — talk to a running agent.
2
+
3
+ import { connect } from 'node:net'
4
+
5
+ import { socketPath } from './paths.mjs'
6
+ import { encode, lineSplitter } from './protocol.mjs'
7
+
8
+ export class AgentUnavailableError extends Error {
9
+ constructor(message) {
10
+ super(message)
11
+ this.name = 'AgentUnavailableError'
12
+ this.code = 'agent_unavailable'
13
+ }
14
+ }
15
+
16
+ export class AgentRequestError extends Error {
17
+ constructor(code, message) {
18
+ super(message)
19
+ this.name = 'AgentRequestError'
20
+ this.code = code
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Send one request and resolve with the result.
26
+ *
27
+ * `timeoutMs: 0` disables the timeout, which uploads and syncs need: a large
28
+ * file can take longer than any fixed number.
29
+ */
30
+ export function request(op, args = {}, { path, timeoutMs = 10_000 } = {}) {
31
+ return new Promise((resolve, reject) => {
32
+ // Resolved here rather than as a default parameter, so a platform the agent
33
+ // does not support rejects this promise instead of throwing out of it.
34
+ let socketFile
35
+ try {
36
+ socketFile = path ?? socketPath()
37
+ } catch (err) {
38
+ reject(err)
39
+ return
40
+ }
41
+
42
+ let settled = false
43
+ const socket = connect({ path: socketFile })
44
+
45
+ const settle = (fn, value) => {
46
+ if (settled) return
47
+ settled = true
48
+ clearTimeout(timer)
49
+ socket.destroy()
50
+ fn(value)
51
+ }
52
+
53
+ const timer = timeoutMs
54
+ ? setTimeout(
55
+ () => settle(reject, new AgentRequestError('timeout', `Agent did not answer within ${timeoutMs} ms.`)),
56
+ timeoutMs,
57
+ )
58
+ : null
59
+
60
+ socket.on('error', (err) => {
61
+ if (err.code === 'ENOENT' || err.code === 'ECONNREFUSED') {
62
+ settle(reject, new AgentUnavailableError('The ShieldFive agent is not running. Run sf login.'))
63
+ } else {
64
+ settle(reject, err)
65
+ }
66
+ })
67
+
68
+ socket.setEncoding('utf8')
69
+ socket.on(
70
+ 'data',
71
+ lineSplitter((line) => {
72
+ let message
73
+ try {
74
+ message = JSON.parse(line)
75
+ } catch {
76
+ return settle(reject, new AgentRequestError('bad_response', 'Agent sent something that is not JSON.'))
77
+ }
78
+ if (message.ok) settle(resolve, message.result)
79
+ else settle(reject, new AgentRequestError(message.error?.code ?? 'error', message.error?.message ?? 'Agent refused.'))
80
+ }),
81
+ )
82
+ socket.on('close', () =>
83
+ settle(reject, new AgentRequestError('closed', 'Agent closed the connection without answering.')),
84
+ )
85
+
86
+ socket.on('connect', () => socket.write(encode({ id: 1, op, args })))
87
+ })
88
+ }
89
+
90
+ /**
91
+ * The agent's status, or null when no agent is listening or the agent cannot
92
+ * run on this platform. Callers fall back to environment credentials on null,
93
+ * so an unsupported platform must answer null, not throw.
94
+ */
95
+ export async function agentStatus(options = {}) {
96
+ try {
97
+ return await request('status', {}, { timeoutMs: 2_000, ...options })
98
+ } catch (err) {
99
+ if (err instanceof AgentUnavailableError || err.code === 'unsupported_platform') return null
100
+ throw err
101
+ }
102
+ }