aegiscode 6.8.10 → 6.8.12

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.
@@ -0,0 +1,834 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * record-vault.js — put a sealed φ(α) record where a human can find it, and
5
+ * never put the key there.
6
+ *
7
+ * ## The problem this file exists for
8
+ *
9
+ * A sealed record is only worth minting if someone can look at it later. Kept
10
+ * at `$AEGIS_HOME/fingerprints/`, it is visible on exactly one machine, and the
11
+ * question a record answers ("what was this session, and who sealed it?") is
12
+ * asked from elsewhere. So the record is published to a shared folder — here,
13
+ * `gdrive:AEGIS-AGPL` — and the local record is *linked* to the copy that
14
+ * lives there.
15
+ *
16
+ * The opposite is true of the key, and that asymmetry is the whole design.
17
+ * A record is evidence meant to travel: it carries a 12-hex derived
18
+ * `keyFingerprint` and an HMAC tag, and nothing in it is secret. The key is an
19
+ * HMAC secret: whoever holds it can mint records indistinguishable from the
20
+ * owner's, which means a key in cloud storage is not a backup, it is a forgery
21
+ * kit with a share link. `AEGIS-AGPL/README` says exactly this about the copy
22
+ * already sitting there, and that copy is the reason this module refuses
23
+ * anything key-shaped rather than trusting the caller to pass the right path.
24
+ *
25
+ * ## What "linked" means, precisely
26
+ *
27
+ * Publishing writes two objects and flips one local file:
28
+ *
29
+ * <root>/records/<fp>-<behaviour>.<stamp>.json the sealed bytes,
30
+ * byte-identical to
31
+ * the local file
32
+ * <root>/records/<fp>-<behaviour>.<stamp>.anchor.json the link: Drive id,
33
+ * url, sha256 of the
34
+ * exact bytes, and the
35
+ * record's own id +
36
+ * attestation
37
+ * <root>/records/index.jsonl append-only ledger
38
+ * <local record>.anchor.json same anchor, beside
39
+ * the record, so
40
+ * `anchor` can check
41
+ * the copy later
42
+ *
43
+ * The published record is the *unmodified* sealed bytes. That is deliberate and
44
+ * it is the point of the sha256 in the anchor: anyone who downloads the copy and
45
+ * gets the same digest is holding exactly what was sealed, and can re-run
46
+ * `fingerprint verify` on it. An earlier shape put the Drive link *inside* the
47
+ * record, which cannot work — the digest of the file would change when the link
48
+ * was added to it — and would have been worse than not working: an un-attested
49
+ * field inside a signed object reads as if the seal covered it. It does not. The
50
+ * seal covers `ATTESTED_FIELDS_V3` and nothing else, so the link lives outside
51
+ * the record, where `fp.verify` cannot be misread as vouching for it.
52
+ *
53
+ * ## The refusal, and why it is here rather than in an instruction
54
+ *
55
+ * `publish` re-checks every byte before it leaves the machine, using the
56
+ * sealer's own rule (`fp.assertNoLeak` from the vendored module) plus the shapes
57
+ * a *file* can have that a record cannot: a bare high-entropy token, a PEM
58
+ * private key, a 64-hex key, a path named `keys/agent.key`. It throws rather
59
+ * than warning, for the same reason `fingerprint.mint` throws: a warning is
60
+ * something a scripted publish never reads. `audit` is the other half — it
61
+ * inspects what is *already* in the vault and names it, so the answer to "is a
62
+ * key in there?" is a command rather than a memory.
63
+ *
64
+ * ## Testing
65
+ *
66
+ * Nothing here talks to a network directly: every remote operation is one
67
+ * `rclone` invocation through `rcloneBinary()`, and the binary is overridable
68
+ * (`AEGIS_VAULT_RCLONE`, `--rclone`). `test/fingerprint-vault.test.mjs` drives
69
+ * the whole surface against a stub, so the suite is hermetic and never touches
70
+ * the user's Drive. The remote/root are overridable the same way
71
+ * (`AEGIS_VAULT_REMOTE`/`AEGIS_VAULT_ROOT`), which is also what keeps a
72
+ * misconfigured vault from writing into some unrelated folder.
73
+ */
74
+
75
+ const crypto = require('node:crypto');
76
+ const fs = require('node:fs');
77
+ const os = require('node:os');
78
+ const path = require('node:path');
79
+ const { execFileSync } = require('node:child_process');
80
+
81
+ const fp = require('./fingerprint.js');
82
+ const authorship = require('./authorship-key.js');
83
+
84
+ /** The folder the sealed records live in, and the folder that must not hold a key. */
85
+ const DEFAULT_REMOTE = 'gdrive';
86
+ const DEFAULT_ROOT = 'AEGIS-AGPL';
87
+ const RECORDS_DIR = 'records';
88
+ const INDEX_NAME = 'index.jsonl';
89
+ const ANCHOR_SUFFIX = '.anchor.json';
90
+ const ANCHOR_VERSION = 1;
91
+ const ANCHOR_KIND = 'aegiscode.record.anchor';
92
+ /** The ledger's own line kind. Every object we emit is labelled, so the audit
93
+ * can validate a known shape instead of guessing from field names. */
94
+ const INDEX_KIND = 'aegiscode.record.index';
95
+
96
+ const RCLONE_ENV = 'AEGIS_VAULT_RCLONE';
97
+ const REMOTE_ENV = 'AEGIS_VAULT_REMOTE';
98
+ const ROOT_ENV = 'AEGIS_VAULT_ROOT';
99
+
100
+ /** Every remote call is bounded: a hung rclone must not hang a mint or a GUI turn. */
101
+ const RCLONE_TIMEOUT_MS = 60_000;
102
+
103
+ /** Longest file `audit` will read to inspect. Anchors and records are all tiny. */
104
+ const MAX_INSPECT_BYTES = 2 * 1024 * 1024;
105
+
106
+ /** How many vault objects one `audit` walks before it says it stopped. */
107
+ const MAX_AUDIT_FILES = 500;
108
+
109
+ /**
110
+ * Paths that are key material by their *name*, whatever they contain.
111
+ *
112
+ * `keys/` is the directory `keygen` writes into and the one already present in
113
+ * the AGPL vault; `agent.key` is the engine's name for the same secret. A vault
114
+ * that accepts these can be talked into publishing a key by someone who only
115
+ * passes a path, which is the exact failure this module exists to prevent.
116
+ */
117
+ const KEY_PATH_PATTERNS = [
118
+ /(^|\/)keys?\//i, // keys/agent.key, key/agent.key
119
+ /\.key$/i, // authorship.key, agent.key
120
+ /\.pem$/i, // PEM private key
121
+ /(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i, // ssh private keys
122
+ /(^|\/)agent\.key(\.|$)/i,
123
+ ];
124
+
125
+ /** A whole file that is one long token is not a record and is plausibly a secret. */
126
+ const BARE_TOKEN = /^[A-Za-z0-9_\-+/=]{40,}$/;
127
+
128
+ /** A whole file that is 32+ hex is a raw digest or a hex-encoded key. */
129
+ const BARE_HEX = /^[0-9a-fA-F]{32,}$/;
130
+
131
+ const PEM_PRIVATE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;
132
+
133
+ /** `--flag value`; returns null when absent, so callers can fall back in order. */
134
+ function flag(argv, name, fallback = null) {
135
+ const list = Array.isArray(argv) ? argv : [];
136
+ const i = list.indexOf(name);
137
+ return i !== -1 && list[i + 1] !== undefined && !String(list[i + 1]).startsWith('--')
138
+ ? list[i + 1]
139
+ : fallback;
140
+ }
141
+
142
+ function has(argv, name) {
143
+ return (Array.isArray(argv) ? argv : []).includes(name);
144
+ }
145
+
146
+ /** The rclone binary: `--rclone`, then the env, then PATH. */
147
+ function rcloneBinary(env = process.env, argv = []) {
148
+ return flag(argv, '--rclone') || env[RCLONE_ENV] || 'rclone';
149
+ }
150
+
151
+ /**
152
+ * Where the vault is. Both halves are injectable because both are things a
153
+ * caller can get wrong in a way that writes a record somewhere unintended.
154
+ */
155
+ function vaultTarget(env = process.env, argv = []) {
156
+ return {
157
+ remote: flag(argv, '--remote') || env[REMOTE_ENV] || DEFAULT_REMOTE,
158
+ root: flag(argv, '--root') || env[ROOT_ENV] || DEFAULT_ROOT,
159
+ rclone: rcloneBinary(env, argv),
160
+ // Carried so `rcloneRun` can hand the *injected* environment to the child.
161
+ // Passing rclone the ambient process env instead made every AEGIS_VAULT_*
162
+ // and every rclone variable (config dir, proxy, a stubbed binary's own
163
+ // settings) a no-op in the child — the caller sets the environment, so the
164
+ // caller's environment is what the subprocess gets.
165
+ env,
166
+ };
167
+ }
168
+
169
+ function remoteSpec(target, ...segments) {
170
+ return `${target.remote}:${[target.root, ...segments].filter(Boolean).join('/')}`;
171
+ }
172
+
173
+ /**
174
+ * A path *below* the root, however it was written: `records/x.json`,
175
+ * `<root>/records/x.json`, or an absolute `remote:…` spec. Everything that
176
+ * reads tolerates all three, because the anchor stores the browsable
177
+ * root-prefixed form (a human reads `AEGIS-AGPL/records/x.json`) while rclone
178
+ * wants it relative.
179
+ */
180
+ function relativeToRoot(target, relPath) {
181
+ let rel = String(relPath || '').replace(/^\/+/, '');
182
+ const spec = `${target.remote}:`;
183
+ if (rel.startsWith(spec)) rel = rel.slice(spec.length);
184
+ if (rel === target.root) return '';
185
+ if (rel.startsWith(`${target.root}/`)) rel = rel.slice(target.root.length + 1);
186
+ return rel;
187
+ }
188
+
189
+ /** `relativeToRoot` + `remoteSpec`: one rclone spec from any of the three forms. */
190
+ function remoteSpecOf(target, relPath) {
191
+ const rel = relativeToRoot(target, relPath);
192
+ return rel ? remoteSpec(target, rel) : remoteSpec(target);
193
+ }
194
+
195
+ /**
196
+ * One rclone call.
197
+ *
198
+ * stderr is captured rather than inherited: rclone prints a client_id NOTICE on
199
+ * every invocation on this host, and a warning on a CLI's stderr for a command
200
+ * whose output is JSON is noise a caller has to filter. On failure the message
201
+ * carries rclone's own last line, because "exit status 1" is not a diagnosis.
202
+ */
203
+ function rcloneRun(target, args, { timeout = RCLONE_TIMEOUT_MS } = {}) {
204
+ try {
205
+ return execFileSync(target.rclone, args, {
206
+ encoding: 'utf8',
207
+ timeout,
208
+ stdio: ['ignore', 'pipe', 'pipe'],
209
+ maxBuffer: 32 * 1024 * 1024,
210
+ env: target.env ? { ...process.env, ...target.env } : process.env,
211
+ });
212
+ } catch (e) {
213
+ const err = String((e && e.stderr) || '').trim().split('\n').filter((l) => !/NOTICE:/.test(l)).pop();
214
+ const msg = err || (e && e.message) || String(e);
215
+ const wrapped = new Error(`vault: rclone ${args[0]} failed — ${msg}`);
216
+ wrapped.code = 'ERCLONE';
217
+ wrapped.stderr = String((e && e.stderr) || '');
218
+ throw wrapped;
219
+ }
220
+ }
221
+
222
+ /** A shelf directory for temporary uploads. Removed by the caller. */
223
+ function tempDir() {
224
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'aegis-vault-'));
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // the guard: what may leave the machine
229
+ // ---------------------------------------------------------------------------
230
+
231
+ /**
232
+ * Inspect one file's *content* and *name* for key material.
233
+ *
234
+ * The JSON half delegates to the sealer's own `fp.assertNoLeak`. That is not a
235
+ * convenience: if this file carried a second, hand-written copy of the leak rule
236
+ * the two would drift, and the drift would be invisible — the vault would allow
237
+ * what the sealer forbids, on the one code path whose whole job is keeping a
238
+ * secret off the network. A throw from `assertNoLeak` is a refusal here.
239
+ *
240
+ * @returns {{dangerous: boolean, reason: string|null}}
241
+ */
242
+ function inspect(name, text, { secret = null, keyPath = null } = {}) {
243
+ const where = String(name || '');
244
+
245
+ for (const pattern of KEY_PATH_PATTERNS) {
246
+ if (pattern.test(where)) {
247
+ return { dangerous: true, reason: `the path looks like key material (${pattern})` };
248
+ }
249
+ }
250
+
251
+ if (keyPath && path.resolve(where) === path.resolve(keyPath)) {
252
+ return { dangerous: true, reason: 'this path IS the authorship key' };
253
+ }
254
+
255
+ const body = String(text === null || text === undefined ? '' : text);
256
+ const trimmed = body.trim();
257
+
258
+ if (secret && trimmed.includes(String(secret))) {
259
+ return { dangerous: true, reason: 'the content carries the authorship key verbatim' };
260
+ }
261
+ if (PEM_PRIVATE.test(body)) {
262
+ return { dangerous: true, reason: 'the content is a PEM private key' };
263
+ }
264
+
265
+ // Only when the whole file is one token: a record is JSON, so this can never
266
+ // fire on a legitimate record, and it is the shape a raw key file has.
267
+ const singleLine = trimmed.split('\n').length === 1;
268
+ if (singleLine && BARE_TOKEN.test(trimmed) && !BARE_HEX.test(trimmed)) {
269
+ return { dangerous: true, reason: 'the content is a bare high-entropy token (a raw secret)' };
270
+ }
271
+ if (singleLine && BARE_HEX.test(trimmed)) {
272
+ return { dangerous: true, reason: 'the content is an unlabelled hex blob (a raw digest or key)' };
273
+ }
274
+
275
+ // A parsed object is checked by the sealer's own rule, with one exception:
276
+ // our own anchor is a *known* artifact whose whole job is to carry a 64-hex
277
+ // sha256, so running the record rule over it reports a long hex run and calls
278
+ // the vault dirty when it is not. Known shapes get their shapes validated;
279
+ // everything else gets the record rule, unweakened.
280
+ let parsed = null;
281
+ try {
282
+ parsed = JSON.parse(body);
283
+ } catch {
284
+ parsed = null;
285
+ }
286
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
287
+ // Anything this module emits is labelled `aegiscode.…`, and a labelled
288
+ // artifact is validated by its own shape. Unlabelled JSON — a record, or
289
+ // anything a user dropped in — gets the record rule, unweakened.
290
+ if (typeof parsed.kind === 'string' && parsed.kind.startsWith('aegiscode.')) {
291
+ return inspectArtifact(parsed, secret);
292
+ }
293
+ try {
294
+ fp.assertNoLeak(parsed, secret || '');
295
+ } catch (e) {
296
+ return { dangerous: true, reason: (e && e.message) || 'failed the leak check' };
297
+ }
298
+ }
299
+
300
+ return { dangerous: false, reason: null };
301
+ }
302
+
303
+ /**
304
+ * The audit's rule for an artifact this module emits — a link
305
+ * (`kind: aegiscode.record.anchor`) or a ledger line
306
+ * (`kind: aegiscode.record.index`).
307
+ *
308
+ * Their digest fields are *expected* — `sha256` is 64 hex by definition, and
309
+ * `attestation` is the 32-hex tag copied out of the record — so they are
310
+ * validated rather than flagged. Anywhere else in the artifact, a long hex run
311
+ * is still a finding, and the key is refused verbatim wherever it appears. This
312
+ * is not a weakening of the rule: it is the difference between "an unknown file
313
+ * carries something key-shaped" (a finding) and "our own index line carries the
314
+ * sha256 it is made of" (not one).
315
+ */
316
+ function inspectArtifact(anchor, secret) {
317
+ const expected = new Set(['sha256', 'attestation', 'code']);
318
+ for (const [key, value] of Object.entries(anchor)) {
319
+ if (value === null || value === undefined) continue;
320
+ const text = Array.isArray(value) ? value.join('\u0000') : String(value);
321
+ if (secret && text.includes(String(secret))) {
322
+ return { dangerous: true, reason: `the link carries the authorship key verbatim in "${key}"` };
323
+ }
324
+ if (!expected.has(key) && fp.longHexRun(text)) {
325
+ return { dangerous: true, reason: `the link carries a long hex run in "${key}"` };
326
+ }
327
+ }
328
+ if (anchor.sha256 !== undefined && !/^[0-9a-f]{64}$/.test(String(anchor.sha256))) {
329
+ return { dangerous: true, reason: 'the link\'s sha256 is not a 64-hex digest' };
330
+ }
331
+ if (anchor.attestation !== undefined && !/^[0-9a-f]{32}$/.test(String(anchor.attestation))) {
332
+ return { dangerous: true, reason: 'the link\'s attestation is not a 32-hex tag' };
333
+ }
334
+ return { dangerous: false, reason: null };
335
+ }
336
+
337
+ /** `inspect`, as a throw. Used before anything is uploaded. */
338
+ function assertPublishable(name, text, opts = {}) {
339
+ const verdict = inspect(name, text, opts);
340
+ if (verdict.dangerous) {
341
+ throw new Error(
342
+ `vault: refusing to publish ${name} — ${verdict.reason}. ` +
343
+ 'The vault carries sealed records only: a key that reaches cloud storage can mint ' +
344
+ 'records indistinguishable from yours, so it is never a backup. Keep it in ' +
345
+ `${authorship.defaultKeyPath(opts.env || process.env)} (0600) and back it up to a ` +
346
+ 'local disk or a password manager.',
347
+ );
348
+ }
349
+ return true;
350
+ }
351
+
352
+ // ---------------------------------------------------------------------------
353
+ // naming
354
+ // ---------------------------------------------------------------------------
355
+
356
+ /** `<keyFingerprint>-<behaviour>.<stamp>` — ASCII, filename-safe, from the record. */
357
+ function baseName(record, createdAt = null) {
358
+ const behaviour = record && record.behaviour ? String(record.behaviour) : 'unobserved';
359
+ const stamp = String(createdAt || (record && record.createdAt) || new Date().toISOString())
360
+ .replace(/[:.]/g, '-');
361
+ return `${record.keyFingerprint}-${behaviour}.${stamp}`;
362
+ }
363
+
364
+ /** `https://drive.google.com/open?id=<id>` — an owner link. Sharing is never changed. */
365
+ function driveUrl(id) {
366
+ return id ? `https://drive.google.com/open?id=${encodeURIComponent(id)}` : null;
367
+ }
368
+
369
+ function sha256(text) {
370
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
371
+ }
372
+
373
+ // ---------------------------------------------------------------------------
374
+ // publish
375
+ // ---------------------------------------------------------------------------
376
+
377
+ /**
378
+ * Read the record to publish.
379
+ *
380
+ * A path or an in-memory record; the path form is preferred because the bytes
381
+ * on disk are the bytes `verify` was run against and the digest is then about a
382
+ * file rather than about a re-serialisation that might differ by whitespace.
383
+ */
384
+ function readRecord({ file = null, record = null, secret = null, env = process.env }) {
385
+ if (file) {
386
+ const abs = path.resolve(file);
387
+ if (!fs.existsSync(abs)) throw new Error(`vault: no record at ${abs}`);
388
+ const text = fs.readFileSync(abs, 'utf8');
389
+ // The guard runs FIRST, on the raw bytes, and that order is the whole
390
+ // point: parsing first means publishing a key file fails with "is not
391
+ // JSON" — true, and useless, because it says nothing about the actual
392
+ // problem, which is where the file was going. A refusal has to name what
393
+ // is wrong with what the user asked for.
394
+ assertPublishable(abs, text, { secret, keyPath: authorship.defaultKeyPath(env), env });
395
+ let parsed;
396
+ try {
397
+ parsed = JSON.parse(text);
398
+ } catch (e) {
399
+ throw new Error(`vault: ${abs} is not JSON — ${e.message}`);
400
+ }
401
+ return { text, record: parsed, file: abs, serialised: text };
402
+ }
403
+ if (record) {
404
+ const text = JSON.stringify(record, null, 2) + '\n';
405
+ return { text, record, file: null, serialised: text };
406
+ }
407
+ throw new Error('vault: publish needs a record file or a record');
408
+ }
409
+
410
+ /**
411
+ * Publish a sealed record, and link the local copy to the copy that travelled.
412
+ *
413
+ * @param {object} o
414
+ * @param {string} [o.file] path to the sealed record
415
+ * @param {object} [o.record] or the record itself
416
+ * @param {object} [o.env] env (injectable; tests)
417
+ * @param {string[]} [o.argv] flags: --remote --root --rclone --dry-run --no-index
418
+ * @param {boolean} [o.dryRun] resolve everything, upload nothing
419
+ * @param {boolean} [o.index] append to index.jsonl (default true)
420
+ * @param {string} [o.secret] the caller's key, if it has it — checked for leaks
421
+ * @param {Date|string} [o.now] publishedAt, injectable so a test can pin it
422
+ * @returns {{ok: boolean, anchor: object, url: string|null, remotePath: string, dryRun: boolean}}
423
+ */
424
+ function publish(o = {}) {
425
+ const env = o.env || process.env;
426
+ const argv = o.argv || [];
427
+ const target = vaultTarget(env, argv);
428
+ const dryRun = Boolean(o.dryRun) || has(argv, '--dry-run');
429
+ const wantIndex = o.index === undefined ? !has(argv, '--no-index') : Boolean(o.index);
430
+
431
+ const secret = o.secret || null;
432
+ const { text, record, file } = readRecord({ ...o, secret, env });
433
+
434
+ // Shape first: `fp.id` throws for anything that is not a fingerprinted
435
+ // record, so a JSON file that is merely *not a key* still cannot be published
436
+ // as a record. Both checks are needed and they are different checks.
437
+ let id;
438
+ try {
439
+ id = fp.id(record);
440
+ } catch (e) {
441
+ throw new Error(`vault: not a sealed φ(α) record — ${(e && e.message) || e}`);
442
+ }
443
+
444
+ // The name is checked separately from the path: a caller can hand over a key
445
+ // by *name* (`keys/agent.key` copied into the records directory as
446
+ // `agent.key`) and the basename is the last thing that would catch it.
447
+ const keyPath = authorship.defaultKeyPath(env);
448
+ assertPublishable(path.basename(file || 'record.json'), text, { secret, keyPath, env });
449
+
450
+ const recordName = `${baseName(record)}.json`;
451
+ // ONE rule for the anchor's name, and it is the record's name plus the
452
+ // suffix — the same rule `localAnchor` uses to find it beside the local
453
+ // record. It used to be derived from the record's *stem*, so the local link
454
+ // (`x.json.anchor.json`) and the published link (`x.anchor.json`) had
455
+ // different names: `anchor` found one, `vault list` paired the other, and the
456
+ // record's own link could not be fetched by the name it was stored under.
457
+ const anchorName = `${recordName}${ANCHOR_SUFFIX}`;
458
+ const names = [
459
+ remoteSpec(target, RECORDS_DIR, recordName),
460
+ remoteSpec(target, RECORDS_DIR, anchorName),
461
+ ];
462
+
463
+ const digest = sha256(text);
464
+ const anchor = {
465
+ v: ANCHOR_VERSION,
466
+ kind: ANCHOR_KIND,
467
+ id,
468
+ keyFingerprint: record.keyFingerprint,
469
+ behaviour: record.behaviour || null,
470
+ code: record.code || null,
471
+ createdAt: record.createdAt,
472
+ attestation: record.attestation,
473
+ sha256: digest,
474
+ bytes: Buffer.byteLength(text, 'utf8'),
475
+ remote: target.remote,
476
+ root: target.root,
477
+ // `path` is for a human (and for pasting into rclone); `key` is the
478
+ // root-relative form the reader uses. Both, because a single field that
479
+ // means one thing to a person and another to rclone is how the root got
480
+ // applied twice.
481
+ path: `${target.root}/${RECORDS_DIR}/${recordName}`,
482
+ key: `${RECORDS_DIR}/${recordName}`,
483
+ emittedAt: new Date(o.now || Date.now()).toISOString(),
484
+ driveId: null,
485
+ url: null,
486
+ index: wantIndex ? `${target.root}/${RECORDS_DIR}/${INDEX_NAME}` : null,
487
+ };
488
+
489
+ if (dryRun) {
490
+ return {
491
+ ok: true,
492
+ dryRun: true,
493
+ anchor,
494
+ url: null,
495
+ remotePath: anchor.path,
496
+ commands: [`rclone copyto ${file || '<record>'} ${names[0]}`, `rclone copyto <anchor> ${names[1]}`],
497
+ };
498
+ }
499
+
500
+ const shelf = tempDir();
501
+ try {
502
+ // Upload the *sealed bytes*. When publishing from a path, that is the file
503
+ // itself; otherwise it is written out first so a download can be diffed
504
+ // against the thing that was sealed.
505
+ const localRecord = file || path.join(shelf, recordName);
506
+ if (!file) fs.writeFileSync(localRecord, text);
507
+ rcloneRun(target, ['copyto', localRecord, names[0]]);
508
+
509
+ // The Drive id comes from a listing, not from a shareable-link call: a
510
+ // `link` would change the folder's sharing, and publishing a record must
511
+ // not touch who can read the vault.
512
+ const listed = listRaw(target, RECORDS_DIR);
513
+ const entry = listed.find((f) => f.Name === recordName) || null;
514
+ if (entry) {
515
+ anchor.driveId = entry.ID || null;
516
+ anchor.url = driveUrl(entry.ID);
517
+ }
518
+
519
+ const localAnchor = file ? `${file}${ANCHOR_SUFFIX}` : null;
520
+ const anchorText = JSON.stringify(anchor, null, 2) + '\n';
521
+ const anchorFile = path.join(shelf, anchorName);
522
+ fs.writeFileSync(anchorFile, anchorText);
523
+ rcloneRun(target, ['copyto', anchorFile, names[1]]);
524
+ if (localAnchor) fs.writeFileSync(localAnchor, anchorText);
525
+
526
+ let indexLines = null;
527
+ if (wantIndex) indexLines = appendIndex(target, anchor);
528
+
529
+ return {
530
+ ok: true,
531
+ dryRun: false,
532
+ anchor,
533
+ url: anchor.url,
534
+ localAnchor,
535
+ remotePath: anchor.path,
536
+ bytes: anchor.bytes,
537
+ sha256: digest,
538
+ indexLines,
539
+ };
540
+ } finally {
541
+ fs.rmSync(shelf, { recursive: true, force: true });
542
+ }
543
+ }
544
+
545
+ /** Read one remote text file, `null` when it is not there. */
546
+ function cat(target, remotePath) {
547
+ try {
548
+ return rcloneRun(target, ['cat', remoteSpecOf(target, remotePath)]);
549
+ } catch (e) {
550
+ if (e.code === 'ERCLONE' && /not found|does not exist|error 404/i.test(e.stderr || e.message)) return null;
551
+ throw e;
552
+ }
553
+ }
554
+
555
+ /** `lsjson --files-only` as objects, tolerating an empty or absent directory. */
556
+ function listRaw(target, remotePath) {
557
+ let raw;
558
+ try {
559
+ raw = rcloneRun(target, ['lsjson', remoteSpecOf(target, remotePath), '--files-only']);
560
+ } catch (e) {
561
+ if (e.code === 'ERCLONE' && /not found|does not exist|error 404|directory not found/i.test(e.stderr || e.message)) return [];
562
+ throw e;
563
+ }
564
+ const text = String(raw).trim();
565
+ if (!text) return [];
566
+ const parsed = JSON.parse(text);
567
+ return Array.isArray(parsed) ? parsed : [];
568
+ }
569
+
570
+ /**
571
+ * Append one line to the vault ledger.
572
+ *
573
+ * Read-modify-write, which has a last-writer-wins race if two publishes overlap.
574
+ * That is why the per-record `.anchor.json` — written one file per publish, no
575
+ * read first — is the authoritative link and this is a convenience: losing a
576
+ * ledger line loses nothing that cannot be rebuilt from the anchors beside each
577
+ * record (`list` reads those, not this).
578
+ */
579
+ function appendIndex(target, anchor) {
580
+ const remotePath = `${RECORDS_DIR}/${INDEX_NAME}`;
581
+ const existing = cat(target, remotePath) || '';
582
+ const line = JSON.stringify({
583
+ kind: INDEX_KIND,
584
+ id: anchor.id,
585
+ keyFingerprint: anchor.keyFingerprint,
586
+ sha256: anchor.sha256,
587
+ path: anchor.path,
588
+ url: anchor.url,
589
+ driveId: anchor.driveId,
590
+ emittedAt: anchor.emittedAt,
591
+ });
592
+ const shelf = tempDir();
593
+ try {
594
+ const file = path.join(shelf, INDEX_NAME);
595
+ fs.writeFileSync(file, existing + line + '\n');
596
+ rcloneRun(target, ['copyto', file, remoteSpecOf(target, remotePath)]);
597
+ return (existing.trim() ? existing.trim().split('\n').length : 0) + 1;
598
+ } finally {
599
+ fs.rmSync(shelf, { recursive: true, force: true });
600
+ }
601
+ }
602
+
603
+ // ---------------------------------------------------------------------------
604
+ // the link, read back
605
+ // ---------------------------------------------------------------------------
606
+
607
+ /** The anchor stored beside a local record. `null` when the record was never published. */
608
+ function localAnchor(file) {
609
+ const sidecar = `${path.resolve(file)}${ANCHOR_SUFFIX}`;
610
+ if (!fs.existsSync(sidecar)) return null;
611
+ try {
612
+ return JSON.parse(fs.readFileSync(sidecar, 'utf8'));
613
+ } catch {
614
+ return null;
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Check the published copy against the link.
620
+ *
621
+ * Three separate claims, reported separately, because they fail for different
622
+ * reasons and a single boolean would hide which:
623
+ *
624
+ * present there is a copy at the anchored path
625
+ * unchanged its sha256 is the one recorded at publish time
626
+ * attested the key on this machine still recomputes its attestation
627
+ *
628
+ * The third is the one worth having: a copy that is byte-identical but whose
629
+ * attestation no longer recomputes means the key moved on (or the record was
630
+ * published by another key), and no digest of the file would ever show that.
631
+ */
632
+ function checkAnchor(o = {}) {
633
+ const env = o.env || process.env;
634
+ const argv = o.argv || [];
635
+ const target = vaultTarget(env, argv);
636
+
637
+ const anchor = o.anchor || (o.file ? localAnchor(o.file) : null);
638
+ if (!anchor) {
639
+ return { ok: false, reason: 'not linked — no anchor beside this record (publish it first)', present: false, unchanged: null, attested: null };
640
+ }
641
+
642
+ const text = cat(target, anchor.key || anchor.path);
643
+ if (text === null) {
644
+ // `present`, not `presence`: the field name is part of the answer, and a
645
+ // consumer reading `.present` got `undefined` from this branch while the
646
+ // other three returned a real boolean — an inconsistency that only shows up
647
+ // when the copy is missing, which is exactly when someone is looking.
648
+ return { ok: false, reason: `no copy at ${anchor.path}`, present: false, unchanged: false, attested: null, anchor };
649
+ }
650
+
651
+ const unchanged = sha256(text) === anchor.sha256;
652
+
653
+ let attested = null;
654
+ let attestationReason = null;
655
+ try {
656
+ const key = o.key || authorship.resolveKey({ argv, env });
657
+ if (!key.secret) {
658
+ attestationReason = 'no authorship key on this machine to recompute with';
659
+ } else {
660
+ const v = fp.verify(JSON.parse(text), key.secret);
661
+ attested = v.ok;
662
+ attestationReason = v.reason;
663
+ }
664
+ } catch (e) {
665
+ attestationReason = (e && e.message) || String(e);
666
+ }
667
+
668
+ return {
669
+ ok: unchanged && attested !== false,
670
+ anchor,
671
+ present: true,
672
+ unchanged,
673
+ attested,
674
+ attestationReason,
675
+ remotePath: anchor.path,
676
+ url: anchor.url,
677
+ reason: unchanged
678
+ ? attested === false
679
+ ? `the published copy does not verify: ${attestationReason}`
680
+ : null
681
+ : 'the published copy is not the bytes that were sealed (sha256 differs)',
682
+ };
683
+ }
684
+
685
+ /** What is in the vault. Reads the anchors, which is why the ledger is optional. */
686
+ function list(o = {}) {
687
+ const env = o.env || process.env;
688
+ const argv = o.argv || [];
689
+ const target = vaultTarget(env, argv);
690
+ const dir = RECORDS_DIR;
691
+ const files = listRaw(target, dir);
692
+ const anchors = files.filter((f) => String(f.Name).endsWith(ANCHOR_SUFFIX));
693
+ const records = files.filter((f) => !String(f.Name).endsWith(ANCHOR_SUFFIX) && String(f.Name).endsWith('.json') && f.Name !== INDEX_NAME);
694
+
695
+ return {
696
+ ok: true,
697
+ remote: target.remote,
698
+ root: target.root,
699
+ records: records.map((r) => {
700
+ // Paired by the same rule that wrote it: the anchor is the record's name
701
+ // plus the suffix. Stripping `.json` off the record name first would look
702
+ // for `<stem>.anchor.json`, which is not the name anything was written
703
+ // under.
704
+ const anchorFile = anchors.find((a) => String(a.Name) === `${r.Name}${ANCHOR_SUFFIX}`);
705
+ let anchor = null;
706
+ if (anchorFile) {
707
+ const text = cat(target, `${dir}/${anchorFile.Name}`);
708
+ // `cat` resolves the path against the root, so `records/<name>` here
709
+ // means `<remote>:<root>/records/<name>` — stated because getting this
710
+ // wrong is what put the ledger one directory too deep.
711
+ try {
712
+ anchor = JSON.parse(text);
713
+ } catch {
714
+ anchor = { unreadable: true };
715
+ }
716
+ }
717
+ return {
718
+ name: r.Name,
719
+ bytes: r.Size,
720
+ emittedAt: r.ModTime,
721
+ id: anchor ? anchor.id : null,
722
+ keyFingerprint: anchor ? anchor.keyFingerprint : null,
723
+ sha256: anchor ? anchor.sha256 : null,
724
+ driveId: (anchor && anchor.driveId) || r.ID || null,
725
+ url: (anchor && anchor.url) || driveUrl(r.ID),
726
+ linked: Boolean(anchor),
727
+ };
728
+ }),
729
+ };
730
+ }
731
+
732
+ /**
733
+ * Inspect what is already in the vault for key material.
734
+ *
735
+ * `publish` cannot stop what was put there before it existed, and the honest
736
+ * answer to "is a key in the vault?" has to be a command rather than an
737
+ * assurance. This reads every object under the root — not just `records/`,
738
+ * because the copy that matters here is `keys/agent.key`, which lives outside
739
+ * the records directory by definition.
740
+ *
741
+ * Reading is capped (`MAX_INSPECT_BYTES`, `MAX_AUDIT_FILES`) and reported as
742
+ * capped: an audit that silently stops inspecting is worse than one that says
743
+ * it did.
744
+ */
745
+ function audit(o = {}) {
746
+ const env = o.env || process.env;
747
+ const argv = o.argv || [];
748
+ const target = vaultTarget(env, argv);
749
+ const max = Number(flag(argv, '--max')) || MAX_AUDIT_FILES;
750
+
751
+ let files;
752
+ try {
753
+ // The whole root, recursively: the object this audit exists to find
754
+ // (`keys/agent.key`) is deliberately outside `records/`.
755
+ files = rcloneLsjsonRecursive(target, '');
756
+ } catch (e) {
757
+ return { ok: false, error: (e && e.message) || String(e), findings: [], checked: 0 };
758
+ }
759
+
760
+ const secret = o.secret || null;
761
+ const findings = [];
762
+ const uninspected = [];
763
+ let checked = 0;
764
+
765
+ for (const file of files) {
766
+ const rel = String(file.Path || file.Name);
767
+ if (checked >= max) {
768
+ uninspected.push({ path: rel, reason: `stopped after ${max} files` });
769
+ continue;
770
+ }
771
+ if (Number(file.Size) > MAX_INSPECT_BYTES) {
772
+ uninspected.push({ path: rel, reason: `larger than ${MAX_INSPECT_BYTES} bytes` });
773
+ continue;
774
+ }
775
+ checked += 1;
776
+ let text;
777
+ try {
778
+ text = rcloneRun(target, ['cat', remoteSpecOf(target, rel)]);
779
+ } catch (e) {
780
+ uninspected.push({ path: rel, reason: (e && e.message) || String(e) });
781
+ continue;
782
+ }
783
+ const verdict = inspect(rel, text, { secret });
784
+ if (verdict.dangerous) findings.push({ path: rel, reason: verdict.reason });
785
+ }
786
+
787
+ return {
788
+ ok: findings.length === 0,
789
+ remote: target.remote,
790
+ root: target.root,
791
+ checked,
792
+ files: files.length,
793
+ uninspected,
794
+ findings,
795
+ };
796
+ }
797
+
798
+ /** Every file under a prefix, with repo-relative names. */
799
+ function rcloneLsjsonRecursive(target, prefix) {
800
+ const raw = rcloneRun(target, ['lsjson', remoteSpecOf(target, prefix), '--files-only', '--recursive']);
801
+ const text = String(raw).trim();
802
+ if (!text) return [];
803
+ const parsed = JSON.parse(text);
804
+ return Array.isArray(parsed) ? parsed : [];
805
+ }
806
+
807
+ module.exports = {
808
+ DEFAULT_REMOTE,
809
+ DEFAULT_ROOT,
810
+ RECORDS_DIR,
811
+ INDEX_NAME,
812
+ ANCHOR_SUFFIX,
813
+ ANCHOR_KIND,
814
+ INDEX_KIND,
815
+ RCLONE_ENV,
816
+ REMOTE_ENV,
817
+ ROOT_ENV,
818
+ inspect,
819
+ assertPublishable,
820
+ publish,
821
+ checkAnchor,
822
+ list,
823
+ audit,
824
+ localAnchor,
825
+ relativeToRoot,
826
+ remoteSpecOf,
827
+ baseName,
828
+ driveUrl,
829
+ vaultTarget,
830
+ rcloneBinary,
831
+ sha256,
832
+ flag,
833
+ has,
834
+ };