aegis-desktop 1.0.13 → 1.0.15
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/SOURCE-OFFER.txt +9 -0
- package/bin/aegis.js +1 -32
- package/lib/account-key.js +1 -56
- package/lib/auto.js +1 -430
- package/lib/avatar/companion.js +1 -698
- package/lib/avatar/cosmetics.js +1 -532
- package/lib/avatar/events.js +1 -344
- package/lib/avatar/holder-turn.js +1 -350
- package/lib/avatar/holders.js +1 -612
- package/lib/avatar/identity.js +1 -641
- package/lib/avatar/level.js +1 -368
- package/lib/avatar/mirror.js +1 -524
- package/lib/avatar/persona.js +1 -388
- package/lib/avatar/profile.js +1 -977
- package/lib/avatar/register.js +1 -307
- package/lib/avatar/store.js +1 -472
- package/lib/avatar/tiers.js +1 -38
- package/lib/avatar/transfer.js +1 -415
- package/lib/avatar/turn.js +1 -216
- package/lib/avatar/voice.js +1 -328
- package/lib/avatar/xp.js +1 -404
- package/lib/deep-link.js +1 -120
- package/lib/fingerprint.js +2 -347
- package/lib/google-connect.js +1 -169
- package/lib/local/agents.js +1 -105
- package/lib/local/autonomous.js +1 -1045
- package/lib/local/claude-pro.js +1 -993
- package/lib/local/context.js +1 -95
- package/lib/local/engine.js +1 -3228
- package/lib/local/entitlement.js +1 -654
- package/lib/local/git-scope.js +1 -228
- package/lib/local/local.js +1 -2135
- package/lib/local/prompt.js +1 -275
- package/lib/local/queue.js +1 -560
- package/lib/local/session-rounds.js +1 -208
- package/lib/local/shell.js +1 -680
- package/lib/local/telemetry.js +1 -470
- package/lib/local/tools.js +1 -1238
- package/lib/local/turn-guard.js +1 -300
- package/lib/local/worktree-lock.js +1 -235
- package/lib/provider-key-mirror.js +1 -252
- package/lib/quick-launcher.js +1 -84
- package/lib/settings.js +1 -890
- package/lib/sync/memory-queue.js +1 -60
- package/lib/sync/persist-gate.js +1 -148
- package/lib/sync/sessions.js +1 -106
- package/lib/window-state.js +1 -66
- package/main.js +3 -4390
- package/package.json +3 -5
- package/preload.js +3 -628
- package/renderer/app.js +1 -6560
- package/renderer/avatar/assemble.js +1 -335
- package/renderer/avatar/avatar.js +1 -380
- package/renderer/avatar/cards.js +1 -141
- package/renderer/avatar/hud.js +1 -206
- package/renderer/avatar/machine.js +1 -213
- package/renderer/avatar/pane.js +1 -439
- package/renderer/avatar/parts.js +1 -437
- package/renderer/budget.js +1 -168
- package/renderer/companion.js +1 -223
- package/renderer/diff.js +1 -359
- package/renderer/diffview.js +1 -336
- package/renderer/fingerprint.js +3 -720
- package/renderer/markdown.js +1 -168
- package/renderer/provider-toolbar.js +1 -134
- package/renderer/providers.js +1 -259
- package/renderer/quick.js +1 -191
- package/renderer/stream-policy.js +1 -306
- package/renderer/transcript-view.js +1 -323
- package/renderer/usage.js +1 -1239
- package/vendor/aegis.js +1 -2054
- package/vendor/attest.js +1 -442
- package/vendor/authorship-key.js +1 -410
- package/vendor/auto-provision.js +1 -134
- package/vendor/brain-catalog.js +1 -268
- package/vendor/byok-catalog.js +1 -230
- package/vendor/credentials.js +1 -494
- package/vendor/device-fingerprint.js +1 -141
- package/vendor/drive-connect.js +1 -85
- package/vendor/drive-upload.js +1 -174
- package/vendor/env-file.js +1 -1273
- package/vendor/fingerprint.js +1 -1064
- package/vendor/foreign-memory.js +1 -669
- package/vendor/google-signin.js +1 -125
- package/vendor/hooks.js +1 -430
- package/vendor/model-discovery.js +1 -330
- package/vendor/platform.js +1 -937
- package/vendor/prefs.js +1 -351
- package/vendor/presence-constants.js +1 -107
- package/vendor/presence.js +1 -438
- package/vendor/record-vault.js +3 -1055
- package/vendor/session-store.js +1 -548
- package/vendor/topup.js +1 -297
- package/vendor/touch.js +1 -458
- package/vendor/update.js +1 -704
- package/vendor/user-models.js +1 -381
package/vendor/record-vault.js
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
3
|
+
"use strict";
|
|
8
4
|
/**
|
|
9
5
|
* record-vault.js — put a sealed φ(α) record where a human can find it, and
|
|
10
6
|
* never put the key there.
|
|
@@ -99,1059 +95,11 @@
|
|
|
99
95
|
* user's Drive or their account. The remote/root are overridable the same way
|
|
100
96
|
* (`AEGIS_VAULT_REMOTE`/`AEGIS_VAULT_ROOT`, `AEGIS_VAULT_BACKEND`), which is
|
|
101
97
|
* also what keeps a misconfigured vault from writing into an unrelated folder.
|
|
102
|
-
*/
|
|
103
|
-
|
|
104
|
-
const crypto = require('node:crypto');
|
|
105
|
-
const fs = require('node:fs');
|
|
106
|
-
const os = require('node:os');
|
|
107
|
-
const path = require('node:path');
|
|
108
|
-
const { execFileSync } = require('node:child_process');
|
|
109
|
-
|
|
110
|
-
const fp = require('./fingerprint.js');
|
|
111
|
-
const authorship = require('./authorship-key.js');
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* The backends a vault can live on.
|
|
115
|
-
*
|
|
116
|
-
* `aegiscloud` is the default because it is the only one that exists on a
|
|
117
|
-
* fresh install: it authenticates with the device key this machine already
|
|
118
|
-
* registered for, so publishing a record needs no second setup. `rclone` is
|
|
119
|
-
* kept for users who want the copy in a folder they own.
|
|
120
|
-
*/
|
|
121
|
-
const BACKEND_CLOUD = 'aegiscloud';
|
|
122
|
-
const BACKEND_RCLONE = 'rclone';
|
|
123
|
-
const DEFAULT_BACKEND = BACKEND_CLOUD;
|
|
124
|
-
|
|
125
|
-
/** The folder the sealed records live in, and the folder that must not hold a key. */
|
|
126
|
-
const DEFAULT_REMOTE = 'gdrive';
|
|
127
|
-
const DEFAULT_ROOT = 'AEGIS-AGPL';
|
|
128
|
-
const RECORDS_DIR = 'records';
|
|
129
|
-
const INDEX_NAME = 'index.jsonl';
|
|
130
|
-
const ANCHOR_SUFFIX = '.anchor.json';
|
|
131
|
-
const ANCHOR_VERSION = 1;
|
|
132
|
-
const ANCHOR_KIND = 'aegiscode.record.anchor';
|
|
133
|
-
/** The ledger's own line kind. Every object we emit is labelled, so the audit
|
|
134
|
-
* can validate a known shape instead of guessing from field names. */
|
|
135
|
-
const INDEX_KIND = 'aegiscode.record.index';
|
|
136
|
-
|
|
137
|
-
const RCLONE_ENV = 'AEGIS_VAULT_RCLONE';
|
|
138
|
-
const REMOTE_ENV = 'AEGIS_VAULT_REMOTE';
|
|
139
|
-
const ROOT_ENV = 'AEGIS_VAULT_ROOT';
|
|
140
|
-
const BACKEND_ENV = 'AEGIS_VAULT_BACKEND';
|
|
141
|
-
const API_BASE_ENV = 'AEGIS_API_BASE';
|
|
142
|
-
|
|
143
|
-
/** Where the aegiscloud backend lives, and the routes it speaks. */
|
|
144
|
-
const CLOUD_PREFIX = '/api/v1/vault';
|
|
145
|
-
|
|
146
|
-
/** Every remote call is bounded: a hung rclone must not hang a mint or a GUI turn. */
|
|
147
|
-
const RCLONE_TIMEOUT_MS = 60_000;
|
|
148
|
-
|
|
149
|
-
/** Longest file `audit` will read to inspect. Anchors and records are all tiny. */
|
|
150
|
-
const MAX_INSPECT_BYTES = 2 * 1024 * 1024;
|
|
151
|
-
|
|
152
|
-
/** How many vault objects one `audit` walks before it says it stopped. */
|
|
153
|
-
const MAX_AUDIT_FILES = 500;
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Paths that are key material by their *name*, whatever they contain.
|
|
157
|
-
*
|
|
158
|
-
* `keys/` is the directory `keygen` writes into and the one already present in
|
|
159
|
-
* the AGPL vault; `agent.key` is the engine's name for the same secret. A vault
|
|
160
|
-
* that accepts these can be talked into publishing a key by someone who only
|
|
161
|
-
* passes a path, which is the exact failure this module exists to prevent.
|
|
162
|
-
*/
|
|
163
|
-
const KEY_PATH_PATTERNS = [
|
|
164
|
-
/(^|\/)keys?\//i, // keys/agent.key, key/agent.key
|
|
165
|
-
/\.key$/i, // authorship.key, agent.key
|
|
166
|
-
/\.pem$/i, // PEM private key
|
|
167
|
-
/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i, // ssh private keys
|
|
168
|
-
/(^|\/)agent\.key(\.|$)/i,
|
|
169
|
-
];
|
|
170
|
-
|
|
171
|
-
/** A whole file that is one long token is not a record and is plausibly a secret. */
|
|
172
|
-
const BARE_TOKEN = /^[A-Za-z0-9_\-+/=]{40,}$/;
|
|
173
|
-
|
|
174
|
-
/** A whole file that is 32+ hex is a raw digest or a hex-encoded key. */
|
|
175
|
-
const BARE_HEX = /^[0-9a-fA-F]{32,}$/;
|
|
176
|
-
|
|
177
|
-
const PEM_PRIVATE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;
|
|
178
|
-
|
|
179
|
-
/** `--flag value`; returns null when absent, so callers can fall back in order. */
|
|
180
|
-
function flag(argv, name, fallback = null) {
|
|
181
|
-
const list = Array.isArray(argv) ? argv : [];
|
|
182
|
-
const i = list.indexOf(name);
|
|
183
|
-
return i !== -1 && list[i + 1] !== undefined && !String(list[i + 1]).startsWith('--')
|
|
184
|
-
? list[i + 1]
|
|
185
|
-
: fallback;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
function has(argv, name) {
|
|
189
|
-
return (Array.isArray(argv) ? argv : []).includes(name);
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/** The rclone binary: `--rclone`, then the env, then PATH. */
|
|
193
|
-
function rcloneBinary(env = process.env, argv = []) {
|
|
194
|
-
return flag(argv, '--rclone') || env[RCLONE_ENV] || 'rclone';
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* Where the vault is. Both halves are injectable because both are things a
|
|
199
|
-
* caller can get wrong in a way that writes a record somewhere unintended.
|
|
200
|
-
*/
|
|
201
|
-
function vaultTarget(env = process.env, argv = [], link = null) {
|
|
202
|
-
const remote = flag(argv, '--remote') || env[REMOTE_ENV] || (link && link.remote) || DEFAULT_REMOTE;
|
|
203
|
-
return {
|
|
204
|
-
// `--backend` wins, then the env. A caller who names an rclone remote
|
|
205
|
-
// (`--remote gdrive`, `AEGIS_VAULT_REMOTE=r2`) is asking for THAT remote, so
|
|
206
|
-
// naming one switches the backend rather than being silently ignored by a
|
|
207
|
-
// cloud default — the old behaviour of reading `--remote` and then talking
|
|
208
|
-
// to aegiscloud would be the worst of both.
|
|
209
|
-
backend: backendFor(env, argv, remote, link),
|
|
210
|
-
remote,
|
|
211
|
-
root: flag(argv, '--root') || env[ROOT_ENV] || (link && link.root) || DEFAULT_ROOT,
|
|
212
|
-
apiBase: String(flag(argv, '--base') || env[API_BASE_ENV] || 'https://aegiscloud.org').replace(/\/+$/, ''),
|
|
213
|
-
rclone: rcloneBinary(env, argv),
|
|
214
|
-
// Carried so `rcloneRun` can hand the *injected* environment to the child.
|
|
215
|
-
// Passing rclone the ambient process env instead made every AEGIS_VAULT_*
|
|
216
|
-
// and every rclone variable (config dir, proxy, a stubbed binary's own
|
|
217
|
-
// settings) a no-op in the child — the caller sets the environment, so the
|
|
218
|
-
// caller's environment is what the subprocess gets.
|
|
219
|
-
env,
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Which backend this target resolves to.
|
|
225
|
-
*
|
|
226
|
-
* Precedence, and each step is a user saying something specific:
|
|
227
|
-
*
|
|
228
|
-
* 1. `--backend` / `$AEGIS_VAULT_BACKEND` — explicit, and an unknown value is
|
|
229
|
-
* an ERROR rather than a quiet fallback: "publish my records to aegiscloud"
|
|
230
|
-
* silently becoming "…to your local Drive" (or the reverse) is a data
|
|
231
|
-
* question, not a cosmetic one.
|
|
232
|
-
* 2. an explicit `--remote` / `$AEGIS_VAULT_REMOTE` — that is an rclone remote
|
|
233
|
-
* name, so it selects rclone.
|
|
234
|
-
* 3. otherwise the default: `aegiscloud`.
|
|
235
|
-
*/
|
|
236
|
-
function backendFor(env, argv, remote, link = null) {
|
|
237
|
-
const explicit = String(flag(argv, '--backend') || env[BACKEND_ENV] || '').trim().toLowerCase();
|
|
238
|
-
if (explicit) {
|
|
239
|
-
if (explicit !== BACKEND_CLOUD && explicit !== BACKEND_RCLONE) {
|
|
240
|
-
throw new Error(`vault: unknown backend "${explicit}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);
|
|
241
|
-
}
|
|
242
|
-
return explicit;
|
|
243
|
-
}
|
|
244
|
-
if (flag(argv, '--remote') || env[REMOTE_ENV]) return BACKEND_RCLONE;
|
|
245
|
-
// A link says where its own copy went; honouring it is what makes `anchor`
|
|
246
|
-
// work on a record published before the user changed their default.
|
|
247
|
-
if (link && (link.backend === BACKEND_CLOUD || link.backend === BACKEND_RCLONE)) return link.backend;
|
|
248
|
-
if (link && link.backend === undefined && link.remote && link.remote !== DEFAULT_REMOTE) return BACKEND_RCLONE;
|
|
249
|
-
return DEFAULT_BACKEND;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
function remoteSpec(target, ...segments) {
|
|
253
|
-
return `${target.remote}:${[target.root, ...segments].filter(Boolean).join('/')}`;
|
|
254
|
-
}
|
|
255
|
-
|
|
98
|
+
*/const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=BACKEND_CLOUD,DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||DEFAULT_REMOTE;return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||DEFAULT_ROOT,apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if(o!==BACKEND_CLOUD&&o!==BACKEND_RCLONE)throw new Error(`vault: unknown backend "${o}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?BACKEND_RCLONE:!n||n.backend!==BACKEND_CLOUD&&n.backend!==BACKEND_RCLONE?n&&void 0===n.backend&&n.remote&&n.remote!==DEFAULT_REMOTE?BACKEND_RCLONE:DEFAULT_BACKEND:n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`}
|
|
256
99
|
/**
|
|
257
100
|
* A path *below* the root, however it was written: `records/x.json`,
|
|
258
101
|
* `<root>/records/x.json`, or an absolute `remote:…` spec. Everything that
|
|
259
102
|
* reads tolerates all three, because the anchor stores the browsable
|
|
260
103
|
* root-prefixed form (a human reads `AEGIS-AGPL/records/x.json`) while rclone
|
|
261
104
|
* wants it relative.
|
|
262
|
-
*/
|
|
263
|
-
function relativeToRoot(target, relPath) {
|
|
264
|
-
let rel = String(relPath || '').replace(/^\/+/, '');
|
|
265
|
-
const spec = `${target.remote}:`;
|
|
266
|
-
if (rel.startsWith(spec)) rel = rel.slice(spec.length);
|
|
267
|
-
if (rel === target.root) return '';
|
|
268
|
-
if (rel.startsWith(`${target.root}/`)) rel = rel.slice(target.root.length + 1);
|
|
269
|
-
return rel;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/** `relativeToRoot` + `remoteSpec`: one rclone spec from any of the three forms. */
|
|
273
|
-
function remoteSpecOf(target, relPath) {
|
|
274
|
-
const rel = relativeToRoot(target, relPath);
|
|
275
|
-
return rel ? remoteSpec(target, rel) : remoteSpec(target);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* One rclone call.
|
|
280
|
-
*
|
|
281
|
-
* stderr is captured rather than inherited: rclone prints a client_id NOTICE on
|
|
282
|
-
* every invocation on this host, and a warning on a CLI's stderr for a command
|
|
283
|
-
* whose output is JSON is noise a caller has to filter. On failure the message
|
|
284
|
-
* carries rclone's own last line, because "exit status 1" is not a diagnosis.
|
|
285
|
-
*/
|
|
286
|
-
function rcloneRun(target, args, { timeout = RCLONE_TIMEOUT_MS } = {}) {
|
|
287
|
-
try {
|
|
288
|
-
return execFileSync(target.rclone, args, {
|
|
289
|
-
encoding: 'utf8',
|
|
290
|
-
timeout,
|
|
291
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
292
|
-
maxBuffer: 32 * 1024 * 1024,
|
|
293
|
-
env: target.env ? { ...process.env, ...target.env } : process.env,
|
|
294
|
-
});
|
|
295
|
-
} catch (e) {
|
|
296
|
-
const err = String((e && e.stderr) || '').trim().split('\n').filter((l) => !/NOTICE:/.test(l)).pop();
|
|
297
|
-
const msg = err || (e && e.message) || String(e);
|
|
298
|
-
const wrapped = new Error(`vault: rclone ${args[0]} failed — ${msg}`);
|
|
299
|
-
wrapped.code = 'ERCLONE';
|
|
300
|
-
wrapped.stderr = String((e && e.stderr) || '');
|
|
301
|
-
throw wrapped;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/** A shelf directory for temporary uploads. Removed by the caller. */
|
|
306
|
-
function tempDir() {
|
|
307
|
-
return fs.mkdtempSync(path.join(os.tmpdir(), 'aegis-vault-'));
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
// ---------------------------------------------------------------------------
|
|
311
|
-
// the aegiscloud backend
|
|
312
|
-
// ---------------------------------------------------------------------------
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* The account key this machine already has, or null.
|
|
316
|
-
*
|
|
317
|
-
* Deliberately NOT a second sign-in: `client/credentials.js` is the one store
|
|
318
|
-
* the whole product resolves a key from, and a machine that has ever used any
|
|
319
|
-
* cloud feature has already registered a device (client/auto-provision.js) and
|
|
320
|
-
* saved that key there. Reading it means "publish to my vault" costs the user
|
|
321
|
-
* nothing beyond the account they already have; any other arrangement would be
|
|
322
|
-
* a second credential with its own expiry and its own way to be stale.
|
|
323
|
-
*
|
|
324
|
-
* `AEGIS_API_KEY` is honoured by credentials.js's own resolution order, so the
|
|
325
|
-
* env override works here for free.
|
|
326
|
-
*/
|
|
327
|
-
function cloudApiKey(o = {}) {
|
|
328
|
-
if (o.apiKey) return String(o.apiKey).trim();
|
|
329
|
-
const env = o.env || process.env;
|
|
330
|
-
try {
|
|
331
|
-
const credentials = require('./credentials.js');
|
|
332
|
-
// `dir` is passed explicitly and derived from the INJECTED env. Without it
|
|
333
|
-
// the store falls back to `os.homedir()`, so a host that scopes AEGIS_HOME
|
|
334
|
-
// (the desktop's data dir, every test) would publish to — or 401 against —
|
|
335
|
-
// whichever account the real user happens to be logged into.
|
|
336
|
-
return String(credentials.resolveApiKey({ env, dir: credentials.aegisHome(env) }).key || '').trim();
|
|
337
|
-
} catch {
|
|
338
|
-
// A host that cannot load the store is not a crash here: the caller gets
|
|
339
|
-
// "no account key" and the same instruction a first-time user gets.
|
|
340
|
-
return '';
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/**
|
|
345
|
-
* One aegiscloud vault call.
|
|
346
|
-
*
|
|
347
|
-
* `fetch` is injectable (`o.fetch`) for the same reason `rcloneBinary` is: the
|
|
348
|
-
* suite must be hermetic, and a test that can only pass by reaching the real
|
|
349
|
-
* account is a test that gets skipped. Errors are wrapped with the server's own
|
|
350
|
-
* message, because "HTTP 401" is not a diagnosis — the account half of it is.
|
|
351
|
-
*/
|
|
352
|
-
async function cloudRun(target, method, route, { body = null, raw = false, timeout = RCLONE_TIMEOUT_MS, fetchImpl = null, apiKey = null } = {}) {
|
|
353
|
-
const key = apiKey || '';
|
|
354
|
-
if (!key) {
|
|
355
|
-
const err = new Error(
|
|
356
|
-
'vault: no AEGIS account key on this machine — the aegiscloud vault is the account ' +
|
|
357
|
-
'you already have. Run `aegiscode login`, or publish to a folder you own with ' +
|
|
358
|
-
'`--backend rclone --remote <name>`.',
|
|
359
|
-
);
|
|
360
|
-
err.code = 'ENOKEY';
|
|
361
|
-
throw err;
|
|
362
|
-
}
|
|
363
|
-
const doFetch = fetchImpl || (typeof fetch === 'function' ? fetch : null);
|
|
364
|
-
if (!doFetch) {
|
|
365
|
-
const err = new Error('vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault');
|
|
366
|
-
err.code = 'ENOFETCH';
|
|
367
|
-
throw err;
|
|
368
|
-
}
|
|
369
|
-
const controller = new AbortController();
|
|
370
|
-
const timer = setTimeout(() => controller.abort(), timeout);
|
|
371
|
-
let res;
|
|
372
|
-
try {
|
|
373
|
-
res = await doFetch(`${target.apiBase}${CLOUD_PREFIX}${route}`, {
|
|
374
|
-
method,
|
|
375
|
-
headers: {
|
|
376
|
-
'Content-Type': 'application/json',
|
|
377
|
-
'X-API-Key': key,
|
|
378
|
-
Authorization: `Bearer ${key}`,
|
|
379
|
-
},
|
|
380
|
-
body: body === null ? undefined : JSON.stringify(body),
|
|
381
|
-
signal: controller.signal,
|
|
382
|
-
});
|
|
383
|
-
} catch (e) {
|
|
384
|
-
const err = new Error(`vault: could not reach ${target.apiBase} — ${(e && e.message) || e}`);
|
|
385
|
-
err.code = 'ENETWORK';
|
|
386
|
-
throw err;
|
|
387
|
-
} finally {
|
|
388
|
-
clearTimeout(timer);
|
|
389
|
-
}
|
|
390
|
-
const text = await res.text();
|
|
391
|
-
let data = null;
|
|
392
|
-
try {
|
|
393
|
-
data = text ? JSON.parse(text) : null;
|
|
394
|
-
} catch {
|
|
395
|
-
data = null;
|
|
396
|
-
}
|
|
397
|
-
if (!res.ok) {
|
|
398
|
-
// A 404 on the collection route is not "the object is missing" — it is a
|
|
399
|
-
// server that predates `/api/v1/vault` (this client ships ahead of the
|
|
400
|
-
// account service it talks to). Saying "not found" there sends the user
|
|
401
|
-
// looking for a record that was never uploaded; name the real situation and
|
|
402
|
-
// the fallback that works today.
|
|
403
|
-
if (res.status === 404 && (route === '' || route.startsWith('?'))) {
|
|
404
|
-
const err = new Error(
|
|
405
|
-
`vault: ${target.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is ` +
|
|
406
|
-
'missing on this server). Publish to a folder you own instead: ' +
|
|
407
|
-
'`--backend rclone --remote <name> --root <folder>`.',
|
|
408
|
-
);
|
|
409
|
-
err.code = 'ENOVAULT';
|
|
410
|
-
err.status = 404;
|
|
411
|
-
throw err;
|
|
412
|
-
}
|
|
413
|
-
const msg = (data && (data.error || data.message)) || text.slice(0, 200) || `HTTP ${res.status}`;
|
|
414
|
-
const err = new Error(`vault: ${method} ${CLOUD_PREFIX}${route} failed — ${msg}`);
|
|
415
|
-
err.code = 'ECLOUD';
|
|
416
|
-
err.status = res.status;
|
|
417
|
-
throw err;
|
|
418
|
-
}
|
|
419
|
-
return raw ? text : data === null ? {} : data;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* A route-safe id for one object.
|
|
424
|
-
*
|
|
425
|
-
* Encoded per SEGMENT, not with one `encodeURIComponent` over the whole name:
|
|
426
|
-
* the object lives under `records/`, so the slash is part of the route rather
|
|
427
|
-
* than part of a name. Encoding it as `%2F` works through Flask's `<path:>`
|
|
428
|
-
* converter, but it turns every message and every log line into
|
|
429
|
-
* `records%2F…`, and a proxy that rejects encoded slashes turns a publish into
|
|
430
|
-
* a mystery 404. The record names themselves are already filename-safe
|
|
431
|
-
* (client-side `baseName`), so this is belt-and-braces, not the guard.
|
|
432
|
-
*/
|
|
433
|
-
function cloudObject(target, name) {
|
|
434
|
-
return `/${String(name || '')
|
|
435
|
-
.split('/')
|
|
436
|
-
.filter(Boolean)
|
|
437
|
-
.map((segment) => encodeURIComponent(segment))
|
|
438
|
-
.join('/')}`;
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
/**
|
|
442
|
-
* The transport the rest of this module talks to.
|
|
443
|
-
*
|
|
444
|
-
* Every remote operation is expressed once, here, in terms the module above
|
|
445
|
-
* understands — `put`, `cat`, `list`, `listRecursive` — so `publish`, `anchor`,
|
|
446
|
-
* `vault` and `--audit` do not each grow a second implementation per backend.
|
|
447
|
-
* The rclone half is the code that was already here, unchanged; the cloud half
|
|
448
|
-
* is the same four operations against `${apiBase}/api/v1/vault`.
|
|
449
|
-
*/
|
|
450
|
-
function transportFor(target, opts = {}) {
|
|
451
|
-
if (target.backend === BACKEND_CLOUD) {
|
|
452
|
-
const apiKey = cloudApiKey(opts);
|
|
453
|
-
const call = (method, route, extra) =>
|
|
454
|
-
cloudRun(target, method, route, { ...extra, fetchImpl: opts.fetch, apiKey });
|
|
455
|
-
return {
|
|
456
|
-
backend: BACKEND_CLOUD,
|
|
457
|
-
/** Upload one object. `rel` is root-relative (`records/x.json`). */
|
|
458
|
-
async put(rel, text) {
|
|
459
|
-
await call('PUT', cloudObject(target, remoteObjectName(rel)), { body: { content: text } });
|
|
460
|
-
},
|
|
461
|
-
/** Upload an existing local file, byte for byte — `publish` needs this. */
|
|
462
|
-
async putFile(rel, localPath) {
|
|
463
|
-
await this.put(rel, fs.readFileSync(localPath, 'utf8'));
|
|
464
|
-
},
|
|
465
|
-
/** Read one object, `null` when it is not there. */
|
|
466
|
-
async cat(rel) {
|
|
467
|
-
try {
|
|
468
|
-
const data = await call('GET', cloudObject(target, remoteObjectName(rel)));
|
|
469
|
-
return data && typeof data.content === 'string' ? data.content : null;
|
|
470
|
-
} catch (e) {
|
|
471
|
-
if (e.status === 404) return null;
|
|
472
|
-
throw e;
|
|
473
|
-
}
|
|
474
|
-
},
|
|
475
|
-
/** `{ Name, Size, ModTime, ID, Path }` for one directory (non-recursive). */
|
|
476
|
-
async list(rel) {
|
|
477
|
-
const data = await call('GET', `?dir=${encodeURIComponent(relativeToRoot(target, rel))}`);
|
|
478
|
-
return Array.isArray(data && data.files) ? data.files : [];
|
|
479
|
-
},
|
|
480
|
-
/** The same shape, for the whole vault (`vault --audit`). */
|
|
481
|
-
async listRecursive(prefix) {
|
|
482
|
-
const data = await call('GET', `?dir=${encodeURIComponent(relativeToRoot(target, prefix))}&recursive=1`);
|
|
483
|
-
return Array.isArray(data && data.files) ? data.files : [];
|
|
484
|
-
},
|
|
485
|
-
describe: `${target.apiBase} (account vault)`,
|
|
486
|
-
};
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
return {
|
|
490
|
-
backend: BACKEND_RCLONE,
|
|
491
|
-
async put(rel, text, { name = 'object' } = {}) {
|
|
492
|
-
const shelf = tempDir();
|
|
493
|
-
try {
|
|
494
|
-
const file = path.join(shelf, name);
|
|
495
|
-
fs.writeFileSync(file, text);
|
|
496
|
-
rcloneRun(target, ['copyto', file, remoteSpecOf(target, rel)]);
|
|
497
|
-
} finally {
|
|
498
|
-
fs.rmSync(shelf, { recursive: true, force: true });
|
|
499
|
-
}
|
|
500
|
-
},
|
|
501
|
-
/** Upload an existing local file, byte for byte — `publish` needs this. */
|
|
502
|
-
async putFile(rel, localPath) {
|
|
503
|
-
rcloneRun(target, ['copyto', localPath, remoteSpecOf(target, rel)]);
|
|
504
|
-
},
|
|
505
|
-
async cat(rel) {
|
|
506
|
-
try {
|
|
507
|
-
return rcloneRun(target, ['cat', remoteSpecOf(target, rel)]);
|
|
508
|
-
} catch (e) {
|
|
509
|
-
if (e.code === 'ERCLONE' && /not found|does not exist|error 404/i.test(e.stderr || e.message)) return null;
|
|
510
|
-
throw e;
|
|
511
|
-
}
|
|
512
|
-
},
|
|
513
|
-
async list(rel) {
|
|
514
|
-
return listRaw(target, rel);
|
|
515
|
-
},
|
|
516
|
-
async listRecursive(prefix) {
|
|
517
|
-
return rcloneLsjsonRecursive(target, prefix);
|
|
518
|
-
},
|
|
519
|
-
describe: `${target.remote}:${target.root}`,
|
|
520
|
-
};
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
/** `records/x.json` → `records/x.json`; strips the root/spec forms the readers accept. */
|
|
524
|
-
function remoteObjectName(rel) {
|
|
525
|
-
return relativeToRoot({ remote: '', root: '' }, rel).replace(/^\/+/, '');
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
// ---------------------------------------------------------------------------
|
|
529
|
-
// the guard: what may leave the machine
|
|
530
|
-
// ---------------------------------------------------------------------------
|
|
531
|
-
|
|
532
|
-
/**
|
|
533
|
-
* Inspect one file's *content* and *name* for key material.
|
|
534
|
-
*
|
|
535
|
-
* The JSON half delegates to the sealer's own `fp.assertNoLeak`. That is not a
|
|
536
|
-
* convenience: if this file carried a second, hand-written copy of the leak rule
|
|
537
|
-
* the two would drift, and the drift would be invisible — the vault would allow
|
|
538
|
-
* what the sealer forbids, on the one code path whose whole job is keeping a
|
|
539
|
-
* secret off the network. A throw from `assertNoLeak` is a refusal here.
|
|
540
|
-
*
|
|
541
|
-
* @returns {{dangerous: boolean, reason: string|null}}
|
|
542
|
-
*/
|
|
543
|
-
function inspect(name, text, { secret = null, keyPath = null } = {}) {
|
|
544
|
-
const where = String(name || '');
|
|
545
|
-
|
|
546
|
-
for (const pattern of KEY_PATH_PATTERNS) {
|
|
547
|
-
if (pattern.test(where)) {
|
|
548
|
-
return { dangerous: true, reason: `the path looks like key material (${pattern})` };
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
if (keyPath && path.resolve(where) === path.resolve(keyPath)) {
|
|
553
|
-
return { dangerous: true, reason: 'this path IS the authorship key' };
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
const body = String(text === null || text === undefined ? '' : text);
|
|
557
|
-
const trimmed = body.trim();
|
|
558
|
-
|
|
559
|
-
if (secret && trimmed.includes(String(secret))) {
|
|
560
|
-
return { dangerous: true, reason: 'the content carries the authorship key verbatim' };
|
|
561
|
-
}
|
|
562
|
-
if (PEM_PRIVATE.test(body)) {
|
|
563
|
-
return { dangerous: true, reason: 'the content is a PEM private key' };
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// Only when the whole file is one token: a record is JSON, so this can never
|
|
567
|
-
// fire on a legitimate record, and it is the shape a raw key file has.
|
|
568
|
-
const singleLine = trimmed.split('\n').length === 1;
|
|
569
|
-
if (singleLine && BARE_TOKEN.test(trimmed) && !BARE_HEX.test(trimmed)) {
|
|
570
|
-
return { dangerous: true, reason: 'the content is a bare high-entropy token (a raw secret)' };
|
|
571
|
-
}
|
|
572
|
-
if (singleLine && BARE_HEX.test(trimmed)) {
|
|
573
|
-
return { dangerous: true, reason: 'the content is an unlabelled hex blob (a raw digest or key)' };
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
// A parsed object is checked by the sealer's own rule, with one exception:
|
|
577
|
-
// our own anchor is a *known* artifact whose whole job is to carry a 64-hex
|
|
578
|
-
// sha256, so running the record rule over it reports a long hex run and calls
|
|
579
|
-
// the vault dirty when it is not. Known shapes get their shapes validated;
|
|
580
|
-
// everything else gets the record rule, unweakened.
|
|
581
|
-
let parsed = null;
|
|
582
|
-
try {
|
|
583
|
-
parsed = JSON.parse(body);
|
|
584
|
-
} catch {
|
|
585
|
-
parsed = null;
|
|
586
|
-
}
|
|
587
|
-
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
588
|
-
// Anything this module emits is labelled `aegiscode.…`, and a labelled
|
|
589
|
-
// artifact is validated by its own shape. Unlabelled JSON — a record, or
|
|
590
|
-
// anything a user dropped in — gets the record rule, unweakened.
|
|
591
|
-
if (typeof parsed.kind === 'string' && parsed.kind.startsWith('aegiscode.')) {
|
|
592
|
-
return inspectArtifact(parsed, secret);
|
|
593
|
-
}
|
|
594
|
-
try {
|
|
595
|
-
fp.assertNoLeak(parsed, secret || '');
|
|
596
|
-
} catch (e) {
|
|
597
|
-
return { dangerous: true, reason: (e && e.message) || 'failed the leak check' };
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
return { dangerous: false, reason: null };
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
/**
|
|
605
|
-
* The audit's rule for an artifact this module emits — a link
|
|
606
|
-
* (`kind: aegiscode.record.anchor`) or a ledger line
|
|
607
|
-
* (`kind: aegiscode.record.index`).
|
|
608
|
-
*
|
|
609
|
-
* Their digest fields are *expected* — `sha256` is 64 hex by definition, and
|
|
610
|
-
* `attestation` is the 32-hex tag copied out of the record — so they are
|
|
611
|
-
* validated rather than flagged. Anywhere else in the artifact, a long hex run
|
|
612
|
-
* is still a finding, and the key is refused verbatim wherever it appears. This
|
|
613
|
-
* is not a weakening of the rule: it is the difference between "an unknown file
|
|
614
|
-
* carries something key-shaped" (a finding) and "our own index line carries the
|
|
615
|
-
* sha256 it is made of" (not one).
|
|
616
|
-
*/
|
|
617
|
-
function inspectArtifact(anchor, secret) {
|
|
618
|
-
const expected = new Set(['sha256', 'attestation', 'code']);
|
|
619
|
-
for (const [key, value] of Object.entries(anchor)) {
|
|
620
|
-
if (value === null || value === undefined) continue;
|
|
621
|
-
const text = Array.isArray(value) ? value.join('\u0000') : String(value);
|
|
622
|
-
if (secret && text.includes(String(secret))) {
|
|
623
|
-
return { dangerous: true, reason: `the link carries the authorship key verbatim in "${key}"` };
|
|
624
|
-
}
|
|
625
|
-
if (!expected.has(key) && fp.longHexRun(text)) {
|
|
626
|
-
return { dangerous: true, reason: `the link carries a long hex run in "${key}"` };
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
if (anchor.sha256 !== undefined && !/^[0-9a-f]{64}$/.test(String(anchor.sha256))) {
|
|
630
|
-
return { dangerous: true, reason: 'the link\'s sha256 is not a 64-hex digest' };
|
|
631
|
-
}
|
|
632
|
-
if (anchor.attestation !== undefined && !/^[0-9a-f]{32}$/.test(String(anchor.attestation))) {
|
|
633
|
-
return { dangerous: true, reason: 'the link\'s attestation is not a 32-hex tag' };
|
|
634
|
-
}
|
|
635
|
-
return { dangerous: false, reason: null };
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
/** `inspect`, as a throw. Used before anything is uploaded. */
|
|
639
|
-
function assertPublishable(name, text, opts = {}) {
|
|
640
|
-
const verdict = inspect(name, text, opts);
|
|
641
|
-
if (verdict.dangerous) {
|
|
642
|
-
throw new Error(
|
|
643
|
-
`vault: refusing to publish ${name} — ${verdict.reason}. ` +
|
|
644
|
-
'The vault carries sealed records only: a key that reaches cloud storage can mint ' +
|
|
645
|
-
'records indistinguishable from yours, so it is never a backup. Keep it in ' +
|
|
646
|
-
`${authorship.defaultKeyPath(opts.env || process.env)} (0600) and back it up to a ` +
|
|
647
|
-
'local disk or a password manager.',
|
|
648
|
-
);
|
|
649
|
-
}
|
|
650
|
-
return true;
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
// ---------------------------------------------------------------------------
|
|
654
|
-
// naming
|
|
655
|
-
// ---------------------------------------------------------------------------
|
|
656
|
-
|
|
657
|
-
/** `<keyFingerprint>-<behaviour>.<stamp>` — ASCII, filename-safe, from the record. */
|
|
658
|
-
function baseName(record, createdAt = null) {
|
|
659
|
-
const behaviour = record && record.behaviour ? String(record.behaviour) : 'unobserved';
|
|
660
|
-
const stamp = String(createdAt || (record && record.createdAt) || new Date().toISOString())
|
|
661
|
-
.replace(/[:.]/g, '-');
|
|
662
|
-
return `${record.keyFingerprint}-${behaviour}.${stamp}`;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
/** `https://drive.google.com/open?id=<id>` — an owner link. Sharing is never changed. */
|
|
666
|
-
function driveUrl(id) {
|
|
667
|
-
return id ? `https://drive.google.com/open?id=${encodeURIComponent(id)}` : null;
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
function sha256(text) {
|
|
671
|
-
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
// ---------------------------------------------------------------------------
|
|
675
|
-
// publish
|
|
676
|
-
// ---------------------------------------------------------------------------
|
|
677
|
-
|
|
678
|
-
/**
|
|
679
|
-
* Read the record to publish.
|
|
680
|
-
*
|
|
681
|
-
* A path or an in-memory record; the path form is preferred because the bytes
|
|
682
|
-
* on disk are the bytes `verify` was run against and the digest is then about a
|
|
683
|
-
* file rather than about a re-serialisation that might differ by whitespace.
|
|
684
|
-
*/
|
|
685
|
-
function readRecord({ file = null, record = null, secret = null, env = process.env }) {
|
|
686
|
-
if (file) {
|
|
687
|
-
const abs = path.resolve(file);
|
|
688
|
-
if (!fs.existsSync(abs)) throw new Error(`vault: no record at ${abs}`);
|
|
689
|
-
const text = fs.readFileSync(abs, 'utf8');
|
|
690
|
-
// The guard runs FIRST, on the raw bytes, and that order is the whole
|
|
691
|
-
// point: parsing first means publishing a key file fails with "is not
|
|
692
|
-
// JSON" — true, and useless, because it says nothing about the actual
|
|
693
|
-
// problem, which is where the file was going. A refusal has to name what
|
|
694
|
-
// is wrong with what the user asked for.
|
|
695
|
-
assertPublishable(abs, text, { secret, keyPath: authorship.defaultKeyPath(env), env });
|
|
696
|
-
let parsed;
|
|
697
|
-
try {
|
|
698
|
-
parsed = JSON.parse(text);
|
|
699
|
-
} catch (e) {
|
|
700
|
-
throw new Error(`vault: ${abs} is not JSON — ${e.message}`);
|
|
701
|
-
}
|
|
702
|
-
return { text, record: parsed, file: abs, serialised: text };
|
|
703
|
-
}
|
|
704
|
-
if (record) {
|
|
705
|
-
const text = JSON.stringify(record, null, 2) + '\n';
|
|
706
|
-
return { text, record, file: null, serialised: text };
|
|
707
|
-
}
|
|
708
|
-
throw new Error('vault: publish needs a record file or a record');
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
/**
|
|
712
|
-
* Publish a sealed record, and link the local copy to the copy that travelled.
|
|
713
|
-
*
|
|
714
|
-
* @param {object} o
|
|
715
|
-
* @param {string} [o.file] path to the sealed record
|
|
716
|
-
* @param {object} [o.record] or the record itself
|
|
717
|
-
* @param {object} [o.env] env (injectable; tests)
|
|
718
|
-
* @param {string[]} [o.argv] flags: --remote --root --rclone --dry-run --no-index
|
|
719
|
-
* @param {boolean} [o.dryRun] resolve everything, upload nothing
|
|
720
|
-
* @param {boolean} [o.index] append to index.jsonl (default true)
|
|
721
|
-
* @param {string} [o.secret] the caller's key, if it has it — checked for leaks
|
|
722
|
-
* @param {Date|string} [o.now] publishedAt, injectable so a test can pin it
|
|
723
|
-
* @returns {{ok: boolean, anchor: object, url: string|null, remotePath: string, dryRun: boolean}}
|
|
724
|
-
*/
|
|
725
|
-
async function publish(o = {}) {
|
|
726
|
-
const env = o.env || process.env;
|
|
727
|
-
const argv = o.argv || [];
|
|
728
|
-
const target = vaultTarget(env, argv);
|
|
729
|
-
const dryRun = Boolean(o.dryRun) || has(argv, '--dry-run');
|
|
730
|
-
const wantIndex = o.index === undefined ? !has(argv, '--no-index') : Boolean(o.index);
|
|
731
|
-
|
|
732
|
-
const secret = o.secret || null;
|
|
733
|
-
const { text, record, file } = readRecord({ ...o, secret, env });
|
|
734
|
-
|
|
735
|
-
// Shape first: `fp.id` throws for anything that is not a fingerprinted
|
|
736
|
-
// record, so a JSON file that is merely *not a key* still cannot be published
|
|
737
|
-
// as a record. Both checks are needed and they are different checks.
|
|
738
|
-
let id;
|
|
739
|
-
try {
|
|
740
|
-
id = fp.id(record);
|
|
741
|
-
} catch (e) {
|
|
742
|
-
throw new Error(`vault: not a sealed φ(α) record — ${(e && e.message) || e}`);
|
|
743
|
-
}
|
|
744
|
-
|
|
745
|
-
// The name is checked separately from the path: a caller can hand over a key
|
|
746
|
-
// by *name* (`keys/agent.key` copied into the records directory as
|
|
747
|
-
// `agent.key`) and the basename is the last thing that would catch it.
|
|
748
|
-
const keyPath = authorship.defaultKeyPath(env);
|
|
749
|
-
assertPublishable(path.basename(file || 'record.json'), text, { secret, keyPath, env });
|
|
750
|
-
|
|
751
|
-
const recordName = `${baseName(record)}.json`;
|
|
752
|
-
// ONE rule for the anchor's name, and it is the record's name plus the
|
|
753
|
-
// suffix — the same rule `localAnchor` uses to find it beside the local
|
|
754
|
-
// record. It used to be derived from the record's *stem*, so the local link
|
|
755
|
-
// (`x.json.anchor.json`) and the published link (`x.anchor.json`) had
|
|
756
|
-
// different names: `anchor` found one, `vault list` paired the other, and the
|
|
757
|
-
// record's own link could not be fetched by the name it was stored under.
|
|
758
|
-
const anchorName = `${recordName}${ANCHOR_SUFFIX}`;
|
|
759
|
-
const recordRel = `${RECORDS_DIR}/${recordName}`;
|
|
760
|
-
const anchorRel = `${RECORDS_DIR}/${anchorName}`;
|
|
761
|
-
|
|
762
|
-
const digest = sha256(text);
|
|
763
|
-
const anchor = {
|
|
764
|
-
v: ANCHOR_VERSION,
|
|
765
|
-
kind: ANCHOR_KIND,
|
|
766
|
-
id,
|
|
767
|
-
keyFingerprint: record.keyFingerprint,
|
|
768
|
-
behaviour: record.behaviour || null,
|
|
769
|
-
code: record.code || null,
|
|
770
|
-
createdAt: record.createdAt,
|
|
771
|
-
attestation: record.attestation,
|
|
772
|
-
sha256: digest,
|
|
773
|
-
bytes: Buffer.byteLength(text, 'utf8'),
|
|
774
|
-
// The backend is recorded because a link has to say WHERE the copy is for
|
|
775
|
-
// `anchor` to look in the right place: the same record can be published to
|
|
776
|
-
// the account vault and to a Drive folder, and the two are different links.
|
|
777
|
-
backend: target.backend,
|
|
778
|
-
remote: target.remote,
|
|
779
|
-
root: target.root,
|
|
780
|
-
// `path` is for a human (and for pasting into rclone); `key` is the
|
|
781
|
-
// root-relative form the reader uses. Both, because a single field that
|
|
782
|
-
// means one thing to a person and another to rclone is how the root got
|
|
783
|
-
// applied twice.
|
|
784
|
-
path: target.backend === BACKEND_CLOUD
|
|
785
|
-
? `${CLOUD_PREFIX}/${recordRel}`
|
|
786
|
-
: `${target.root}/${recordRel}`,
|
|
787
|
-
key: recordRel,
|
|
788
|
-
emittedAt: new Date(o.now || Date.now()).toISOString(),
|
|
789
|
-
driveId: null,
|
|
790
|
-
url: null,
|
|
791
|
-
index: wantIndex ? `${target.root}/${RECORDS_DIR}/${INDEX_NAME}` : null,
|
|
792
|
-
};
|
|
793
|
-
|
|
794
|
-
const transport = transportFor(target, o);
|
|
795
|
-
|
|
796
|
-
if (dryRun) {
|
|
797
|
-
return {
|
|
798
|
-
ok: true,
|
|
799
|
-
dryRun: true,
|
|
800
|
-
backend: target.backend,
|
|
801
|
-
anchor,
|
|
802
|
-
url: null,
|
|
803
|
-
remotePath: anchor.path,
|
|
804
|
-
commands: target.backend === BACKEND_CLOUD
|
|
805
|
-
? [`PUT ${target.apiBase}${CLOUD_PREFIX}/${recordRel}`, `PUT ${target.apiBase}${CLOUD_PREFIX}/${anchorRel}`]
|
|
806
|
-
: [`rclone copyto ${file || '<record>'} ${remoteSpec(target, recordRel)}`, `rclone copyto <anchor> ${remoteSpec(target, anchorRel)}`],
|
|
807
|
-
};
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
// Upload the *sealed bytes*. When publishing from a path, that is the file
|
|
811
|
-
// itself; otherwise it is written out first so a download can be diffed
|
|
812
|
-
// against the thing that was sealed.
|
|
813
|
-
if (file) await transport.putFile(recordRel, file);
|
|
814
|
-
else await transport.put(recordRel, text, { name: recordName });
|
|
815
|
-
|
|
816
|
-
// The Drive id comes from a listing, not from a shareable-link call: a
|
|
817
|
-
// `link` would change the folder's sharing, and publishing a record must
|
|
818
|
-
// not touch who can read the vault. The cloud backend returns its own
|
|
819
|
-
// object id and url from the same kind of listing.
|
|
820
|
-
const listed = await transport.list(RECORDS_DIR);
|
|
821
|
-
const entry = listed.find((f) => String(f.Name) === recordName) || null;
|
|
822
|
-
if (entry) {
|
|
823
|
-
anchor.driveId = entry.ID || null;
|
|
824
|
-
anchor.url = entry.url || (target.backend === BACKEND_CLOUD ? null : driveUrl(entry.ID));
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
const localAnchor = file ? `${file}${ANCHOR_SUFFIX}` : null;
|
|
828
|
-
const anchorText = JSON.stringify(anchor, null, 2) + '\n';
|
|
829
|
-
await transport.put(anchorRel, anchorText, { name: anchorName });
|
|
830
|
-
if (localAnchor) fs.writeFileSync(localAnchor, anchorText);
|
|
831
|
-
|
|
832
|
-
let indexLines = null;
|
|
833
|
-
if (wantIndex) indexLines = await appendIndex(target, anchor, transport);
|
|
834
|
-
|
|
835
|
-
return {
|
|
836
|
-
ok: true,
|
|
837
|
-
dryRun: false,
|
|
838
|
-
backend: target.backend,
|
|
839
|
-
anchor,
|
|
840
|
-
url: anchor.url,
|
|
841
|
-
localAnchor,
|
|
842
|
-
remotePath: anchor.path,
|
|
843
|
-
bytes: anchor.bytes,
|
|
844
|
-
sha256: digest,
|
|
845
|
-
indexLines,
|
|
846
|
-
};
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
/** Read one remote text file through rclone, `null` when it is not there. */
|
|
850
|
-
function rcloneCat(target, remotePath) {
|
|
851
|
-
try {
|
|
852
|
-
return rcloneRun(target, ['cat', remoteSpecOf(target, remotePath)]);
|
|
853
|
-
} catch (e) {
|
|
854
|
-
if (e.code === 'ERCLONE' && /not found|does not exist|error 404/i.test(e.stderr || e.message)) return null;
|
|
855
|
-
throw e;
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
/** `lsjson --files-only` as objects, tolerating an empty or absent directory. */
|
|
860
|
-
function listRaw(target, remotePath) {
|
|
861
|
-
let raw;
|
|
862
|
-
try {
|
|
863
|
-
raw = rcloneRun(target, ['lsjson', remoteSpecOf(target, remotePath), '--files-only']);
|
|
864
|
-
} catch (e) {
|
|
865
|
-
if (e.code === 'ERCLONE' && /not found|does not exist|error 404|directory not found/i.test(e.stderr || e.message)) return [];
|
|
866
|
-
throw e;
|
|
867
|
-
}
|
|
868
|
-
const text = String(raw).trim();
|
|
869
|
-
if (!text) return [];
|
|
870
|
-
const parsed = JSON.parse(text);
|
|
871
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
/**
|
|
875
|
-
* Append one line to the vault ledger.
|
|
876
|
-
*
|
|
877
|
-
* Read-modify-write, which has a last-writer-wins race if two publishes overlap.
|
|
878
|
-
* That is why the per-record `.anchor.json` — written one file per publish, no
|
|
879
|
-
* read first — is the authoritative link and this is a convenience: losing a
|
|
880
|
-
* ledger line loses nothing that cannot be rebuilt from the anchors beside each
|
|
881
|
-
* record (`list` reads those, not this).
|
|
882
|
-
*/
|
|
883
|
-
async function appendIndex(target, anchor, transport = transportFor(target)) {
|
|
884
|
-
const rel = `${RECORDS_DIR}/${INDEX_NAME}`;
|
|
885
|
-
// `cat` resolves null for a missing object on BOTH backends (the rclone
|
|
886
|
-
// adapter maps "not found", the cloud adapter maps a 404), so a first publish
|
|
887
|
-
// starts from an empty ledger rather than from an error.
|
|
888
|
-
const existing = (await transport.cat(rel)) || '';
|
|
889
|
-
const line = JSON.stringify({
|
|
890
|
-
kind: INDEX_KIND,
|
|
891
|
-
id: anchor.id,
|
|
892
|
-
keyFingerprint: anchor.keyFingerprint,
|
|
893
|
-
sha256: anchor.sha256,
|
|
894
|
-
path: anchor.path,
|
|
895
|
-
url: anchor.url,
|
|
896
|
-
driveId: anchor.driveId,
|
|
897
|
-
emittedAt: anchor.emittedAt,
|
|
898
|
-
});
|
|
899
|
-
await transport.put(rel, existing + line + '\n', { name: INDEX_NAME });
|
|
900
|
-
return (existing.trim() ? existing.trim().split('\n').length : 0) + 1;
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
// ---------------------------------------------------------------------------
|
|
904
|
-
// the link, read back
|
|
905
|
-
// ---------------------------------------------------------------------------
|
|
906
|
-
|
|
907
|
-
/** The anchor stored beside a local record. `null` when the record was never published. */
|
|
908
|
-
function localAnchor(file) {
|
|
909
|
-
const sidecar = `${path.resolve(file)}${ANCHOR_SUFFIX}`;
|
|
910
|
-
if (!fs.existsSync(sidecar)) return null;
|
|
911
|
-
try {
|
|
912
|
-
return JSON.parse(fs.readFileSync(sidecar, 'utf8'));
|
|
913
|
-
} catch {
|
|
914
|
-
return null;
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
/**
|
|
919
|
-
* Check the published copy against the link.
|
|
920
|
-
*
|
|
921
|
-
* Three separate claims, reported separately, because they fail for different
|
|
922
|
-
* reasons and a single boolean would hide which:
|
|
923
|
-
*
|
|
924
|
-
* present there is a copy at the anchored path
|
|
925
|
-
* unchanged its sha256 is the one recorded at publish time
|
|
926
|
-
* attested the key on this machine still recomputes its attestation
|
|
927
|
-
*
|
|
928
|
-
* The third is the one worth having: a copy that is byte-identical but whose
|
|
929
|
-
* attestation no longer recomputes means the key moved on (or the record was
|
|
930
|
-
* published by another key), and no digest of the file would ever show that.
|
|
931
|
-
*/
|
|
932
|
-
async function checkAnchor(o = {}) {
|
|
933
|
-
const env = o.env || process.env;
|
|
934
|
-
const argv = o.argv || [];
|
|
935
|
-
const anchor = o.anchor || (o.file ? localAnchor(o.file) : null);
|
|
936
|
-
if (!anchor) {
|
|
937
|
-
return { ok: false, reason: 'not linked — no anchor beside this record (publish it first)', present: false, unchanged: null, attested: null };
|
|
938
|
-
}
|
|
939
|
-
// The link says WHERE it was published, so the check reads the backend off the
|
|
940
|
-
// anchor rather than off this machine's current default: a record published to
|
|
941
|
-
// the account vault must still verify after the user switches their default to
|
|
942
|
-
// a Drive remote (and the other way round).
|
|
943
|
-
const target = vaultTarget(env, argv, anchor);
|
|
944
|
-
const transport = transportFor(target, o);
|
|
945
|
-
|
|
946
|
-
const text = await transport.cat(anchor.key || anchor.path);
|
|
947
|
-
if (text === null) {
|
|
948
|
-
// `present`, not `presence`: the field name is part of the answer, and a
|
|
949
|
-
// consumer reading `.present` got `undefined` from this branch while the
|
|
950
|
-
// other three returned a real boolean — an inconsistency that only shows up
|
|
951
|
-
// when the copy is missing, which is exactly when someone is looking.
|
|
952
|
-
return { ok: false, reason: `no copy at ${anchor.path}`, present: false, unchanged: false, attested: null, anchor };
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
const unchanged = sha256(text) === anchor.sha256;
|
|
956
|
-
|
|
957
|
-
let attested = null;
|
|
958
|
-
let attestationReason = null;
|
|
959
|
-
try {
|
|
960
|
-
const key = o.key || authorship.resolveKey({ argv, env });
|
|
961
|
-
if (!key.secret) {
|
|
962
|
-
attestationReason = 'no authorship key on this machine to recompute with';
|
|
963
|
-
} else {
|
|
964
|
-
const v = fp.verify(JSON.parse(text), key.secret);
|
|
965
|
-
attested = v.ok;
|
|
966
|
-
attestationReason = v.reason;
|
|
967
|
-
}
|
|
968
|
-
} catch (e) {
|
|
969
|
-
attestationReason = (e && e.message) || String(e);
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
return {
|
|
973
|
-
ok: unchanged && attested !== false,
|
|
974
|
-
anchor,
|
|
975
|
-
present: true,
|
|
976
|
-
unchanged,
|
|
977
|
-
attested,
|
|
978
|
-
attestationReason,
|
|
979
|
-
remotePath: anchor.path,
|
|
980
|
-
url: anchor.url,
|
|
981
|
-
reason: unchanged
|
|
982
|
-
? attested === false
|
|
983
|
-
? `the published copy does not verify: ${attestationReason}`
|
|
984
|
-
: null
|
|
985
|
-
: 'the published copy is not the bytes that were sealed (sha256 differs)',
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
/** What is in the vault. Reads the anchors, which is why the ledger is optional. */
|
|
990
|
-
async function list(o = {}) {
|
|
991
|
-
const env = o.env || process.env;
|
|
992
|
-
const argv = o.argv || [];
|
|
993
|
-
const target = vaultTarget(env, argv);
|
|
994
|
-
const transport = transportFor(target, o);
|
|
995
|
-
const dir = RECORDS_DIR;
|
|
996
|
-
const files = await transport.list(dir);
|
|
997
|
-
const anchors = files.filter((f) => String(f.Name).endsWith(ANCHOR_SUFFIX));
|
|
998
|
-
const records = files.filter((f) => !String(f.Name).endsWith(ANCHOR_SUFFIX) && String(f.Name).endsWith('.json') && f.Name !== INDEX_NAME);
|
|
999
|
-
|
|
1000
|
-
const rows = [];
|
|
1001
|
-
for (const r of records) {
|
|
1002
|
-
// Paired by the same rule that wrote it: the anchor is the record's name
|
|
1003
|
-
// plus the suffix. Stripping `.json` off the record name first would look
|
|
1004
|
-
// for `<stem>.anchor.json`, which is not the name anything was written
|
|
1005
|
-
// under.
|
|
1006
|
-
const anchorFile = anchors.find((a) => String(a.Name) === `${r.Name}${ANCHOR_SUFFIX}`);
|
|
1007
|
-
let anchor = null;
|
|
1008
|
-
if (anchorFile) {
|
|
1009
|
-
// `cat` resolves the path against the root, so `records/<name>` here
|
|
1010
|
-
// means `<remote>:<root>/records/<name>` — stated because getting this
|
|
1011
|
-
// wrong is what put the ledger one directory too deep.
|
|
1012
|
-
const text = await transport.cat(`${dir}/${anchorFile.Name}`);
|
|
1013
|
-
try {
|
|
1014
|
-
anchor = JSON.parse(text);
|
|
1015
|
-
} catch {
|
|
1016
|
-
anchor = { unreadable: true };
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
rows.push({
|
|
1020
|
-
name: r.Name,
|
|
1021
|
-
bytes: r.Size,
|
|
1022
|
-
emittedAt: r.ModTime,
|
|
1023
|
-
id: anchor ? anchor.id : null,
|
|
1024
|
-
keyFingerprint: anchor ? anchor.keyFingerprint : null,
|
|
1025
|
-
sha256: anchor ? anchor.sha256 : null,
|
|
1026
|
-
driveId: (anchor && anchor.driveId) || r.ID || null,
|
|
1027
|
-
url: (anchor && anchor.url) || r.url || driveUrl(r.ID),
|
|
1028
|
-
linked: Boolean(anchor),
|
|
1029
|
-
});
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
return {
|
|
1033
|
-
ok: true,
|
|
1034
|
-
backend: target.backend,
|
|
1035
|
-
remote: target.remote,
|
|
1036
|
-
root: target.root,
|
|
1037
|
-
where: transport.describe,
|
|
1038
|
-
records: rows,
|
|
1039
|
-
};
|
|
1040
|
-
}
|
|
1041
|
-
|
|
1042
|
-
/**
|
|
1043
|
-
* Inspect what is already in the vault for key material.
|
|
1044
|
-
*
|
|
1045
|
-
* `publish` cannot stop what was put there before it existed, and the honest
|
|
1046
|
-
* answer to "is a key in the vault?" has to be a command rather than an
|
|
1047
|
-
* assurance. This reads every object under the root — not just `records/`,
|
|
1048
|
-
* because the copy that matters here is `keys/agent.key`, which lives outside
|
|
1049
|
-
* the records directory by definition.
|
|
1050
|
-
*
|
|
1051
|
-
* Reading is capped (`MAX_INSPECT_BYTES`, `MAX_AUDIT_FILES`) and reported as
|
|
1052
|
-
* capped: an audit that silently stops inspecting is worse than one that says
|
|
1053
|
-
* it did.
|
|
1054
|
-
*/
|
|
1055
|
-
async function audit(o = {}) {
|
|
1056
|
-
const env = o.env || process.env;
|
|
1057
|
-
const argv = o.argv || [];
|
|
1058
|
-
const target = vaultTarget(env, argv);
|
|
1059
|
-
const transport = transportFor(target, o);
|
|
1060
|
-
const max = Number(flag(argv, '--max')) || MAX_AUDIT_FILES;
|
|
1061
|
-
|
|
1062
|
-
let files;
|
|
1063
|
-
try {
|
|
1064
|
-
// The whole root, recursively: the object this audit exists to find
|
|
1065
|
-
// (`keys/agent.key`) is deliberately outside `records/`.
|
|
1066
|
-
files = await transport.listRecursive('');
|
|
1067
|
-
} catch (e) {
|
|
1068
|
-
return { ok: false, backend: target.backend, where: transport.describe, error: (e && e.message) || String(e), findings: [], checked: 0 };
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
const secret = o.secret || null;
|
|
1072
|
-
const findings = [];
|
|
1073
|
-
const uninspected = [];
|
|
1074
|
-
let checked = 0;
|
|
1075
|
-
|
|
1076
|
-
for (const file of files) {
|
|
1077
|
-
const rel = String(file.Path || file.Name);
|
|
1078
|
-
if (checked >= max) {
|
|
1079
|
-
uninspected.push({ path: rel, reason: `stopped after ${max} files` });
|
|
1080
|
-
continue;
|
|
1081
|
-
}
|
|
1082
|
-
if (Number(file.Size) > MAX_INSPECT_BYTES) {
|
|
1083
|
-
uninspected.push({ path: rel, reason: `larger than ${MAX_INSPECT_BYTES} bytes` });
|
|
1084
|
-
continue;
|
|
1085
|
-
}
|
|
1086
|
-
checked += 1;
|
|
1087
|
-
let text;
|
|
1088
|
-
try {
|
|
1089
|
-
text = await transport.cat(rel);
|
|
1090
|
-
} catch (e) {
|
|
1091
|
-
uninspected.push({ path: rel, reason: (e && e.message) || String(e) });
|
|
1092
|
-
continue;
|
|
1093
|
-
}
|
|
1094
|
-
const verdict = inspect(rel, text, { secret });
|
|
1095
|
-
if (verdict.dangerous) findings.push({ path: rel, reason: verdict.reason });
|
|
1096
|
-
}
|
|
1097
|
-
|
|
1098
|
-
return {
|
|
1099
|
-
ok: findings.length === 0,
|
|
1100
|
-
backend: target.backend,
|
|
1101
|
-
remote: target.remote,
|
|
1102
|
-
root: target.root,
|
|
1103
|
-
where: transport.describe,
|
|
1104
|
-
checked,
|
|
1105
|
-
files: files.length,
|
|
1106
|
-
uninspected,
|
|
1107
|
-
findings,
|
|
1108
|
-
};
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
/** Every file under a prefix, with repo-relative names. */
|
|
1112
|
-
function rcloneLsjsonRecursive(target, prefix) {
|
|
1113
|
-
const raw = rcloneRun(target, ['lsjson', remoteSpecOf(target, prefix), '--files-only', '--recursive']);
|
|
1114
|
-
const text = String(raw).trim();
|
|
1115
|
-
if (!text) return [];
|
|
1116
|
-
const parsed = JSON.parse(text);
|
|
1117
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
module.exports = {
|
|
1121
|
-
DEFAULT_REMOTE,
|
|
1122
|
-
DEFAULT_ROOT,
|
|
1123
|
-
DEFAULT_BACKEND,
|
|
1124
|
-
BACKEND_CLOUD,
|
|
1125
|
-
BACKEND_RCLONE,
|
|
1126
|
-
CLOUD_PREFIX,
|
|
1127
|
-
BACKEND_ENV,
|
|
1128
|
-
API_BASE_ENV,
|
|
1129
|
-
RECORDS_DIR,
|
|
1130
|
-
INDEX_NAME,
|
|
1131
|
-
ANCHOR_SUFFIX,
|
|
1132
|
-
ANCHOR_KIND,
|
|
1133
|
-
INDEX_KIND,
|
|
1134
|
-
RCLONE_ENV,
|
|
1135
|
-
REMOTE_ENV,
|
|
1136
|
-
ROOT_ENV,
|
|
1137
|
-
inspect,
|
|
1138
|
-
assertPublishable,
|
|
1139
|
-
publish,
|
|
1140
|
-
checkAnchor,
|
|
1141
|
-
list,
|
|
1142
|
-
audit,
|
|
1143
|
-
localAnchor,
|
|
1144
|
-
relativeToRoot,
|
|
1145
|
-
remoteSpecOf,
|
|
1146
|
-
baseName,
|
|
1147
|
-
driveUrl,
|
|
1148
|
-
vaultTarget,
|
|
1149
|
-
rcloneBinary,
|
|
1150
|
-
rcloneCat,
|
|
1151
|
-
transportFor,
|
|
1152
|
-
cloudApiKey,
|
|
1153
|
-
backendFor,
|
|
1154
|
-
sha256,
|
|
1155
|
-
flag,
|
|
1156
|
-
has,
|
|
1157
|
-
};
|
|
105
|
+
*/function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const e of s){const t=String(e.Path||e.Name);if(u>=a){l.push({path:t,reason:`stopped after ${a} files`});continue}if(Number(e.Size)>2097152){l.push({path:t,reason:"larger than 2097152 bytes"});continue}let r;u+=1;try{r=await o.cat(t)}catch(e){l.push({path:t,reason:e&&e.message||String(e)});continue}const n=inspect(t,r,{secret:i});n.dangerous&&c.push({path:t,reason:n.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
|