@mnmal-ai/substrate 1.0.0-alpha.2 → 1.0.0-alpha.21

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.
Files changed (53) hide show
  1. package/README.md +64 -14
  2. package/dist/boot-store-Dz6PGwNY.js +4079 -0
  3. package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-BeVye_Oj.d.ts} +2 -87
  4. package/dist/cli-CH7M6ZTQ.js +3383 -0
  5. package/dist/client.browser.js +2485 -0
  6. package/dist/client.d.ts +273 -135
  7. package/dist/client.js +6 -6
  8. package/dist/cluster-worker.js +0 -1
  9. package/dist/{content-type-C7T28xNb.js → content-type-wLljot5M.js} +0 -1
  10. package/dist/{env-utils-CGNazUNt.js → env-utils-s25Z1YSA.js} +0 -1
  11. package/dist/{errors-D4vKuwz8.d.ts → errors-CoHLKAX0.d.ts} +44 -4
  12. package/dist/{fake-DUVtKVSE.js → fake-DdXtb-m8.js} +0 -1
  13. package/dist/{index-D7mSOFlM.d.ts → index-D7XRAGC6.d.ts} +7 -11
  14. package/dist/msgpackr-Dq18g6Ds.js +16 -0
  15. package/dist/node-version-BtK_Nq6z.js +32 -0
  16. package/dist/pack.d.ts +75 -11
  17. package/dist/pack.js +4 -4
  18. package/dist/pg-edges-store-Dnaxesmy.js +443 -0
  19. package/dist/{plugin-QuJN9pG_.js → plugin-BIz4Pr5-.js} +132 -8
  20. package/dist/proposals-bootstrap.js +6 -5
  21. package/dist/proposals.config.schema.json +5 -0
  22. package/dist/proposals.d.ts +17 -5
  23. package/dist/proposals.default-config.json +2 -1
  24. package/dist/proposals.js +2 -3
  25. package/dist/recall-bootstrap.js +5 -4
  26. package/dist/recall.config.schema.json +6 -0
  27. package/dist/recall.d.ts +35 -6
  28. package/dist/recall.js +2 -3
  29. package/dist/{repl-C52wyfMs.js → repl-BUkd9DPZ.js} +65 -33
  30. package/dist/{row-ByLFE2Wx.d.ts → row-aEWVHEsf.d.ts} +92 -12
  31. package/dist/run-Cu9w5Y10.js +2435 -0
  32. package/dist/{plugin-t2g2wX0b.d.ts → schema-DwnXxdjk.d.ts} +1293 -63
  33. package/dist/script-A9dxMRZA.js +143 -0
  34. package/dist/script-runner.js +77 -0
  35. package/dist/sdk.d.ts +227 -38
  36. package/dist/sdk.js +5 -110
  37. package/dist/semver-D_zdq0hi.js +17 -0
  38. package/dist/{src-DWm0iA88.js → src--accZ5Ka.js} +188 -87
  39. package/dist/{src-DMzc3HfW.js → src-BNdhH_Hx.js} +745 -851
  40. package/dist/{src-CG7giuHr.js → src-BQnDrs_E.js} +793 -75
  41. package/dist/{src-BLgbLq2k.js → src-B_kHkbsr.js} +780 -330
  42. package/dist/src-BbCUeMsI.js +7723 -0
  43. package/dist/{src-CHp3QyqB.js → src-BmJD4ScT.js} +9215 -3376
  44. package/dist/{row-DZ0Fnpc6.js → src-DmiUWOLp.js} +2 -1
  45. package/dist/substrate-admin.js +17 -782
  46. package/dist/substrate.js +4 -5487
  47. package/dist/testing.d.ts +730 -53
  48. package/dist/testing.js +20 -163
  49. package/dist/{ws-C72iVS5T.d.ts → ws-DJaKruX-.d.ts} +4 -5
  50. package/package.json +26 -26
  51. package/dist/dataset-BQ8egGl5.js +0 -1535
  52. package/dist/schema-g4FQLr0V.d.ts +0 -433
  53. package/dist/src-CXKnqeTW.js +0 -2339
@@ -1,768 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
3
- import { d as buildAuditRow, f as AUDIT_EVENT_TYPE } from "./src-CHp3QyqB.js";
4
- import { d as resolveDefaultKidPath, u as resolveDefaultKeyPath } from "./env-utils-CGNazUNt.js";
5
- import { E as describeGrant, I as decodeList, L as encodeList, M as grantEntryError, g as checkUpdatable, h as checkRevocable, y as newlyGranted } from "./row-DZ0Fnpc6.js";
6
- import { S as reconcileIdentities } from "./src-DMzc3HfW.js";
7
- import { A as describeAdminTarget, B as version, C as CLI_ACTOR_KID, D as listActiveAdminKeys, E as generateAdminKeypair, F as RESTART_NOTE, I as USAGE, L as argvError, M as resolveAdminTarget, N as ARGV_SPEC, O as readEd25519PublicKey, P as validateArgv, S as BootstrapError, T as forUpdate, _ as REVOKE_EXIT_CODES, a as formatRegisterOutput, b as runKeyPatchViaRoute, c as runRegisterViaRoute, d as formatDoctorReport, f as runDoctor, g as bootstrapKidPath, h as runBootstrap, i as runOnboard, j as resolveAdminAuth, k as readKeyById, l as grantLines, m as parseBootstrapArgs, n as formatChecklist, o as parseRegisterArgs, p as formatBootstrapOutput, r as onboardCommand, s as runRegister, t as openPgDataset, u as doctorCommand, v as UPDATE_EXIT_CODES, w as base64Url, x as ACTOR_HINT, y as runKeyListViaRoute, z as AdminCliError } from "./dataset-BQ8egGl5.js";
8
- import { existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
9
- import { dirname } from "node:path";
10
- import { createHash, randomUUID } from "node:crypto";
2
+ import { t as assertNodeVersion } from "./node-version-BtK_Nq6z.js";
3
+ import { realpathSync } from "node:fs";
11
4
  import { pathToFileURL } from "node:url";
12
- import { createInterface } from "node:readline";
13
5
 
14
- //#region src/admin/commands/list.ts
6
+ //#region src/admin/entrypoint.ts
15
7
  /**
16
- * `list` — print the active Key rows.
17
- *
18
- * Without `--url`: read-only, direct-to-postgres, and it DOES NOT
19
- * AUTHENTICATE, so an admin row here is no evidence admin auth works — that is
20
- * `doctor`'s question. With `--url`: an authenticated read through the server.
21
- */
22
- /**
23
- * Parse `list`'s arguments. Returns the `--url` base when one was given.
24
- */
25
- function parseListArgs(argv) {
26
- try {
27
- return parseListArgsInner(argv);
28
- } catch (err) {
29
- if (err instanceof AdminCliError) throw argvError("list", err.message, err.exitCode);
30
- throw err;
31
- }
32
- }
33
- function parseListArgsInner(argv) {
34
- validateArgv("list", argv);
35
- const out = {};
36
- for (let i = 0; i < argv.length; i++) {
37
- const tok = argv[i] ?? "";
38
- if (tok === "--url") {
39
- const value = argv[i + 1];
40
- if (value === void 0 || value.startsWith("-")) throw new AdminCliError("list: --url requires a base URL, e.g. --url https://host:3100", 1);
41
- out.url = value;
42
- i += 1;
43
- continue;
44
- }
45
- if (tok.startsWith("--url=")) {
46
- const value = tok.slice(6);
47
- if (value === "") throw new AdminCliError("list: --url requires a base URL, e.g. --url https://host:3100", 1);
48
- out.url = value;
49
- }
50
- }
51
- return out;
52
- }
53
- async function runList(env, openDataset = openPgDataset) {
54
- const { dataset, close } = await openDataset(env);
55
- try {
56
- const { rows } = await dataset.read("Key", { where: { revokedAt: { eq: null } } });
57
- const out = [];
58
- for (const row of rows) {
59
- const kid = typeof row.kid === "string" ? row.kid : "";
60
- if (kid.length === 0) continue;
61
- if (row.revokedAt != null) continue;
62
- const createdAt = row._metadata?.createdAt ?? "";
63
- out.push({
64
- kid,
65
- name: typeof row.name === "string" ? row.name : "",
66
- capabilities: typeof row.capabilities === "string" ? row.capabilities : "",
67
- namespaces: typeof row.namespaces === "string" ? row.namespaces : "",
68
- createdAt
69
- });
70
- }
71
- return out;
72
- } finally {
73
- await close();
74
- }
75
- }
76
- /**
77
- * Provenance line, printed with every result including the empty one, so an
78
- * unauthenticated direct read is not mistaken for proof that admin auth works
79
- * — or, when empty, for proof that the right store is empty.
80
- */
81
- const PROVENANCE = "read directly from SUBSTRATE_DATABASE_URL — NOT authenticated, and not a check that any credential works.\nTo ask a running server whether admin auth actually works: substrate-admin doctor --url <base>\n";
82
- function formatListOutput(rows) {
83
- if (rows.length === 0) return `no active Key rows\n${PROVENANCE}`;
84
- return `${formatTable(rows)}${PROVENANCE}`;
85
- }
86
- /** The aligned table, shared by both modes so they cannot drift apart. */
87
- function formatTable(rows) {
88
- const header = {
89
- kid: "kid",
90
- name: "name",
91
- capabilities: "capabilities",
92
- namespaces: "namespaces",
93
- createdAt: "createdAt"
94
- };
95
- const all = [header, ...rows];
96
- const widths = {
97
- kid: Math.max(...all.map((r) => r.kid.length)),
98
- name: Math.max(...all.map((r) => r.name.length)),
99
- capabilities: Math.max(...all.map((r) => r.capabilities.length)),
100
- namespaces: Math.max(...all.map((r) => r.namespaces.length)),
101
- createdAt: Math.max(...all.map((r) => r.createdAt.length))
102
- };
103
- const pad = (s, w) => s + " ".repeat(Math.max(0, w - s.length));
104
- const divider = [
105
- "-".repeat(widths.kid),
106
- "-".repeat(widths.name),
107
- "-".repeat(widths.capabilities),
108
- "-".repeat(widths.namespaces),
109
- "-".repeat(widths.createdAt)
110
- ].join(" ");
111
- const lines = [[
112
- pad(header.kid, widths.kid),
113
- pad(header.name, widths.name),
114
- pad(header.capabilities, widths.capabilities),
115
- pad(header.namespaces, widths.namespaces),
116
- pad(header.createdAt, widths.createdAt)
117
- ].join(" "), divider];
118
- for (const r of rows) lines.push([
119
- pad(r.kid, widths.kid),
120
- pad(r.name, widths.name),
121
- pad(r.capabilities, widths.capabilities),
122
- pad(r.namespaces, widths.namespaces),
123
- pad(r.createdAt, widths.createdAt)
124
- ].join(" "));
125
- return `${lines.join("\n")}\n`;
126
- }
127
- /**
128
- * Render the AUTHENTICATED read, naming the target and stating that the
129
- * server verified the credential before answering.
130
- */
131
- function formatRemoteListOutput(rows, baseUrl) {
132
- const mapped = rows.map((r) => ({
133
- kid: typeof r.kid === "string" ? r.kid : "",
134
- name: typeof r.name === "string" ? r.name : "",
135
- capabilities: typeof r.capabilities === "string" ? r.capabilities : "",
136
- namespaces: typeof r.namespaces === "string" ? r.namespaces : "",
137
- createdAt: typeof r.createdAt === "string" ? r.createdAt : ""
138
- }));
139
- const provenance = `read from ${baseUrl} over the admin-gated route — AUTHENTICATED, and the server accepted this credential.\n`;
140
- if (mapped.length === 0) return `no active Key rows\n${provenance}`;
141
- return `${formatTable(mapped)}${provenance}`;
142
- }
143
-
144
- //#endregion
145
- //#region src/admin/commands/revoke.ts
146
- /**
147
- * `revoke` — soft-delete a Key by stamping `revokedAt`.
148
- *
149
- * Refuses the last active admin. `checkRevocable` is shared with the route so
150
- * both transports enforce the same floor.
151
- */
152
- async function runRevoke(kid, env, openDataset = openPgDataset) {
153
- if (kid === void 0 || kid.length === 0) throw argvError("revoke", "revoke requires a <kid> positional arg");
154
- const adminCapability = env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? env.SUBSTRATE_ADMIN_CAPABILITY : "admin";
155
- const { dataset, close } = await openDataset(env);
156
- try {
157
- return await dataset.withTransaction(async (tx) => {
158
- const existing = await readKeyById(tx, kid);
159
- const refusal = checkRevocable({
160
- kid,
161
- exists: existing !== null,
162
- existingRevokedAt: existing?.revokedAt,
163
- activeAdminKids: (await listActiveAdminKeys(tx, adminCapability)).map((a) => a.kid)
164
- });
165
- if (refusal !== null) throw new AdminCliError(refusal.message, REVOKE_EXIT_CODES[refusal.code]);
166
- const now = /* @__PURE__ */ new Date();
167
- const mergedRow = forUpdate({
168
- ...existing.row,
169
- revokedAt: now
170
- });
171
- await tx.write("Key", [mergedRow], ACTOR_HINT);
172
- await tx.write(AUDIT_EVENT_TYPE, [buildAuditRow({
173
- actorKid: CLI_ACTOR_KID,
174
- kind: "key_revoked",
175
- targetKid: kid,
176
- details: {
177
- revokedAt: now.toISOString(),
178
- cliSubcommand: "revoke"
179
- },
180
- now
181
- })], ACTOR_HINT);
182
- return {
183
- kid,
184
- revokedAt: now.toISOString()
185
- };
186
- });
187
- } finally {
188
- await close();
189
- }
190
- }
191
- function formatRevokeOutput(result) {
192
- return [
193
- `Key ${result.kid} revoked at ${result.revokedAt}`,
194
- "",
195
- RESTART_NOTE,
196
- ""
197
- ].join("\n");
198
- }
199
-
200
- //#endregion
201
- //#region src/admin/commands/rotate.ts
202
- /**
203
- * `rotate` — mint a fresh keypair for an existing kid and retire the old row,
204
- * in one transaction.
205
- *
206
- * `--out` is required and must not already exist. An admin tool that silently
207
- * clobbers an operator's private key destroys the only copy of a credential.
208
- */
209
- function parseRotateArgs(argv) {
210
- try {
211
- return parseRotateArgsInner(argv);
212
- } catch (err) {
213
- if (err instanceof AdminCliError) throw argvError("rotate", err.message, err.exitCode);
214
- throw err;
215
- }
216
- }
217
- function parseRotateArgsInner(argv) {
218
- const rest = argv.slice(1);
219
- validateArgv("rotate", rest);
220
- let kid;
221
- let outPath;
222
- let wantsEncrypt = false;
223
- for (let i = 0; i < rest.length; i++) {
224
- const tok = rest[i];
225
- if (tok === void 0) continue;
226
- if (tok === "--out") {
227
- if (outPath !== void 0) throw new AdminCliError("rotate: --out specified more than once", 1);
228
- const val = rest[i + 1];
229
- if (val === void 0 || val.length === 0 || val.startsWith("--")) throw new AdminCliError("rotate: --out requires a path argument", 1);
230
- outPath = val;
231
- i += 1;
232
- } else if (tok === "--encrypt") {
233
- if (wantsEncrypt) throw new AdminCliError("rotate: --encrypt specified more than once", 1);
234
- wantsEncrypt = true;
235
- } else kid = tok;
236
- }
237
- if (kid === void 0 || kid.length === 0) throw new AdminCliError("rotate requires a <kid> positional arg", 1);
238
- if (outPath === void 0 || outPath.length === 0) throw new AdminCliError("rotate requires --out <path>", 1);
239
- return {
240
- kid,
241
- outPath,
242
- wantsEncrypt
243
- };
244
- }
245
- async function runRotate(kid, outPath, env, wantsEncrypt = false, openDataset = openPgDataset) {
246
- if (kid === void 0 || kid.length === 0) throw new AdminCliError("rotate requires a <kid> positional arg");
247
- if (outPath === void 0 || outPath.length === 0) throw new AdminCliError("rotate requires --out <path>");
248
- if (existsSync(outPath)) throw new AdminCliError(`--out path already exists: ${outPath} (move it aside and retry)`, 2);
249
- const { publicKeyPem, privateKeyPem, encrypted } = generateAdminKeypair(env, wantsEncrypt);
250
- try {
251
- mkdirSync(dirname(outPath), {
252
- recursive: true,
253
- mode: 448
254
- });
255
- writeFileSync(outPath, privateKeyPem, {
256
- mode: 384,
257
- flag: "wx"
258
- });
259
- } catch (err) {
260
- const msg = err instanceof Error ? err.message : String(err);
261
- throw new AdminCliError(`failed to write private key to '${outPath}': ${msg}. Nothing was changed.`, 5);
262
- }
263
- let committed = false;
264
- const { dataset, close } = await openDataset(env).catch((err) => {
265
- rmSync(outPath, { force: true });
266
- throw err;
267
- });
268
- try {
269
- const newKid = randomUUID();
270
- const shaFull = createHash("sha256").update(publicKeyPem).digest();
271
- const fingerprint = `sha256:${base64Url(shaFull).slice(0, 8)}`;
272
- const { name, namespaces, capabilities } = await dataset.withTransaction(async (tx) => {
273
- const existing = await readKeyById(tx, kid);
274
- if (existing === null) throw new AdminCliError(`no Key with kid ${kid}`, 3);
275
- if (existing.revokedAt != null) throw new AdminCliError(`cannot rotate revoked Key ${kid}`, 4);
276
- const preservedName = typeof existing.row.name === "string" ? existing.row.name : "";
277
- const preservedAlgorithm = typeof existing.row.algorithm === "string" ? existing.row.algorithm : "EdDSA";
278
- if (preservedAlgorithm !== "EdDSA") throw new AdminCliError(`cannot rotate Key with algorithm '${preservedAlgorithm}' — only EdDSA is currently supported by the CLI`, 5);
279
- const preservedNamespaces = typeof existing.row.namespaces === "string" ? existing.row.namespaces : "";
280
- const preservedCapabilities = typeof existing.row.capabilities === "string" ? existing.row.capabilities : "";
281
- const preservedKid = existing.row.kid;
282
- const now = /* @__PURE__ */ new Date();
283
- await tx.write("Key", [forUpdate({
284
- ...existing.row,
285
- revokedAt: now
286
- })], ACTOR_HINT);
287
- await tx.write("Key", [{
288
- id: newKid,
289
- kid: preservedKid,
290
- name: preservedName,
291
- algorithm: preservedAlgorithm,
292
- publicKey: publicKeyPem,
293
- namespaces: preservedNamespaces,
294
- capabilities: preservedCapabilities,
295
- revokedAt: null
296
- }], ACTOR_HINT);
297
- await tx.write(AUDIT_EVENT_TYPE, [buildAuditRow({
298
- actorKid: CLI_ACTOR_KID,
299
- kind: "key_rotated",
300
- targetKid: kid,
301
- details: {
302
- oldKid: kid,
303
- newKid,
304
- name: preservedName
305
- },
306
- now
307
- })], ACTOR_HINT);
308
- return {
309
- name: preservedName,
310
- namespaces: preservedNamespaces,
311
- capabilities: preservedCapabilities
312
- };
313
- });
314
- committed = true;
315
- return {
316
- oldKid: kid,
317
- newKid,
318
- fingerprint,
319
- privateKeyPath: outPath,
320
- name,
321
- namespaces,
322
- capabilities,
323
- encrypted
324
- };
325
- } finally {
326
- if (!committed) rmSync(outPath, { force: true });
327
- await close();
328
- }
329
- }
330
- function formatRotateOutput(result) {
331
- const encLabel = result.encrypted ? "encrypted: aes-256-cbc+pbes2" : "unencrypted";
332
- return [
333
- "substrate-admin rotate complete.",
334
- `old kid: ${result.oldKid}`,
335
- `new kid: ${result.newKid}`,
336
- `fingerprint: ${result.fingerprint}`,
337
- `private key: ${result.privateKeyPath} (mode 0600, ${encLabel})`,
338
- `namespaces: ${result.namespaces}`,
339
- `capabilities: ${result.capabilities}`,
340
- "",
341
- `Use the new private key to sign JWTs with kid=${result.newKid} to authenticate. The old key is revoked and no longer valid.`,
342
- "",
343
- RESTART_NOTE,
344
- ""
345
- ].join("\n");
346
- }
347
-
348
- //#endregion
349
- //#region src/admin/commands/update.ts
350
- /**
351
- * `update` — change a live key's grant in place, leaving the keypair alone.
352
- *
353
- * An omitted flag leaves that field unchanged; `--ns` REPLACES rather than
354
- * merges. Widening authority needs `--widen`, narrowing does not, and the audit
355
- * event carries before AND after so a grant change is reconstructable from the
356
- * trail rather than from whoever remembers running it.
357
- */
358
- /**
359
- * Parse `update <kid> [--ns <csv>] [--caps <csv>] [--name <n>] [--widen]
360
- * [--allow-admin]`.
361
- *
362
- * Unlike `parseRegisterArgs`, an omitted flag means LEAVE UNCHANGED: the
363
- * defaulting `register` does at parse time (caps → read,mutate, name → kid)
364
- * is deliberately not repeated, so `update <kid> --name foo` cannot change
365
- * the grant.
366
- */
367
- function parseUpdateArgs(argv) {
368
- try {
369
- return parseUpdateArgsInner(argv);
370
- } catch (err) {
371
- if (err instanceof AdminCliError) throw argvError("update", err.message, err.exitCode);
372
- throw err;
373
- }
374
- }
375
- function parseUpdateArgsInner(argv) {
376
- const rest = argv.slice(1);
377
- validateArgv("update", rest);
378
- let kid;
379
- let name;
380
- let nsCsv;
381
- let capsCsv;
382
- let widen = false;
383
- let allowAdmin = false;
384
- let allowUnknownNs = false;
385
- let url = null;
386
- const takeValue = (flag, i) => {
387
- const val = rest[i + 1];
388
- if (val === void 0 || val.length === 0 || val.startsWith("--")) throw new AdminCliError(`update: ${flag} requires a value`, 1);
389
- return val;
390
- };
391
- for (let i = 0; i < rest.length; i++) {
392
- const tok = rest[i];
393
- if (tok === void 0) continue;
394
- if (tok === "--name") {
395
- if (name !== void 0) throw new AdminCliError("update: --name specified more than once", 1);
396
- name = takeValue("--name", i);
397
- i += 1;
398
- } else if (tok === "--ns") {
399
- if (nsCsv !== void 0) throw new AdminCliError("update: --ns specified more than once", 1);
400
- nsCsv = takeValue("--ns", i);
401
- i += 1;
402
- } else if (tok === "--caps") {
403
- if (capsCsv !== void 0) throw new AdminCliError("update: --caps specified more than once", 1);
404
- capsCsv = takeValue("--caps", i);
405
- i += 1;
406
- } else if (tok === "--url") {
407
- if (url === "") throw new AdminCliError("update: --direct and --url are mutually exclusive", 1);
408
- if (url !== null) throw new AdminCliError("update: --url specified more than once", 1);
409
- url = takeValue("--url", i);
410
- i += 1;
411
- } else if (tok === "--direct") {
412
- if (url !== null && url !== "") throw new AdminCliError("update: --direct and --url are mutually exclusive", 1);
413
- url = "";
414
- } else if (tok === "--allow-unknown-ns") allowUnknownNs = true;
415
- else if (tok === "--widen") {
416
- if (widen) throw new AdminCliError("update: --widen specified more than once", 1);
417
- widen = true;
418
- } else if (tok === "--allow-admin") {
419
- if (allowAdmin) throw new AdminCliError("update: --allow-admin specified more than once", 1);
420
- allowAdmin = true;
421
- } else kid = tok;
422
- }
423
- if (kid === void 0 || kid.length === 0) throw new AdminCliError("update requires a <kid> positional arg", 1);
424
- const splitCsv = (csv) => csv.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
425
- const namespaces = nsCsv === void 0 ? void 0 : splitCsv(nsCsv);
426
- if (namespaces !== void 0) {
427
- const nsError = grantEntryError(namespaces, ["read", "mutate"]);
428
- if (nsError !== null) throw new AdminCliError(`update: ${nsError} — e.g. --ns inventory:read,notes:read+mutate`, 1);
429
- }
430
- return {
431
- kid,
432
- name,
433
- namespaces,
434
- capabilities: capsCsv === void 0 ? void 0 : splitCsv(capsCsv),
435
- widen,
436
- allowAdmin,
437
- allowUnknownNs,
438
- url
439
- };
440
- }
441
- /**
442
- * NOTE on `--allow-unknown-ns`: the unhosted-namespace check is ROUTE-SIDE
443
- * only, because it needs the engine's federated schema. A `--direct` update
444
- * can still write a grant naming a namespace nobody hosts.
445
- */
446
- async function runUpdate(args, env, openDataset = openPgDataset) {
447
- if (args.name === void 0 && args.namespaces === void 0 && args.capabilities === void 0) throw new AdminCliError("update requires at least one of --ns, --caps or --name — there is nothing to change", 1);
448
- const adminCapability = env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? env.SUBSTRATE_ADMIN_CAPABILITY : "admin";
449
- const { dataset, close } = await openDataset(env);
450
- try {
451
- return await dataset.withTransaction(async (tx) => {
452
- const existing = await readKeyById(tx, args.kid);
453
- const prevNs = decodeList(existing?.row.namespaces);
454
- const prevCaps = decodeList(existing?.row.capabilities);
455
- const prevName = typeof existing?.row.name === "string" ? existing.row.name : "";
456
- const nextNs = args.namespaces ?? prevNs;
457
- const nextCaps = args.capabilities ?? prevCaps;
458
- const nextName = args.name ?? prevName;
459
- const refusal = checkUpdatable({
460
- kid: args.kid,
461
- exists: existing !== null,
462
- existingRevokedAt: existing?.revokedAt,
463
- prevNamespaces: prevNs,
464
- prevCapabilities: prevCaps,
465
- nextNamespaces: nextNs,
466
- nextCapabilities: nextCaps,
467
- activeAdminKids: (await listActiveAdminKeys(tx, adminCapability)).map((a) => a.kid),
468
- adminCapability,
469
- widen: args.widen === true,
470
- allowAdmin: args.allowAdmin === true
471
- });
472
- if (refusal !== null) {
473
- const suffix = refusal.code === "requires_widen" ? " Pass --widen to confirm it is deliberate. Narrowing a grant needs no flag." : refusal.code === "requires_allow_admin" ? "" : "";
474
- const message = refusal.code === "requires_allow_admin" ? "update: granting the 'admin' capability requires --allow-admin" : `${refusal.message}${suffix}`;
475
- throw new AdminCliError(message, UPDATE_EXIT_CODES[refusal.code]);
476
- }
477
- const nsGranted = newlyGranted(prevNs, nextNs);
478
- const capsGranted = newlyGranted(prevCaps, nextCaps);
479
- const before = {
480
- name: prevName,
481
- namespaces: encodeList(prevNs),
482
- capabilities: encodeList(prevCaps)
483
- };
484
- const after = {
485
- name: nextName,
486
- namespaces: encodeList(nextNs),
487
- capabilities: encodeList(nextCaps)
488
- };
489
- if (!(after.name !== before.name || after.namespaces !== before.namespaces || after.capabilities !== before.capabilities)) return {
490
- kid: args.kid,
491
- before,
492
- after,
493
- changed: false
494
- };
495
- const now = /* @__PURE__ */ new Date();
496
- await tx.write("Key", [forUpdate({
497
- ...existing.row,
498
- name: after.name,
499
- namespaces: after.namespaces,
500
- capabilities: after.capabilities
501
- })], ACTOR_HINT);
502
- await tx.write(AUDIT_EVENT_TYPE, [buildAuditRow({
503
- actorKid: CLI_ACTOR_KID,
504
- kind: "key_authority_updated",
505
- targetKid: args.kid,
506
- details: {
507
- before,
508
- after,
509
- namespacesGranted: nsGranted,
510
- capabilitiesGranted: capsGranted,
511
- widened: nsGranted.length > 0 || capsGranted.length > 0,
512
- cliSubcommand: "update"
513
- },
514
- now
515
- })], ACTOR_HINT);
516
- return {
517
- kid: args.kid,
518
- before,
519
- after,
520
- changed: true
521
- };
522
- });
523
- } finally {
524
- await close();
525
- }
526
- }
527
- function formatUpdateOutput(result) {
528
- if (!result.changed) return [
529
- `substrate-admin update: no change — ${result.kid} already carries this authority.`,
530
- `name: ${result.before.name}`,
531
- ...grantLines("grant: ", result.before.namespaces, result.before.capabilities),
532
- ` (stored as: namespaces='${result.before.namespaces}' capabilities='${result.before.capabilities}')`,
533
- "",
534
- "Nothing was written and no audit row was emitted.",
535
- ""
536
- ].join("\n");
537
- const row = (label, b, a) => b === a ? `${label}${b === "" ? "(empty)" : b} (unchanged)` : `${label}${b} -> ${a}`;
538
- const beforeGrant = grantLines("grant before: ", result.before.namespaces, result.before.capabilities);
539
- const afterGrant = grantLines(" after: ", result.after.namespaces, result.after.capabilities);
540
- return [
541
- "substrate-admin update complete.",
542
- `kid: ${result.kid}`,
543
- row("name: ", result.before.name, result.after.name),
544
- ...beforeGrant,
545
- ...afterGrant,
546
- ` (stored as: namespaces='${result.after.namespaces}' capabilities='${result.after.capabilities}')`,
547
- "",
548
- RESTART_NOTE,
549
- ""
550
- ].join("\n");
551
- }
552
-
553
- //#endregion
554
- //#region src/admin/main.ts
555
- /**
556
- * Argv -> subcommand dispatch.
557
- *
558
- * Every case here is thin on purpose: parse, resolve the target, call the
559
- * command module, format. The logic lives in `./commands/`, so this file stays
560
- * readable as the map of what the CLI can do.
561
- */
562
- /**
563
- * CLI entry point. Parses `process.argv`, dispatches to the requested
564
- * sub-command, and writes human-readable output. Returns the exit code so the
565
- * top-level runner can call `process.exit` once.
566
- */
567
- async function main(argv, env, out, errOut, openDataset = openPgDataset, prompt = {
568
- ask: async () => null,
569
- interactive: false
570
- }) {
571
- const command = argv[0];
572
- if (command === void 0) {
573
- errOut(`${USAGE}\n`);
574
- return 1;
575
- }
576
- if (command === "--version" || command === "-v" || command === "version") {
577
- out(`${version}\n`);
578
- return 0;
579
- }
580
- if (command === "help" || argv.some((a) => a === "--help" || a === "-h")) {
581
- out(`${USAGE}\n`);
582
- return 0;
583
- }
584
- try {
585
- if (ARGV_SPEC[command] === void 0) {
586
- errOut(`unknown command: ${command}\n${USAGE}\n`);
587
- return 1;
588
- }
589
- validateArgv(command, argv.slice(1));
590
- switch (command) {
591
- case "bootstrap": {
592
- const parsed = parseBootstrapArgs(argv);
593
- const result = await runBootstrap(env, parsed.wantsEncrypt);
594
- out(formatBootstrapOutput(result));
595
- return 0;
596
- }
597
- case "doctor": {
598
- const report = await doctorCommand(argv.slice(1), env);
599
- out(formatDoctorReport(report));
600
- return report.exitCode;
601
- }
602
- case "onboard": return onboardCommand(argv.slice(1), env, {
603
- out,
604
- ask: prompt.ask
605
- }, prompt.interactive);
606
- case "list": {
607
- const args = parseListArgs(argv.slice(1));
608
- if (args.url !== void 0) {
609
- const remote = await runKeyListViaRoute(args.url, env);
610
- out(formatRemoteListOutput(remote, args.url));
611
- return 0;
612
- }
613
- const rows = await runList(env, openDataset);
614
- out(formatListOutput(rows));
615
- return 0;
616
- }
617
- case "revoke": {
618
- const rest = argv.slice(1);
619
- let kid;
620
- let url;
621
- let direct = false;
622
- for (let i = 0; i < rest.length; i++) {
623
- const tok = rest[i];
624
- if (tok === void 0) continue;
625
- if (tok === "--url") {
626
- if (url !== void 0) throw argvError("revoke", "revoke: --url specified more than once", 1);
627
- url = rest[i + 1] ?? "";
628
- i += 1;
629
- continue;
630
- }
631
- if (tok === "--direct") {
632
- direct = true;
633
- continue;
634
- }
635
- kid = tok;
636
- }
637
- if (kid === void 0 || kid.length === 0) {
638
- errOut(`revoke requires a <kid> positional arg\n${USAGE}\n`);
639
- return 1;
640
- }
641
- if (direct && url !== void 0) throw argvError("revoke", "revoke: --direct and --url are mutually exclusive", 1);
642
- const target = resolveAdminTarget(direct ? "" : url ?? null, env);
643
- errOut(`${describeAdminTarget("revoke", target)}\n`);
644
- if (target.kind === "route") {
645
- const payload = await runKeyPatchViaRoute({
646
- kid,
647
- revoke: true
648
- }, target.baseUrl, env, REVOKE_EXIT_CODES);
649
- out(`Key ${String(payload.kid)} revoked at ${String(payload.revokedAt)} — the running server saw it.
650
- `);
651
- return 0;
652
- }
653
- const result = await runRevoke(kid, env, openDataset);
654
- out(formatRevokeOutput(result));
655
- return 0;
656
- }
657
- case "rotate": {
658
- const parsed = parseRotateArgs(argv);
659
- const result = await runRotate(parsed.kid, parsed.outPath, env, parsed.wantsEncrypt, openDataset);
660
- out(formatRotateOutput(result));
661
- return 0;
662
- }
663
- case "register": {
664
- const parsed = parseRegisterArgs(argv);
665
- const target = resolveAdminTarget(parsed.url, env);
666
- errOut(`${describeAdminTarget("register", target)}\n`);
667
- const result = target.kind === "route" ? await runRegisterViaRoute(parsed, target.baseUrl, env) : await runRegister(parsed, env, openDataset);
668
- out(formatRegisterOutput(result));
669
- return 0;
670
- }
671
- case "update": {
672
- const parsed = parseUpdateArgs(argv);
673
- const target = resolveAdminTarget(parsed.url, env);
674
- errOut(`${describeAdminTarget("update", target)}\n`);
675
- if (target.kind === "route") {
676
- const payload = await runKeyPatchViaRoute({
677
- kid: parsed.kid,
678
- ...parsed.name !== void 0 ? { name: parsed.name } : {},
679
- ...parsed.namespaces !== void 0 ? { namespaces: parsed.namespaces } : {},
680
- ...parsed.capabilities !== void 0 ? { capabilities: parsed.capabilities } : {},
681
- widen: parsed.widen === true,
682
- allowAdmin: parsed.allowAdmin === true,
683
- allowUnknownNs: parsed.allowUnknownNs
684
- }, target.baseUrl, env, UPDATE_EXIT_CODES);
685
- out(`Key ${String(payload.kid)} updated via the route — the running server saw it.\n`);
686
- return 0;
687
- }
688
- const result = await runUpdate(parsed, env, openDataset);
689
- out(formatUpdateOutput(result));
690
- return 0;
691
- }
692
- default:
693
- errOut(`unknown command: ${command}\n${USAGE}\n`);
694
- return 1;
695
- }
696
- } catch (err) {
697
- const exitCode = err instanceof BootstrapError || err instanceof AdminCliError ? err.exitCode : 1;
698
- errOut(`${err instanceof Error ? err.message : String(err)}\n`);
699
- return exitCode;
700
- }
701
- }
702
-
703
- //#endregion
704
- //#region src/admin/stdin-ask.ts
705
- /**
706
- * The line reader behind an interactive `substrate-admin onboard`.
707
- *
708
- * - End of input (Ctrl-D, a closed pipe) resolves the open question, and every later
709
- * one, with null — the loop turns that into a quit with its summary.
710
- * - Ctrl-C at a prompt does the same. Ctrl-C with no prompt open (an action or a fetch in
711
- * flight) calls `onInterrupt`, because no prompt will come back to notice a close.
712
- * - `terminal` is set from the INPUT, so redirecting stderr cannot turn Ctrl-C back into
713
- * a process-killing SIGINT.
714
- * - One pending resolver and one permanent close listener, so nothing accumulates per
715
- * question.
716
- */
717
- function createAsk(streams) {
718
- const rl = createInterface({
719
- input: streams.input,
720
- output: streams.output,
721
- terminal: streams.terminal
722
- });
723
- let closed = false;
724
- let pending = null;
725
- const settle = (line) => {
726
- const resolve = pending;
727
- pending = null;
728
- resolve?.(line);
729
- };
730
- rl.on("close", () => {
731
- closed = true;
732
- settle(null);
733
- });
734
- rl.on("SIGINT", () => {
735
- if (pending !== null) rl.close();
736
- else streams.onInterrupt();
737
- });
738
- return (prompt) => {
739
- if (closed) return Promise.resolve(null);
740
- return new Promise((resolve) => {
741
- pending = resolve;
742
- rl.question(prompt, (line) => settle(line));
743
- });
744
- };
745
- }
746
-
747
- //#endregion
748
- //#region src/bin/admin.ts
749
- /**
750
- * `substrate-admin` — admin CLI entrypoint (§5.12). This file is the ENTRYPOINT
751
- * and nothing else; the parts live under `../admin/`:
752
- *
753
- * env.ts which files hold the admin identity
754
- * identity.ts which store a write lands in, and which key signs it
755
- * keys.ts Key row plumbing, keypair minting, admin classification
756
- * route.ts driving PATCH /substrate/v1/_system/keys, refusal -> exit codes
757
- * usage.ts the help text
758
- * main.ts argv -> subcommand dispatch
759
- * commands/* one module per subcommand
760
- *
761
- * The public surface is re-exported below for tests, tooling and
762
- * `substrate federate enroll`.
763
- */
764
- /**
765
- * Is this module the process entrypoint?
8
+ * Is the module at `moduleUrl` the process entrypoint?
766
9
  *
767
10
  * Compares REALPATHS. Node resolves symlinks when it builds `import.meta.url`
768
11
  * but `process.argv[1]` is whatever the caller typed, so a naive comparison is
@@ -782,27 +25,19 @@ function isEntrypointPath(moduleUrl, argv1) {
782
25
  return false;
783
26
  }
784
27
  }
785
- function isEntrypoint() {
786
- return isEntrypointPath(import.meta.url, process.argv[1]);
787
- }
788
- if (isEntrypoint()) {
789
- const interactive = process.stdin.isTTY === true && process.argv[2] === "onboard";
790
- main(process.argv.slice(2), process.env, (s) => process.stdout.write(s), (s) => process.stderr.write(s), openPgDataset, interactive ? {
791
- ask: createAsk({
792
- input: process.stdin,
793
- output: process.stderr,
794
- terminal: true,
795
- onInterrupt: () => {
796
- process.stderr.write("\ninterrupted.\n");
797
- process.exit(130);
798
- }
799
- }),
800
- interactive: true
801
- } : {
802
- ask: async () => null,
803
- interactive: false
804
- }).then((exitCode) => process.exit(exitCode));
28
+
29
+ //#endregion
30
+ //#region src/bin/admin.ts
31
+ /**
32
+ * `substrate-admin` entrypoint, and nothing else: it checks the Node version,
33
+ * then loads the CLI (`../admin/run.ts`) dynamically, because static imports
34
+ * would evaluate the whole CLI before the check. The public surface is
35
+ * `../admin/index.ts`.
36
+ */
37
+ if (isEntrypointPath(import.meta.url, process.argv[1])) {
38
+ assertNodeVersion();
39
+ import("./run-Cu9w5Y10.js").then(({ runAdminCli }) => runAdminCli());
805
40
  }
806
41
 
807
42
  //#endregion
808
- export { AdminCliError, BootstrapError, bootstrapKidPath, describeAdminTarget, describeGrant, doctorCommand, formatBootstrapOutput, formatChecklist, formatDoctorReport, formatRegisterOutput, formatRevokeOutput, formatRotateOutput, formatUpdateOutput, grantLines, isEntrypointPath, listActiveAdminKeys, main, onboardCommand, openPgDataset, parseBootstrapArgs, parseListArgs, parseRegisterArgs, parseRotateArgs, parseUpdateArgs, readEd25519PublicKey, reconcileIdentities, resolveAdminAuth, resolveAdminTarget, resolveDefaultKeyPath, resolveDefaultKidPath, runBootstrap, runDoctor, runList, runOnboard, runRegister, runRegisterViaRoute, runRevoke, runRotate, runUpdate };
43
+ export { };