prae-cli 0.7.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,392 @@
1
+ import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, scryptSync, sign, verify } from "node:crypto";
4
+
5
+ //#region ../ledger/src/entry.ts
6
+ /** The hash a chain starts from. */
7
+ const GENESIS = "0".repeat(64);
8
+ /**
9
+ * Deterministic serialization: object keys sorted at every depth.
10
+ *
11
+ * A hash over `JSON.stringify(entry)` would depend on key insertion order,
12
+ * which means a re-serialized entry could hash differently while saying
13
+ * exactly the same thing — and a verifier that reports tampering on a
14
+ * faithful copy trains its operators to ignore it.
15
+ */
16
+ function canonical(value) {
17
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
18
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
19
+ return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
20
+ }
21
+ /** Hash one entry's content together with its position and predecessor. */
22
+ function hashEntry(record, seq, prev) {
23
+ return createHash("sha256").update(canonical({
24
+ ...record,
25
+ seq,
26
+ prev
27
+ })).digest("hex");
28
+ }
29
+ /** Chain a record onto a predecessor. */
30
+ function chain(record, seq, prev) {
31
+ return {
32
+ ...record,
33
+ seq,
34
+ prev,
35
+ hash: hashEntry(record, seq, prev)
36
+ };
37
+ }
38
+ /** The short form an auditor quotes from a screenshot. */
39
+ function seal(entry) {
40
+ return `${entry.hash.slice(0, 4)}…${entry.hash.slice(-4)}`;
41
+ }
42
+
43
+ //#endregion
44
+ //#region ../ledger/src/receipt.ts
45
+ function generateKeypair() {
46
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
47
+ return {
48
+ publicKey: publicKey.export({
49
+ type: "spki",
50
+ format: "pem"
51
+ }).toString(),
52
+ privateKey: privateKey.export({
53
+ type: "pkcs8",
54
+ format: "pem"
55
+ }).toString()
56
+ };
57
+ }
58
+ /** Sign a row's seal. The seal already covers the whole canonical record. */
59
+ function signEntry(entry, privateKeyPem) {
60
+ const key = createPrivateKey(privateKeyPem);
61
+ return sign(null, Buffer.from(entry.hash, "hex"), key).toString("base64");
62
+ }
63
+ function verifySignature(entry, signature, publicKeyPem) {
64
+ try {
65
+ const key = createPublicKey(publicKeyPem);
66
+ return verify(null, Buffer.from(entry.hash, "hex"), key, Buffer.from(signature, "base64"));
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+ function makeReceipt(entry, privateKeyPem, publicKeyPem) {
72
+ return {
73
+ receipt: "prae/1",
74
+ entry,
75
+ signature: signEntry(entry, privateKeyPem),
76
+ publicKey: publicKeyPem
77
+ };
78
+ }
79
+ /** Verify a receipt from nothing but the receipt. */
80
+ function verifyReceipt(receipt) {
81
+ if (receipt.receipt !== "prae/1") return {
82
+ ok: false,
83
+ reason: `unknown receipt format ${String(receipt.receipt)}`
84
+ };
85
+ const { seq, prev, hash, sig,...record } = receipt.entry;
86
+ if (hashEntry(record, seq, prev) !== hash) return {
87
+ ok: false,
88
+ reason: "entry contents do not match their seal; the row was altered"
89
+ };
90
+ if (!verifySignature(receipt.entry, receipt.signature, receipt.publicKey)) return {
91
+ ok: false,
92
+ reason: "signature does not verify; not sealed by this key"
93
+ };
94
+ return { ok: true };
95
+ }
96
+ /**
97
+ * A short identifier for a public key, for pinning by eye.
98
+ *
99
+ * A counterparty checks a receipt against a key they already trust; comparing
100
+ * the whole PEM by hand invites skimming, and eight grouped hex bytes do not.
101
+ */
102
+ function fingerprint(publicKeyPem) {
103
+ const der = createPublicKey(publicKeyPem).export({
104
+ type: "spki",
105
+ format: "der"
106
+ });
107
+ return createHash("sha256").update(der).digest("hex").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
108
+ }
109
+
110
+ //#endregion
111
+ //#region ../ledger/src/authority.ts
112
+ const priv = (k) => typeof k === "string" ? createPrivateKey(k) : k;
113
+ /** How long a signed answer is good for, by default. */
114
+ const ANSWER_TTL_MS = 5 * 6e4;
115
+ /** A detached signature over exact bytes (a policy pack's file). */
116
+ function signBytes(bytes, privateKey) {
117
+ return sign(null, Buffer.from(bytes), priv(privateKey)).toString("base64");
118
+ }
119
+ /**
120
+ * How a private key is sealed at rest: scrypt (N = 2^17, r = 8, p = 1) over
121
+ * the passphrase, AES-256-GCM over the key. The sealed file can sit where an
122
+ * agent can read it; each guess at the passphrase costs ~128 MiB and a
123
+ * noticeable fraction of a second, so a strong passphrase holds against an
124
+ * offline attack. (PKCS#8 as Node writes it uses PBKDF2 at 2,048 rounds —
125
+ * too cheap for a file the agent can copy.)
126
+ */
127
+ const SCRYPT = {
128
+ N: 2 ** 17,
129
+ r: 8,
130
+ p: 1,
131
+ maxmem: 512 * 1024 * 1024
132
+ };
133
+ const MIN_PASSPHRASE = 12;
134
+ const SEALED = "PRAE SEALED KEY";
135
+ function sealPrivateKey(key, passphrase) {
136
+ if (passphrase.length < MIN_PASSPHRASE) throw new Error(`passphrase: ${MIN_PASSPHRASE} characters or more`);
137
+ const salt = randomBytes(16);
138
+ const iv = randomBytes(12);
139
+ const cipher = createCipheriv("aes-256-gcm", scryptSync(passphrase, salt, 32, SCRYPT), iv);
140
+ const der = key.export({
141
+ type: "pkcs8",
142
+ format: "der"
143
+ });
144
+ const data = Buffer.concat([cipher.update(der), cipher.final()]);
145
+ return `-----BEGIN ${SEALED}-----\n${(Buffer.from(JSON.stringify({
146
+ v: 1,
147
+ kdf: "scrypt",
148
+ N: SCRYPT.N,
149
+ r: SCRYPT.r,
150
+ p: SCRYPT.p,
151
+ salt: salt.toString("base64"),
152
+ iv: iv.toString("base64"),
153
+ tag: cipher.getAuthTag().toString("base64"),
154
+ data: data.toString("base64")
155
+ })).toString("base64").match(/.{1,64}/g) ?? []).join("\n")}\n-----END ${SEALED}-----\n`;
156
+ }
157
+ /** A keypair whose private half is sealed under a passphrase. */
158
+ function sealedKeypair(passphrase) {
159
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
160
+ return {
161
+ publicKey: publicKey.export({
162
+ type: "spki",
163
+ format: "pem"
164
+ }).toString(),
165
+ sealedPrivateKey: sealPrivateKey(privateKey, passphrase)
166
+ };
167
+ }
168
+ /** Unseal into memory. Throws on a wrong passphrase or a tampered file. */
169
+ function unsealPrivateKey(sealed, passphrase) {
170
+ const match = sealed.match(/* @__PURE__ */ new RegExp(`-----BEGIN ${SEALED}-----([\\s\\S]+?)-----END ${SEALED}-----`));
171
+ if (match === null) throw new Error("not a PRAE sealed key (an older format?): make a new one with prae keygen --role");
172
+ const box = JSON.parse(Buffer.from((match[1] ?? "").replace(/\s/g, ""), "base64").toString("utf8"));
173
+ if (box.v !== 1 || box.kdf !== "scrypt") throw new Error("unknown sealing");
174
+ const decipher = createDecipheriv("aes-256-gcm", scryptSync(passphrase, Buffer.from(String(box.salt), "base64"), 32, {
175
+ N: Number(box.N),
176
+ r: Number(box.r),
177
+ p: Number(box.p),
178
+ maxmem: SCRYPT.maxmem
179
+ }), Buffer.from(String(box.iv), "base64"));
180
+ decipher.setAuthTag(Buffer.from(String(box.tag), "base64"));
181
+ return createPrivateKey({
182
+ key: Buffer.concat([decipher.update(Buffer.from(String(box.data), "base64")), decipher.final()]),
183
+ format: "der",
184
+ type: "pkcs8"
185
+ });
186
+ }
187
+
188
+ //#endregion
189
+ //#region ../ledger/src/ledger.ts
190
+ /**
191
+ * Read a ledger held as text.
192
+ *
193
+ * Split out from the class because a ledger is not always a file being
194
+ * appended to: a build step renders one it imported, and a reader pastes one
195
+ * in. Those callers need the same parsing and the same verification the CLI
196
+ * runs, and a second implementation of either is how two answers to "does this
197
+ * chain hold" come to exist.
198
+ */
199
+ function readEntries(text) {
200
+ return text.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
201
+ }
202
+ /** Re-derive every hash and confirm each entry names its predecessor. */
203
+ function verifyEntries(text) {
204
+ const problems = [];
205
+ let expectedPrev = GENESIS;
206
+ let expectedSeq = 0;
207
+ let count = 0;
208
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
209
+ for (const [index, line] of lines.entries()) {
210
+ const at = index + 1;
211
+ count += 1;
212
+ let entry;
213
+ try {
214
+ entry = JSON.parse(line);
215
+ } catch {
216
+ problems.push({
217
+ line: at,
218
+ message: "not valid JSON"
219
+ });
220
+ return {
221
+ ok: false,
222
+ entries: count,
223
+ problems
224
+ };
225
+ }
226
+ if (entry.seq !== expectedSeq) problems.push({
227
+ line: at,
228
+ message: `expected seq ${expectedSeq}, found ${entry.seq}`
229
+ });
230
+ if (entry.prev !== expectedPrev) problems.push({
231
+ line: at,
232
+ message: "does not name the previous entry; a row was removed or reordered"
233
+ });
234
+ const { seq, prev, hash, sig: _sig,...record } = entry;
235
+ if (hashEntry(record, seq, prev) !== hash) problems.push({
236
+ line: at,
237
+ message: "contents do not match the sealed hash"
238
+ });
239
+ expectedPrev = entry.hash;
240
+ expectedSeq = entry.seq + 1;
241
+ }
242
+ return {
243
+ ok: problems.length === 0,
244
+ entries: count,
245
+ problems
246
+ };
247
+ }
248
+ /** The last complete line of a file, reading only its end when it can. */
249
+ function lastLine(path) {
250
+ const fd = openSync(path, "r");
251
+ try {
252
+ const size = fstatSync(fd).size;
253
+ for (let span = 64 * 1024;; span *= 4) {
254
+ const start = Math.max(0, size - span);
255
+ const buffer = Buffer.alloc(size - start);
256
+ readSync(fd, buffer, 0, buffer.length, start);
257
+ const lines = buffer.toString("utf8").split("\n").filter((line) => line.trim() !== "");
258
+ if (start === 0 || lines.length > 1) return lines.at(-1);
259
+ }
260
+ } finally {
261
+ closeSync(fd);
262
+ }
263
+ }
264
+ /** Where the chain ends now: the next seq and the hash to continue from. */
265
+ function tailOf(path) {
266
+ let tail;
267
+ try {
268
+ tail = lastLine(path);
269
+ } catch (error) {
270
+ if (error.code !== "ENOENT") throw error;
271
+ return {
272
+ seq: 0,
273
+ last: GENESIS
274
+ };
275
+ }
276
+ if (tail === void 0) return {
277
+ seq: 0,
278
+ last: GENESIS
279
+ };
280
+ let entry;
281
+ try {
282
+ entry = JSON.parse(tail);
283
+ } catch {
284
+ throw new Error(`prae ledger: last line of ${path} is not readable; refusing to append onto a chain that cannot be continued`);
285
+ }
286
+ return {
287
+ seq: entry.seq + 1,
288
+ last: entry.hash
289
+ };
290
+ }
291
+ const SLEEP = new Int32Array(new SharedArrayBuffer(4));
292
+ /** A lock older than this was left by a writer that died holding it. */
293
+ const STALE_LOCK_MS = 1e4;
294
+ /** Run `fn` holding an exclusive lock file; synchronous, like the append. */
295
+ function withLock(lock, fn) {
296
+ const deadline = Date.now() + 3e4;
297
+ for (;;) {
298
+ let fd;
299
+ try {
300
+ fd = openSync(lock, "wx");
301
+ } catch (error) {
302
+ if (error.code !== "EEXIST") throw error;
303
+ try {
304
+ if (Date.now() - statSync(lock).mtimeMs > STALE_LOCK_MS) {
305
+ unlinkSync(lock);
306
+ continue;
307
+ }
308
+ } catch {}
309
+ if (Date.now() > deadline) throw new Error(`prae ledger: ${lock} has been held for 30 s; refusing to append without it`);
310
+ Atomics.wait(SLEEP, 0, 0, 2);
311
+ continue;
312
+ }
313
+ try {
314
+ return fn();
315
+ } finally {
316
+ closeSync(fd);
317
+ try {
318
+ unlinkSync(lock);
319
+ } catch {}
320
+ }
321
+ }
322
+ }
323
+ var Ledger = class Ledger {
324
+ path;
325
+ constructor(path) {
326
+ this.path = path;
327
+ }
328
+ /**
329
+ * Open a ledger, reading the tail to continue an existing chain.
330
+ *
331
+ * A corrupt or truncated final line is a hard error rather than something to
332
+ * skip past: appending onto a chain whose end we could not read would bury
333
+ * the damage under valid-looking entries.
334
+ */
335
+ /** Sign every appended row with this Ed25519 private key (PEM). */
336
+ signWith;
337
+ /** Or through a signing boundary that holds the key (PRA-108). */
338
+ signer;
339
+ static open(path, options = {}) {
340
+ const ledger = Ledger.openUnsigned(path);
341
+ ledger.signWith = options.signWith;
342
+ ledger.signer = options.signer;
343
+ return ledger;
344
+ }
345
+ static openUnsigned(path) {
346
+ mkdirSync(dirname(path), { recursive: true });
347
+ try {
348
+ writeFileSync(path, "", { flag: "wx" });
349
+ } catch (error) {
350
+ if (error.code !== "EEXIST") throw error;
351
+ }
352
+ tailOf(path);
353
+ return new Ledger(path);
354
+ }
355
+ /** Append one decision and return the entry as written. */
356
+ append(record) {
357
+ return withLock(`${this.path}.lock`, () => {
358
+ const { seq, last } = tailOf(this.path);
359
+ const sealed = chain(record, seq, last);
360
+ const entry = this.signer !== void 0 ? {
361
+ ...sealed,
362
+ sig: this.signer(sealed)
363
+ } : this.signWith === void 0 ? sealed : {
364
+ ...sealed,
365
+ sig: signEntry(sealed, this.signWith)
366
+ };
367
+ appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
368
+ return entry;
369
+ });
370
+ }
371
+ /** Every entry, in order. */
372
+ read() {
373
+ return readEntries(readFileSync(this.path, "utf8"));
374
+ }
375
+ /**
376
+ * Re-derive every hash and confirm each entry names its predecessor.
377
+ *
378
+ * Catches a deleted row, an edited field, and a reordering. Does not catch a
379
+ * wholesale rewrite of the file by someone holding the same code — see the
380
+ * note in `entry.ts`.
381
+ */
382
+ verify() {
383
+ return verifyEntries(readFileSync(this.path, "utf8"));
384
+ }
385
+ };
386
+
387
+ //#endregion
388
+ //#region ../ledger/src/signer.ts
389
+ const nap = new Int32Array(new SharedArrayBuffer(4));
390
+
391
+ //#endregion
392
+ export { seal as _, signBytes as a, generateKeypair as c, verifyReceipt as d, verifySignature as f, hashEntry as g, chain as h, sealedKeypair as i, makeReceipt as l, canonical as m, readEntries as n, unsealPrivateKey as o, GENESIS as p, verifyEntries as r, fingerprint as s, Ledger as t, signEntry as u };
@@ -0,0 +1,3 @@
1
+ import { _ as seal, a as signBytes, c as generateKeypair, d as verifyReceipt, f as verifySignature, g as hashEntry, h as chain, i as sealedKeypair, l as makeReceipt, m as canonical, n as readEntries, o as unsealPrivateKey, p as GENESIS, r as verifyEntries, s as fingerprint, t as Ledger, u as signEntry } from "./src-D7g4lvaY.js";
2
+
3
+ export { GENESIS, Ledger, canonical, chain, fingerprint, generateKeypair, hashEntry, makeReceipt, readEntries, seal, sealedKeypair, signBytes, signEntry, unsealPrivateKey, verifyEntries, verifyReceipt, verifySignature };