@mnmal-ai/substrate 1.0.0-alpha.0 → 1.0.0-alpha.10

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 (47) hide show
  1. package/README.md +51 -9
  2. package/dist/boot-store-BVqfFxh1.js +4060 -0
  3. package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-Cp4PaIYO.d.ts} +2 -87
  4. package/dist/cli-hSCBywhE.js +3126 -0
  5. package/dist/client.d.ts +130 -8
  6. package/dist/client.js +6 -5
  7. package/dist/{plugin-t2g2wX0b.d.ts → dataset-CejF-Fr_.d.ts} +1640 -1320
  8. package/dist/{agent-token-BIboWOU0.js → env-utils-CGNazUNt.js} +31 -2
  9. package/dist/{errors-D4vKuwz8.d.ts → errors-7mycvNGq.d.ts} +1 -1
  10. package/dist/{index-D7mSOFlM.d.ts → index-DgSfwx7M.d.ts} +1 -1
  11. package/dist/node-version-C5FSmwJX.js +26 -0
  12. package/dist/pack.d.ts +2 -2
  13. package/dist/pack.js +1 -1
  14. package/dist/pg-edges-store-Lxsl5ZnK.js +381 -0
  15. package/dist/{plugin-j1jt1l3n.js → plugin-CtwOINCM.js} +171 -18
  16. package/dist/proposals-bootstrap.js +6 -4
  17. package/dist/proposals.config.schema.json +5 -0
  18. package/dist/proposals.d.ts +15 -4
  19. package/dist/proposals.default-config.json +2 -1
  20. package/dist/proposals.js +2 -2
  21. package/dist/recall-bootstrap.js +13 -4
  22. package/dist/recall.config.schema.json +12 -0
  23. package/dist/recall.d.ts +54 -9
  24. package/dist/recall.js +2 -2
  25. package/dist/{repl-C52wyfMs.js → repl-DqfHelK7.js} +62 -29
  26. package/dist/{row-ByLFE2Wx.d.ts → row-BKKCXIG6.d.ts} +5 -3
  27. package/dist/run-B5dTbZ3g.js +1997 -0
  28. package/dist/{schema-g4FQLr0V.d.ts → schema-DoSc-4ig.d.ts} +44 -7
  29. package/dist/script-C6DSa_Na.js +134 -0
  30. package/dist/sdk.d.ts +90 -12
  31. package/dist/sdk.js +5 -110
  32. package/dist/{src-D91yij6C.js → src-5SJ5GEIM.js} +1557 -327
  33. package/dist/{src-DuopV8u7.js → src-7CUSMK66.js} +148 -19
  34. package/dist/{src-CrEgiMJQ.js → src-Bi849yhn.js} +39 -15
  35. package/dist/{src-D88LvCX8.js → src-CqT-QWZ_.js} +697 -57
  36. package/dist/src-CyvV7dCK.js +4333 -0
  37. package/dist/{row-DK7lPZVe.js → src-Da0t6si5.js} +11 -11
  38. package/dist/{src-C4DzaIQZ.js → src-hZb8wfvg.js} +12 -1
  39. package/dist/substrate-admin.js +17 -781
  40. package/dist/substrate.js +4 -5471
  41. package/dist/testing.d.ts +557 -8
  42. package/dist/testing.js +39 -3
  43. package/dist/{ws-C72iVS5T.d.ts → ws-ByZyHk7m.d.ts} +3 -3
  44. package/package.json +21 -20
  45. package/dist/dataset-BXkus75W.js +0 -1527
  46. package/dist/env-utils-B7SGmoeJ.js +0 -21
  47. package/dist/src-CzxvmhFn.js +0 -2327
@@ -1,1527 +0,0 @@
1
- import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
- import { d as buildAuditRow, f as AUDIT_EVENT_TYPE } from "./src-D91yij6C.js";
3
- import { a as makeAuthorizationProvider, c as resolveDefaultKeyPath, l as resolveDefaultKidPath, r as adminClaimCapabilities, s as resolveAdminCredential, t as ADMIN_CAPABILITIES } from "./agent-token-BIboWOU0.js";
4
- import { D as isActiveAdminKeyRow, E as describeGrant, L as encodeList, M as grantEntryError, T as SYSTEM_NAMESPACE, v as grantEntriesConfer } from "./row-DK7lPZVe.js";
5
- import { _ as currentStep, b as DIAGNOSE_CHECKS, g as STEP_MARKS, h as SKIPPABLE_STEPS, n as tokenAudience, p as CURRENT_MARK, v as planOnboarding, x as diagnose, y as requiredOutstanding } from "./src-DuopV8u7.js";
6
- import { i as pendingMigrations, o as runMigrations, t as PgDataset } from "./src-CzxvmhFn.js";
7
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
- import { homedir } from "node:os";
9
- import { dirname, join } from "node:path";
10
- import { createHash, createPublicKey, generateKeyPairSync, randomUUID } from "node:crypto";
11
- import postgres from "postgres";
12
-
13
- //#region package.json
14
- var version = "1.0.0-alpha.0";
15
-
16
- //#endregion
17
- //#region src/admin/errors.ts
18
- /**
19
- * Shared CLI error carrying a process exit code. Used by `substrate-admin` and by
20
- * the `substrate federate` verbs that write direct-to-pg.
21
- */
22
- var AdminCliError = class extends Error {
23
- name = "AdminCliError";
24
- exitCode;
25
- constructor(message, exitCode = 1) {
26
- super(message);
27
- this.exitCode = exitCode;
28
- }
29
- };
30
-
31
- //#endregion
32
- //#region src/pg-client.ts
33
- function formatPgNotice(notice) {
34
- const candidate = typeof notice === "object" && notice !== null ? notice : null;
35
- const message = typeof candidate?.message === "string" ? candidate.message : String(notice);
36
- return `pg ${(typeof candidate?.severity === "string" ? candidate.severity : "NOTICE").toLowerCase()}: ${message}\n`;
37
- }
38
- /**
39
- * The `onnotice` option, with an injectable sink so the routing is testable
40
- * without opening a connection.
41
- */
42
- function pgNoticeOptions(write = (s) => void process.stderr.write(s)) {
43
- return { onnotice: (notice) => write(formatPgNotice(notice)) };
44
- }
45
- /**
46
- * Open a pg client with substrate's standard options. Prefer this over calling
47
- * `postgres()` directly so NOTICE routing stays consistent across `serve`, the
48
- * admin CLI, `substrate federate`, and the migrate CLI.
49
- */
50
- function openSql(url) {
51
- return postgres(url, pgNoticeOptions());
52
- }
53
-
54
- //#endregion
55
- //#region src/admin/usage.ts
56
- /** The `--help` text, kept beside the dispatch that has to stay true to it. */
57
- const USAGE = [
58
- "Usage: substrate-admin <subcommand>",
59
- " substrate-admin --version print the package version (also -v, version)",
60
- "",
61
- "Subcommands:",
62
- " bootstrap [--encrypt] seed the genesis admin Key",
63
- " doctor [--url <base>] check this deployment end to end and say what is wrong",
64
- " onboard [--url <base>] [--check] walk a deployment to ready, offering to run each fix",
65
- " list print active Key rows (DIRECT to pg — does not authenticate)",
66
- " list --url <base> ask a SERVER over the admin-gated route (authenticates)",
67
- " revoke <kid> soft-delete a Key by kid",
68
- " rotate <kid> --out <path> [--encrypt] rotate a Key (new key to <path>)",
69
- " register <kid> --pubkey <path> --ns <csv> register an existing ed25519 pubkey as an agent Key",
70
- " update <kid> [--ns <csv>] ... change a live key's namespaces/caps/name in place",
71
- "",
72
- " register transport: drives POST /substrate/v1/_system/keys (credential + directory row,",
73
- " one transaction, no restart) using --url or SUBSTRATE_URL and an admin identity",
74
- " (SUBSTRATE_ADMIN_TOKEN, or SUBSTRATE_ADMIN_KEY_PATH + SUBSTRATE_ADMIN_KEY_ID).",
75
- " --direct forces the legacy direct-to-postgres write — break-glass only:",
76
- " it needs the pg superuser password and CANNOT write the directory row.",
77
- " register directory flags: --no-directory (credential only), --no-broadcast",
78
- " (directory row with broadcastEligible false), --project <p>.",
79
- " register flags: --ns <csv> is REQUIRED (use --ns '*' to grant every namespace);",
80
- " --name <n> --caps <csv> --allow-admin are optional.",
81
- " update flags: --name <n> --ns <csv> --caps <csv> --widen --allow-admin",
82
- " omitted flags leave that field unchanged; --widen is required",
83
- " only when the change grants authority the key does not have.",
84
- " --ns entries may carry per-namespace capabilities:",
85
- " --ns inventory:read,notes:read+mutate read inventory, write notes.",
86
- " A bare entry takes --caps, so --ns notes is unchanged.",
87
- " --allow-unknown-ns (register + update): confirm a grant naming a namespace",
88
- " this deployment does not host. Without it such a grant is",
89
- " refused, because it is accepted by the store and then",
90
- " refused at every frame — it reads as granted and reaches",
91
- " nothing. Pass it to register ahead of a plugin install.",
92
- " TARGET (register / revoke / update): --url <base> goes through a running",
93
- " server; --direct writes to SUBSTRATE_DATABASE_URL. Say neither and the",
94
- " target comes from SUBSTRATE_URL, or from SUBSTRATE_DATABASE_URL when no",
95
- " SUBSTRATE_URL is set. If BOTH are set and you name neither, the",
96
- " command REFUSES rather than guessing — these are credential",
97
- " writes and a silent choice can PATCH the wrong store. Every",
98
- " run prints the target and where it came from before acting.",
99
- " doctor goes through the running server on purpose: it is the one command that can",
100
- " answer NO about auth. It checks reachability, whether the server verifies",
101
- " credentials at all, whether YOUR admin credential resolves, whether the grant it",
102
- " resolves to confers admin, and how many admin keys the deployment has left.",
103
- " A check it could not run prints as `skip`, never as a pass.",
104
- " --encrypt produces a PKCS#8+PBES2 (aes-256-cbc) encrypted private-key PEM.",
105
- " Passphrase is read from SUBSTRATE_ADMIN_KEY_PASSPHRASE (required when --encrypt is set).",
106
- " An encrypted admin key is read with SUBSTRATE_ADMIN_KEY_PASSPHRASE for every command that signs."
107
- ].join("\n");
108
- /** One-line synopsis per subcommand — the shape the operator typed wrong. */
109
- const SYNOPSIS = {
110
- bootstrap: "substrate-admin bootstrap [--encrypt]",
111
- doctor: "substrate-admin doctor [--url <base> | --direct]",
112
- onboard: "substrate-admin onboard [--url <base>] [--check]",
113
- list: "substrate-admin list [--url <base>]",
114
- revoke: "substrate-admin revoke <kid> [--url <base> | --direct]",
115
- rotate: "substrate-admin rotate <kid> --out <path> [--encrypt]",
116
- register: "substrate-admin register <kid> --pubkey <path> --ns <csv> [--name <n>] [--caps <csv>] [--allow-admin]",
117
- update: "substrate-admin update <kid> [--name <n>] [--ns <csv>] [--caps <csv>] [--widen] [--allow-admin]"
118
- };
119
- /**
120
- * An argv-parse failure with the command's usage synopsis attached. Every
121
- * throw inside a parse*Args function goes through here; run-phase errors keep
122
- * bare messages because they name the refusing layer instead.
123
- */
124
- function argvError(cmd, message, exitCode = 1) {
125
- const synopsis = SYNOPSIS[cmd];
126
- return new AdminCliError(synopsis === void 0 ? message : `${message}\nusage: ${synopsis}`, exitCode);
127
- }
128
- /**
129
- * Printed after every DIRECT-to-postgres credential write. No interceptor
130
- * fires, so the running server does not see the change until its re-prime
131
- * interval elapses or it restarts.
132
- */
133
- const RESTART_NOTE = [
134
- "A RUNNING binary will not see this change until its registry re-primes —",
135
- "restart it (e.g. `sudo systemctl restart substrate-binary`), or set",
136
- "SUBSTRATE_KEY_REFRESH_INTERVAL_MS so it converges without one."
137
- ].join("\n");
138
-
139
- //#endregion
140
- //#region src/admin/argv.ts
141
- /**
142
- * One argv contract for every subcommand, declared once.
143
- *
144
- * This owns exactly two questions: is this flag known, and is this positional
145
- * one too many. Everything semantic stays with each parser — duplicate
146
- * detection, mutual exclusion (`--direct` vs `--url`), required flags, value
147
- * SHAPES, and missing required positionals.
148
- */
149
- /**
150
- * The seven subcommands, and the whole of what each accepts.
151
- *
152
- * This table is also the definition of "known command": `main` refuses anything
153
- * absent from it BEFORE dispatching, so a subcommand added to the dispatch
154
- * switch without an entry here does not run at all.
155
- *
156
- * Per-command wording (`hint`, `excess`) and `list`'s `--url=` form are
157
- * deliberate and pinned by tests.
158
- */
159
- const ARGV_SPEC = {
160
- bootstrap: {
161
- valueFlags: [],
162
- boolFlags: ["--encrypt"],
163
- maxPositionals: 0
164
- },
165
- doctor: {
166
- valueFlags: ["--url"],
167
- boolFlags: ["--direct"],
168
- maxPositionals: 0,
169
- hint: " (accepts --url <base> or --direct)",
170
- excess: (tok) => `doctor: unexpected argument '${tok}' (accepts --url <base> or --direct)`
171
- },
172
- onboard: {
173
- valueFlags: ["--url"],
174
- boolFlags: ["--direct", "--check"],
175
- maxPositionals: 0,
176
- hint: " (accepts --url <base> and --check)",
177
- excess: (tok) => `onboard: unexpected argument '${tok}' (accepts --url <base> and --check)`
178
- },
179
- list: {
180
- valueFlags: ["--url"],
181
- boolFlags: [],
182
- maxPositionals: 0,
183
- hint: " (list accepts only --url <base>)",
184
- excess: (tok) => `list: unexpected argument '${tok}' (list accepts only --url <base>)`,
185
- equalsForm: true
186
- },
187
- revoke: {
188
- valueFlags: ["--url"],
189
- boolFlags: ["--direct"],
190
- maxPositionals: 1,
191
- excess: (tok) => `revoke: unexpected extra argument '${tok}' — one <kid> at a time`
192
- },
193
- rotate: {
194
- valueFlags: ["--out"],
195
- boolFlags: ["--encrypt"],
196
- maxPositionals: 1
197
- },
198
- register: {
199
- valueFlags: [
200
- "--pubkey",
201
- "--name",
202
- "--ns",
203
- "--caps",
204
- "--url",
205
- "--project"
206
- ],
207
- boolFlags: [
208
- "--allow-admin",
209
- "--allow-unknown-ns",
210
- "--direct",
211
- "--no-directory",
212
- "--no-broadcast"
213
- ],
214
- maxPositionals: 1
215
- },
216
- update: {
217
- valueFlags: [
218
- "--name",
219
- "--ns",
220
- "--caps",
221
- "--url"
222
- ],
223
- boolFlags: [
224
- "--direct",
225
- "--allow-unknown-ns",
226
- "--widen",
227
- "--allow-admin"
228
- ],
229
- maxPositionals: 1
230
- }
231
- };
232
- /** A command with no descriptor accepts nothing at all. */
233
- const FAIL_CLOSED = {
234
- valueFlags: [],
235
- boolFlags: [],
236
- maxPositionals: 0
237
- };
238
- /**
239
- * Refuse unknown flags and surplus positionals for `cmd`, given its tail
240
- * (argv WITHOUT the subcommand name).
241
- *
242
- * Pure and idempotent, which is why it is safe to call from both `main` —
243
- * once, before dispatch — and from each `parse*Args`. The parsers are exported
244
- * from `bin/substrate-admin.ts` and called directly, so they cannot delegate their
245
- * guarantee to a caller they do not have.
246
- */
247
- function validateArgv(cmd, tail) {
248
- const spec = ARGV_SPEC[cmd] ?? FAIL_CLOSED;
249
- let positionals = 0;
250
- for (let i = 0; i < tail.length; i++) {
251
- const tok = tail[i];
252
- if (tok === void 0) continue;
253
- if (tok.startsWith("--")) {
254
- if (spec.valueFlags.includes(tok)) {
255
- const next = tail[i + 1];
256
- const nextIsKnownFlag = next !== void 0 && (spec.valueFlags.includes(next) || spec.boolFlags.includes(next));
257
- if (next !== void 0 && !nextIsKnownFlag) i += 1;
258
- continue;
259
- }
260
- if (spec.boolFlags.includes(tok)) continue;
261
- if (spec.equalsForm === true && spec.valueFlags.some((f) => tok.startsWith(`${f}=`))) continue;
262
- throw argvError(cmd, `${cmd}: unknown flag ${tok}${spec.hint ?? ""}`, 1);
263
- }
264
- positionals += 1;
265
- if (positionals > spec.maxPositionals) throw argvError(cmd, spec.excess?.(tok) ?? `${cmd}: unexpected positional arg '${tok}'`, 1);
266
- }
267
- }
268
-
269
- //#endregion
270
- //#region src/admin/identity.ts
271
- /**
272
- * WHICH store a credential write lands in, and WHICH identity signs it —
273
- * each resolved explicitly and reported with where the choice came from.
274
- */
275
- /**
276
- * Resolve the target for `update` / `revoke` / `register`.
277
- *
278
- * `explicitUrl` is the parser's tri-state: a base URL from `--url`, the empty
279
- * string from `--direct`, and `null` for "said nothing".
280
- *
281
- * When both `SUBSTRATE_URL` and `SUBSTRATE_DATABASE_URL` are set ambiently and no flag
282
- * chooses, this throws naming both escape hatches rather than picking: they
283
- * name two different stores, and a credential write to the wrong one can
284
- * succeed.
285
- */
286
- function resolveAdminTarget(explicitUrl, env) {
287
- if (explicitUrl !== null) return explicitUrl.length > 0 ? {
288
- kind: "route",
289
- baseUrl: explicitUrl,
290
- source: "flag"
291
- } : {
292
- kind: "direct",
293
- source: "flag"
294
- };
295
- const ambientUrl = env.SUBSTRATE_URL !== void 0 && env.SUBSTRATE_URL.length > 0 ? env.SUBSTRATE_URL : null;
296
- const ambientStore = env.SUBSTRATE_DATABASE_URL !== void 0 && env.SUBSTRATE_DATABASE_URL.length > 0 ? env.SUBSTRATE_DATABASE_URL : null;
297
- if (ambientUrl !== null && ambientStore !== null) throw new AdminCliError(`two targets given and neither was chosen: SUBSTRATE_URL names a running server (${ambientUrl}) and SUBSTRATE_DATABASE_URL names a postgres store. This is a credential write, so it will not guess. Pass \`--url <base>\` to go through the server, or \`--direct\` to write to SUBSTRATE_DATABASE_URL.`, 1);
298
- return ambientUrl !== null ? {
299
- kind: "route",
300
- baseUrl: ambientUrl,
301
- source: "env"
302
- } : {
303
- kind: "direct",
304
- source: "fallback"
305
- };
306
- }
307
- /**
308
- * One line, printed BEFORE the write, naming the destination and its
309
- * provenance, so a misdirected command is self-diagnosing.
310
- */
311
- function describeAdminTarget(command, target) {
312
- if (target.kind === "route") {
313
- const from = target.source === "flag" ? "--url" : "SUBSTRATE_URL";
314
- return `${command}: targeting ${target.baseUrl} (from ${from})`;
315
- }
316
- return `${command}: targeting the postgres store DIRECTLY, bypassing the running server (from ${target.source === "flag" ? "--direct" : "SUBSTRATE_DATABASE_URL"})`;
317
- }
318
- /**
319
- * Build the `Authorization` value for an admin route at `baseUrl`, or explain
320
- * what to set. A minted token names `baseUrl`'s origin as its `aud`; a
321
- * `baseUrl` that is plain http to a non-loopback host is refused.
322
- *
323
- * Fail-loud: a message naming the missing key is more use than the 401 an
324
- * unauthenticated admin call would get.
325
- */
326
- function resolveAdminAuth(env, baseUrl) {
327
- let audience;
328
- try {
329
- audience = tokenAudience(baseUrl);
330
- } catch (err) {
331
- return { error: err instanceof Error ? err.message : String(err) };
332
- }
333
- const cred = resolveAdminCredential(env);
334
- if (cred.kind === "error") return { error: cred.error };
335
- if (cred.kind === "token") return { ok: cred.authorization };
336
- const passphrase = env.SUBSTRATE_ADMIN_KEY_PASSPHRASE !== void 0 && env.SUBSTRATE_ADMIN_KEY_PASSPHRASE.length > 0 ? { passphrase: env.SUBSTRATE_ADMIN_KEY_PASSPHRASE } : {};
337
- try {
338
- return { ok: makeAuthorizationProvider({
339
- keyPath: cred.keyPath,
340
- kid: cred.kid
341
- }, {
342
- capabilities: adminClaimCapabilities(env),
343
- audience,
344
- ...passphrase
345
- })() };
346
- } catch (err) {
347
- return { error: `could not sign with ${cred.keyPath}: ${err instanceof Error ? err.message : err}` };
348
- }
349
- }
350
-
351
- //#endregion
352
- //#region src/admin/keys.ts
353
- /**
354
- * Key row plumbing shared by every subcommand: reading rows, classifying
355
- * the admin ones, minting keypairs, and the write-attribution hint.
356
- *
357
- * `listActiveAdminKeys` classifies through `isActiveAdminKeyRow` rather than
358
- * reading the flat `capabilities` column: a key stored
359
- * `namespaces: '*:read+mutate+admin'` carries no `admin` in `capabilities`
360
- * and is nonetheless an admin.
361
- */
362
- /** Sentinel `actorKid` stamped on every audit row emitted by this CLI. */
363
- const CLI_ACTOR_KID = "substrate-admin-cli";
364
- /**
365
- * Substrate auto-fill hint for every `_system` write this CLI makes. Without
366
- * it the row metadata (`createdBy` / `updatedBy`) lands NULL.
367
- *
368
- * `kind: 'system'` rather than `'agent'`: this is a component acting, not a
369
- * registered identity signing.
370
- */
371
- const ACTOR_HINT = { identity: {
372
- kind: "system",
373
- id: CLI_ACTOR_KID
374
- } };
375
- /**
376
- * Strip `_metadata` from a row read back for update, so the write's
377
- * {@link ACTOR_HINT} actually takes effect.
378
- *
379
- * A dataset auto-fills metadata from `options.identity` only when the
380
- * incoming row has NO `_metadata`, so a row built as `{ ...existing.row, ... }`
381
- * would silently keep the previous `updatedBy`.
382
- *
383
- * Stripping is safe and does not lose `createdBy`: the dataset merges per-field
384
- * against the STORED row (`createdBy: existing.createdBy ?? incoming.createdBy`),
385
- * so `created*` survive from storage while `updated*` come from the hint.
386
- */
387
- function forUpdate(row) {
388
- const { _metadata: _dropped, ...rest } = row;
389
- return rest;
390
- }
391
- /**
392
- * Mint an ed25519 keypair for `bootstrap` / `rotate`. When `wantsEncrypt` is
393
- * true, the private-key PEM is PKCS#8+PBES2 (aes-256-cbc) encrypted with
394
- * `SUBSTRATE_ADMIN_KEY_PASSPHRASE` — the env var MUST be set to a non-empty value
395
- * or this helper hard-errors. When false, the PEM is cleartext PKCS#8.
396
- *
397
- * At-rest encryption is purely operator-side: the server only ever reads the
398
- * public key from pg, so the encrypted-ness of the on-disk private key has no
399
- * server-side coupling.
400
- */
401
- function generateAdminKeypair(env, wantsEncrypt) {
402
- if (wantsEncrypt) {
403
- const passphrase = env.SUBSTRATE_ADMIN_KEY_PASSPHRASE;
404
- if (passphrase === void 0 || passphrase.length === 0) throw new AdminCliError("--encrypt requires SUBSTRATE_ADMIN_KEY_PASSPHRASE to be set to a non-empty value", 6);
405
- const { privateKey, publicKey } = generateKeyPairSync("ed25519", {
406
- publicKeyEncoding: {
407
- format: "pem",
408
- type: "spki"
409
- },
410
- privateKeyEncoding: {
411
- format: "pem",
412
- type: "pkcs8",
413
- cipher: "aes-256-cbc",
414
- passphrase
415
- }
416
- });
417
- return {
418
- publicKeyPem: publicKey.toString(),
419
- privateKeyPem: privateKey.toString(),
420
- encrypted: true
421
- };
422
- }
423
- const { privateKey, publicKey } = generateKeyPairSync("ed25519", {
424
- publicKeyEncoding: {
425
- format: "pem",
426
- type: "spki"
427
- },
428
- privateKeyEncoding: {
429
- format: "pem",
430
- type: "pkcs8"
431
- }
432
- });
433
- return {
434
- publicKeyPem: publicKey.toString(),
435
- privateKeyPem: privateKey.toString(),
436
- encrypted: false
437
- };
438
- }
439
- var BootstrapError = class extends Error {
440
- name = "BootstrapError";
441
- exitCode;
442
- constructor(message, exitCode = 1) {
443
- super(message);
444
- this.exitCode = exitCode;
445
- }
446
- };
447
- function base64Url(buf) {
448
- return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
449
- }
450
- function rowAsAdminKey(row) {
451
- const kid = row.kid;
452
- if (typeof kid !== "string" || kid.length === 0) return null;
453
- return {
454
- kid,
455
- name: typeof row.name === "string" ? row.name : "",
456
- namespaces: typeof row.namespaces === "string" ? row.namespaces : "",
457
- capabilities: typeof row.capabilities === "string" ? row.capabilities : "",
458
- createdAt: row._metadata?.createdAt ?? null
459
- };
460
- }
461
- /**
462
- * Read every non-revoked Key row whose grant confers `adminCapability`
463
- * on `_system` (per `isActiveAdminKeyRow`). Scans the whole table, which is
464
- * fine at CLI cadence.
465
- */
466
- async function listActiveAdminKeys(dataset, adminCapability) {
467
- const { rows } = await dataset.read("Key", {});
468
- const out = [];
469
- for (const row of rows) {
470
- if (!isActiveAdminKeyRow(row, adminCapability)) continue;
471
- const ak = rowAsAdminKey(row);
472
- if (ak === null) continue;
473
- out.push(ak);
474
- }
475
- return out;
476
- }
477
- /**
478
- * `bootstrap`-specific helper: first matching admin row or `null`. Wraps
479
- * `listActiveAdminKeys` so the bootstrap contract ("refuse if ANY admin row
480
- * exists") doesn't leak the array shape out of this module.
481
- */
482
- async function firstAdminKey(dataset, adminCapability) {
483
- return (await listActiveAdminKeys(dataset, adminCapability))[0] ?? null;
484
- }
485
- /** The capability name that means "admin" when `SUBSTRATE_ADMIN_CAPABILITY` is unset. */
486
- const DEFAULT_ADMIN_CAPABILITY = "admin";
487
- async function readKeyById(dataset, kid) {
488
- const { rows } = await dataset.read("Key", { where: { kid: { eq: kid } } });
489
- const row = rows.find((r) => r.revokedAt == null) ?? rows[0];
490
- if (row === void 0) return null;
491
- return {
492
- row,
493
- revokedAt: row.revokedAt instanceof Date ? row.revokedAt : typeof row.revokedAt === "string" ? row.revokedAt : null
494
- };
495
- }
496
- /**
497
- * Read a public-key PEM from disk and assert it is Ed25519. Returns the PEM
498
- * text verbatim for storage on the Key row. Throws AdminCliError(2) on a
499
- * missing/unreadable file, a private-key PEM (missing `BEGIN PUBLIC KEY`
500
- * header — prevents accidental private-key leakage when the operator passes
501
- * the wrong file to `--pubkey`), an unparseable PEM, or a non-ed25519 key.
502
- * `register` only mints/accepts Ed25519 agent identities (the one alg the
503
- * verifier + signer support).
504
- */
505
- function readEd25519PublicKey(path) {
506
- let pem;
507
- try {
508
- pem = readFileSync(path, "utf8");
509
- } catch (err) {
510
- const msg = err instanceof Error ? err.message : String(err);
511
- throw new AdminCliError(`register: cannot read --pubkey '${path}': ${msg}`, 2);
512
- }
513
- if (!pem.includes("BEGIN PUBLIC KEY")) throw new AdminCliError(`register: --pubkey '${path}' is not a public-key PEM (missing 'BEGIN PUBLIC KEY' header) — did you pass the private key by mistake?`, 2);
514
- let keyType;
515
- try {
516
- keyType = createPublicKey(pem).asymmetricKeyType;
517
- } catch (err) {
518
- const msg = err instanceof Error ? err.message : String(err);
519
- throw new AdminCliError(`register: --pubkey '${path}' is not a valid public key: ${msg}`, 2);
520
- }
521
- if (keyType !== "ed25519") throw new AdminCliError(`register: --pubkey '${path}' is ${keyType ?? "unknown"}, expected ed25519`, 2);
522
- return pem;
523
- }
524
-
525
- //#endregion
526
- //#region src/admin/route.ts
527
- /**
528
- * Drive `PATCH /substrate/v1/_system/keys`. A write through the engine reaches the
529
- * running server's key registry; a direct write does not.
530
- *
531
- * Refusals come back with the same `code` the CLI's own guards produce,
532
- * because both sides ask `key-guards`. Statuses are mapped back to the
533
- * same exit codes so scripts do not care which transport ran.
534
- */
535
- async function runKeyPatchViaRoute(body, baseUrl, env, exitCodes, fetchImpl = fetch) {
536
- const auth = resolveAdminAuth(env, baseUrl);
537
- if ("error" in auth) throw new AdminCliError(`${body.revoke === true ? "revoke" : "update"}: ${auth.error}`, 1);
538
- const url = `${baseUrl.replace(/\/+$/, "")}/substrate/v1/_system/keys`;
539
- let res;
540
- try {
541
- res = await fetchImpl(url, {
542
- method: "PATCH",
543
- headers: {
544
- "content-type": "application/json",
545
- authorization: auth.ok
546
- },
547
- body: JSON.stringify(body),
548
- redirect: "error"
549
- });
550
- } catch (err) {
551
- throw new AdminCliError(`could not reach ${url}: ${err instanceof Error ? err.message : String(err)}`, 1);
552
- }
553
- const payload = await res.json().catch(() => ({}));
554
- if (!res.ok) {
555
- const code = typeof payload.code === "string" ? payload.code : "request_failed";
556
- const message = typeof payload.message === "string" ? payload.message : `HTTP ${res.status}`;
557
- throw new AdminCliError(message, exitCodes[code] ?? 1);
558
- }
559
- return payload;
560
- }
561
- /**
562
- * `revoke` refusal code -> CLI exit code. The route maps the same reasons to
563
- * HTTP statuses. Values are stable: scripts key on them.
564
- */
565
- const REVOKE_EXIT_CODES = {
566
- unknown_kid: 2,
567
- already_revoked: 3,
568
- last_active_admin: 4
569
- };
570
- /**
571
- * `update` refusal code -> CLI exit code. Values are stable: scripts key on
572
- * them. Guards, in the order they fire:
573
- * - unknown kid → exit 2; revoked kid → exit 3 (updating a revoked key would
574
- * be a quiet way to resurrect a retired identity)
575
- * - dropping admin from the last active admin → exit 4, mirroring `revoke`'s
576
- * lockout guard. Fires BEFORE the widen gate: it cannot be lifted by a flag,
577
- * and one request can trip both.
578
- * - a change that GRANTS authority the key lacks → exit 5 unless `--widen`
579
- * - granting `admin` → additionally requires `--allow-admin`, mirroring
580
- * `register`
581
- */
582
- const UPDATE_EXIT_CODES = {
583
- unknown_kid: 2,
584
- already_revoked: 3,
585
- last_active_admin: 4,
586
- last_admin_deadmin: 4,
587
- requires_widen: 5,
588
- requires_allow_admin: 1,
589
- invalid_grant: 1
590
- };
591
- /**
592
- * Drive `GET /substrate/v1/_system/keys` — the authenticated read behind
593
- * `list --url`, gated by the server's admin check.
594
- *
595
- * Pages to exhaustion rather than returning the first page: a silently
596
- * truncated answer to "which identities exist" is worse than an error.
597
- */
598
- async function runKeyListViaRoute(baseUrl, env, fetchImpl = fetch) {
599
- const auth = resolveAdminAuth(env, baseUrl);
600
- if ("error" in auth) throw new AdminCliError(`list: ${auth.error}`, 1);
601
- const base = `${baseUrl.replace(/\/+$/, "")}/substrate/v1/_system/keys`;
602
- const keys = [];
603
- let cursor;
604
- for (let page = 0; page < 50; page += 1) {
605
- const url = cursor === void 0 ? base : `${base}?cursor=${encodeURIComponent(cursor)}`;
606
- let res;
607
- try {
608
- res = await fetchImpl(url, {
609
- method: "GET",
610
- headers: { authorization: auth.ok },
611
- redirect: "error"
612
- });
613
- } catch (err) {
614
- throw new AdminCliError(`could not reach ${url}: ${err instanceof Error ? err.message : String(err)}`, 1);
615
- }
616
- const payload = await res.json().catch(() => ({}));
617
- if (!res.ok) {
618
- const message = typeof payload.message === "string" ? payload.message : `HTTP ${res.status}`;
619
- throw new AdminCliError(res.status === 403 ? `list --url: refused by ${baseUrl} — ${message}\n This is the server's verdict on the credential you presented, which is exactly what \`list\` without --url cannot tell you.` : `list --url: ${message}`, res.status === 403 ? 5 : 1);
620
- }
621
- const batch = payload.keys;
622
- if (!Array.isArray(batch)) throw new AdminCliError("list --url: response carried no `keys` array", 1);
623
- keys.push(...batch);
624
- if (payload.hasMore !== true) return keys;
625
- cursor = typeof payload.nextCursor === "string" ? payload.nextCursor : void 0;
626
- if (cursor === void 0) throw new AdminCliError("list --url: server reported hasMore with no nextCursor — refusing to report a partial list as complete", 1);
627
- }
628
- throw new AdminCliError("list --url: pagination did not terminate after 50 pages", 1);
629
- }
630
-
631
- //#endregion
632
- //#region src/admin/env.ts
633
- /**
634
- * Where the admin CLI's key files live, and the env it reads them from.
635
- *
636
- * These resolvers live together because they answer one question — *which
637
- * file is this deployment's admin identity?* — and `bootstrap` (the writer)
638
- * and `resolveAdminAuth` (the reader) must agree on it.
639
- */
640
- /**
641
- * Where `bootstrap` writes the kid. Beside the key when one was named
642
- * explicitly, else the default path.
643
- */
644
- function bootstrapKidPath(env) {
645
- return env.SUBSTRATE_ADMIN_KEY_PATH !== void 0 && env.SUBSTRATE_ADMIN_KEY_PATH.length > 0 ? `${resolveDefaultKeyPath(env).replace(/\.key$/, "")}.kid` : resolveDefaultKidPath(env);
646
- }
647
-
648
- //#endregion
649
- //#region src/admin/commands/bootstrap.ts
650
- /**
651
- * `bootstrap` — seed the genesis admin Key on a fresh `_system` namespace.
652
- *
653
- * The one subcommand that CANNOT go through the route: it exists to create the
654
- * first admin identity, so there is none to present. Direct-to-postgres is not
655
- * a legacy path here, it is the only possible one.
656
- */
657
- /**
658
- * What the genesis row grants: the admin capability plus `read` / `mutate`.
659
- *
660
- * `resolveAdminAuth` mints with `adminClaimCapabilities`, a superset of this
661
- * row for any `adminCapability`, and `auth.ts` intersects that claim against
662
- * the row, so the row is the ceiling. Derived from the same constant so the
663
- * two cannot drift; `admin` alone does not satisfy the per-frame `read` /
664
- * `mutate` gates.
665
- */
666
- function seedCapabilities(adminCapability) {
667
- return [...ADMIN_CAPABILITIES.filter((c) => c !== DEFAULT_ADMIN_CAPABILITY), adminCapability];
668
- }
669
- /**
670
- * Perform the bootstrap.
671
- *
672
- * `wantsEncrypt` controls whether the on-disk private-key PEM is
673
- * PBES2-encrypted with `SUBSTRATE_ADMIN_KEY_PASSPHRASE`. Defaults to false.
674
- */
675
- async function runBootstrap(env, wantsEncrypt = false, openSql = postgres) {
676
- const storeSpec = env.SUBSTRATE_DATABASE_URL;
677
- if (storeSpec === void 0 || storeSpec.length === 0) throw new BootstrapError("SUBSTRATE_DATABASE_URL is required (must be a postgres:// URL)");
678
- if (!storeSpec.startsWith("postgres://") && !storeSpec.startsWith("postgresql://")) throw new BootstrapError(`SUBSTRATE_DATABASE_URL must be a postgres:// URL for bootstrap (got '${redactStore(storeSpec)}'). Memory-backed stores cannot persist the admin key across restarts.`);
679
- const adminCapability = env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? env.SUBSTRATE_ADMIN_CAPABILITY : DEFAULT_ADMIN_CAPABILITY;
680
- const seededCapabilities = seedCapabilities(adminCapability);
681
- const privateKeyPath = resolveDefaultKeyPath(env);
682
- if (existsSync(privateKeyPath)) throw new BootstrapError(`private key path '${privateKeyPath}' already exists — move it aside and retry`);
683
- const kidPath = bootstrapKidPath(env);
684
- if (existsSync(kidPath)) throw new BootstrapError(`kid path '${kidPath}' already exists — move it aside and retry`);
685
- const { publicKeyPem, privateKeyPem, encrypted } = generateAdminKeypair(env, wantsEncrypt);
686
- const sql = openSql(storeSpec);
687
- let dataset;
688
- try {
689
- await runMigrations(sql);
690
- dataset = new PgDataset({
691
- namespace: SYSTEM_NAMESPACE,
692
- sql
693
- });
694
- return await dataset.withAdvisoryLock("substrate:bootstrap", async () => {
695
- const existing = await firstAdminKey(dataset, adminCapability);
696
- if (existing !== null) throw new BootstrapError(`admin Key already bootstrapped (kid: ${existing.kid}). Revoke or purge it via the _system namespace before running bootstrap again.`);
697
- const kid = randomUUID();
698
- const shaFull = createHash("sha256").update(publicKeyPem).digest();
699
- const fingerprint = `sha256:${base64Url(shaFull).slice(0, 8)}`;
700
- const parentDir = dirname(privateKeyPath);
701
- mkdirSync(parentDir, {
702
- recursive: true,
703
- mode: 448
704
- });
705
- writeFileSync(privateKeyPath, privateKeyPem, {
706
- mode: 384,
707
- flag: "wx"
708
- });
709
- writeFileSync(kidPath, `${kid}\n`, {
710
- mode: 384,
711
- flag: "wx"
712
- });
713
- const now = /* @__PURE__ */ new Date();
714
- await dataset.write("Key", [{
715
- id: kid,
716
- kid,
717
- name: "bootstrap-admin",
718
- algorithm: "EdDSA",
719
- publicKey: publicKeyPem,
720
- namespaces: "*",
721
- capabilities: encodeList(seededCapabilities),
722
- revokedAt: null
723
- }], {
724
- identity: {
725
- kind: "system",
726
- id: "bootstrap"
727
- },
728
- now
729
- });
730
- return {
731
- kid,
732
- fingerprint,
733
- privateKeyPath,
734
- namespaces: "*",
735
- capabilities: seededCapabilities.join(","),
736
- encrypted
737
- };
738
- });
739
- } finally {
740
- try {
741
- await sql.end();
742
- } catch {}
743
- }
744
- }
745
- function formatBootstrapOutput(result) {
746
- const encLabel = result.encrypted ? "encrypted: aes-256-cbc+pbes2" : "unencrypted";
747
- return [
748
- "substrate-admin bootstrap complete.",
749
- `kid: ${result.kid}`,
750
- `fingerprint: ${result.fingerprint}`,
751
- `private key: ${result.privateKeyPath} (mode 0600, ${encLabel})`,
752
- `namespaces: ${result.namespaces}`,
753
- `capabilities: ${result.capabilities}`,
754
- "",
755
- `Use the private key to sign JWTs with kid=${result.kid} to authenticate as admin.`,
756
- "",
757
- RESTART_NOTE,
758
- ""
759
- ].join("\n");
760
- }
761
- function parseBootstrapArgs(argv) {
762
- try {
763
- return parseBootstrapArgsInner(argv);
764
- } catch (err) {
765
- if (err instanceof AdminCliError) throw argvError("bootstrap", err.message, err.exitCode);
766
- throw err;
767
- }
768
- }
769
- function parseBootstrapArgsInner(argv) {
770
- const rest = argv.slice(1);
771
- validateArgv("bootstrap", rest);
772
- let wantsEncrypt = false;
773
- for (const tok of rest) if (tok === "--encrypt") {
774
- if (wantsEncrypt) throw new AdminCliError("bootstrap: --encrypt specified more than once", 1);
775
- wantsEncrypt = true;
776
- }
777
- return { wantsEncrypt };
778
- }
779
-
780
- //#endregion
781
- //#region src/admin/commands/doctor.ts
782
- /**
783
- * `substrate-admin doctor` — diagnoses an admin deployment through checks that
784
- * can each answer NO.
785
- *
786
- * 1. **Route-only.** Every auth claim is checked through the running server;
787
- * a direct postgres read never authenticates, so it cannot test auth.
788
- * 2. **A SKIP is not an OK.** A check whose precondition failed renders as
789
- * `skip` with the reason — never as a pass, and never omitted.
790
- * 3. **Shared classifiers.** Admin checks use `isActiveAdminKeyRow` and
791
- * `capabilitiesFor`, the same predicates the server's guards use, so the
792
- * doctor cannot agree with a copy that has drifted from the guard.
793
- */
794
- /** The NO a non-route target gets: doctor and onboard both refuse to measure through postgres. */
795
- const DIRECT_TARGET_REFUSAL = {
796
- name: "target",
797
- status: "no",
798
- detail: "resolved to the postgres store, bypassing the running server. Nothing below can be measured from there: a direct read never authenticates, so it answers a different question from the one you asked (this is what made `substrate-admin list` misleading — it printed the admin row while admin auth was broken).",
799
- fix: "Pass `--url <base>`, or set SUBSTRATE_URL, so the checks go through the server that is doing the refusing."
800
- };
801
- /**
802
- * Runs every check against `target`, in dependency order. A failure
803
- * short-circuits its dependants into explicit skips.
804
- */
805
- async function runDoctor(env, target, fetchImpl = fetch) {
806
- if (target.kind !== "route") return {
807
- checks: [DIRECT_TARGET_REFUSAL, ...DIAGNOSE_CHECKS.map((name) => ({
808
- name,
809
- status: "skip",
810
- detail: "not asked — target answered no"
811
- }))],
812
- exitCode: 1
813
- };
814
- const result = await diagnoseTarget(env, target.baseUrl, fetchImpl);
815
- return {
816
- checks: [{
817
- name: "target",
818
- status: "ok",
819
- detail: describeAdminTarget("doctor", target).replace(/^doctor: /, "")
820
- }, ...result.checks],
821
- exitCode: result.exitCode
822
- };
823
- }
824
- /** Diagnose `baseUrl` with the admin credential `env` resolves — shared by doctor and onboard. */
825
- async function diagnoseTarget(env, baseUrl, fetchImpl = fetch) {
826
- const auth = resolveAdminAuth(env, baseUrl);
827
- return diagnose({
828
- baseUrl,
829
- credential: "error" in auth ? { error: auth.error } : {
830
- authorization: () => auth.ok,
831
- label: describeCredential(env)
832
- },
833
- ...env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? { adminCapability: env.SUBSTRATE_ADMIN_CAPABILITY } : {},
834
- fetch: (input, init) => fetchImpl(input, {
835
- ...init,
836
- redirect: "error"
837
- })
838
- });
839
- }
840
- /** Which credential the run used, without printing any of it. */
841
- function describeCredential(env) {
842
- if (env.SUBSTRATE_ADMIN_TOKEN !== void 0 && env.SUBSTRATE_ADMIN_TOKEN.length > 0) return "SUBSTRATE_ADMIN_TOKEN";
843
- return `${env.SUBSTRATE_ADMIN_KEY_PATH !== void 0 && env.SUBSTRATE_ADMIN_KEY_PATH.length > 0 ? env.SUBSTRATE_ADMIN_KEY_PATH : "the default admin key path"} (the file path only — no key material is read out here)`;
844
- }
845
- const GLYPH = {
846
- ok: "ok ",
847
- no: "NO ",
848
- skip: "skip"
849
- };
850
- /**
851
- * Renders the report. The trailer counts skips separately from passes so a
852
- * reader cannot sum unasked checks into a verdict.
853
- */
854
- function formatDoctorReport(report) {
855
- const width = Math.max(...report.checks.map((c) => c.name.length));
856
- const lines = ["substrate-admin doctor", ""];
857
- for (const check of report.checks) {
858
- lines.push(` ${GLYPH[check.status]} ${check.name.padEnd(width)} ${check.detail}`);
859
- if (check.fix !== void 0) lines.push(` ${" ".repeat(width)} fix: ${check.fix}`);
860
- }
861
- const ok = report.checks.filter((c) => c.status === "ok").length;
862
- const no = report.checks.filter((c) => c.status === "no").length;
863
- const skipped = report.checks.filter((c) => c.status === "skip").length;
864
- lines.push("", skipped > 0 ? `${ok} ok, ${no} failed, ${skipped} NOT ASKED (a skipped check is not a passing one).` : `${ok} ok, ${no} failed.`);
865
- return `${lines.join("\n")}\n`;
866
- }
867
- /** Resolve the target and run — the shape `main` dispatches to. */
868
- async function doctorCommand(argv, env, fetchImpl = fetch) {
869
- validateArgv("doctor", argv);
870
- let url;
871
- let direct = false;
872
- for (let i = 0; i < argv.length; i++) {
873
- const tok = argv[i];
874
- if (tok === void 0) continue;
875
- if (tok === "--url") {
876
- if (url !== void 0) throw argvError("doctor", "doctor: --url specified more than once", 1);
877
- url = argv[i + 1] ?? "";
878
- i += 1;
879
- continue;
880
- }
881
- if (tok === "--direct") direct = true;
882
- }
883
- return runDoctor(env, resolveAdminTarget(direct ? "" : url ?? null, env), fetchImpl);
884
- }
885
-
886
- //#endregion
887
- //#region src/admin/commands/onboard-keys.ts
888
- /**
889
- * Key-file helpers for onboarding: generating a keypair for the register steps, and
890
- * knowing in advance when `bootstrap` would refuse. Both refuse to overwrite, like
891
- * `bootstrap`: clobbering key material destroys an identity silently.
892
- */
893
- /** `~` and `~/…` against HOME; a shell would have done this, a prompt does not. */
894
- function expandHome(env, path) {
895
- if (path !== "~" && !path.startsWith("~/")) return path;
896
- return join(env.HOME ?? homedir(), path.slice(1));
897
- }
898
- /**
899
- * Writes `<path>` (0600) and `<path>.pub`, plus `<path minus .key>.kid` when a kid is
900
- * given — the file the credential resolver reads beside a named key. Creates missing
901
- * parent directories 0700. On a failed write, removes whatever this call already wrote.
902
- */
903
- function writeKeypair(env, path, kid) {
904
- const privateKeyPath = expandHome(env, path);
905
- const publicKeyPath = `${privateKeyPath}.pub`;
906
- const kidPath = kid === void 0 ? void 0 : `${privateKeyPath.replace(/\.key$/, "")}.kid`;
907
- const targets = [
908
- privateKeyPath,
909
- publicKeyPath,
910
- ...kidPath === void 0 ? [] : [kidPath]
911
- ];
912
- for (const p of targets) if (existsSync(p)) throw new AdminCliError(`'${p}' already exists — choose another path`, 1);
913
- const { publicKeyPem, privateKeyPem } = generateAdminKeypair(env, false);
914
- mkdirSync(dirname(privateKeyPath), {
915
- recursive: true,
916
- mode: 448
917
- });
918
- const written = [];
919
- try {
920
- writeFileSync(privateKeyPath, privateKeyPem, {
921
- mode: 384,
922
- flag: "wx"
923
- });
924
- written.push(privateKeyPath);
925
- writeFileSync(publicKeyPath, publicKeyPem, {
926
- mode: 420,
927
- flag: "wx"
928
- });
929
- written.push(publicKeyPath);
930
- if (kidPath !== void 0 && kid !== void 0) writeFileSync(kidPath, `${kid}\n`, {
931
- mode: 384,
932
- flag: "wx"
933
- });
934
- } catch (err) {
935
- for (const p of written) rmSync(p, { force: true });
936
- throw err;
937
- }
938
- return {
939
- privateKeyPath,
940
- publicKeyPath,
941
- ...kidPath === void 0 ? {} : { kidPath }
942
- };
943
- }
944
- /**
945
- * The files whose presence makes `bootstrap` refuse — its own guards, checked without
946
- * opening postgres, so onboard offers bootstrap only when it can succeed.
947
- */
948
- function bootstrapBlockers(env) {
949
- return [resolveDefaultKeyPath(env), bootstrapKidPath(env)].filter((p) => existsSync(p));
950
- }
951
-
952
- //#endregion
953
- //#region src/admin/grant-display.ts
954
- /**
955
- * Rendering a stored grant as the AUTHORITY it confers, rather than as the two
956
- * columns it happens to be stored in.
957
- *
958
- * The two columns only mean anything jointly: `capabilities` is the default
959
- * for BARE `--ns` entries only, so `--ns 'notes:read'` with default
960
- * capabilities `read,mutate` is a read-only grant, not a write grant.
961
- */
962
- /**
963
- * `describeGrant` laid out under a label, continuation lines aligned.
964
- *
965
- * The label is passed in rather than fixed so `register` and `update` can align
966
- * the grant block with their own existing columns.
967
- */
968
- function grantLines(label, namespaces, capabilities) {
969
- const entries = describeGrant(namespaces, capabilities);
970
- const pad = " ".repeat(label.length);
971
- return entries.map((e, i) => `${i === 0 ? label : pad}${e}`);
972
- }
973
-
974
- //#endregion
975
- //#region src/admin/commands/register.ts
976
- /**
977
- * `register` — add an existing ed25519 public key as an agent Key.
978
- *
979
- * `--ns` is REQUIRED and has no default, because a default here is an unbounded
980
- * grant nobody chose. The route path also writes the directory row in the same
981
- * transaction: a credential with no directory row keeps authenticating while
982
- * mail routing and agent listing quietly break.
983
- */
984
- /**
985
- * Parse `register <kid> --pubkey <path> --ns <csv> [--name <n>] [--caps <csv>]
986
- * [--allow-admin]`. Positional <kid> exactly once, single-valued flags.
987
- * Defaults (kid as name, caps read,mutate) are resolved here; `--ns` has no
988
- * default and its absence throws `AdminCliError`.
989
- */
990
- function parseRegisterArgs(argv) {
991
- try {
992
- return parseRegisterArgsInner(argv);
993
- } catch (err) {
994
- if (err instanceof AdminCliError) throw argvError("register", err.message, err.exitCode);
995
- throw err;
996
- }
997
- }
998
- function parseRegisterArgsInner(argv) {
999
- const rest = argv.slice(1);
1000
- validateArgv("register", rest);
1001
- let kid;
1002
- let pubkeyPath;
1003
- let name;
1004
- let nsCsv;
1005
- let capsCsv;
1006
- let allowAdmin = false;
1007
- let allowUnknownNs = false;
1008
- let url;
1009
- let direct = false;
1010
- let noDirectory = false;
1011
- let noBroadcast = false;
1012
- let project;
1013
- const takeValue = (flag, i) => {
1014
- const val = rest[i + 1];
1015
- if (val === void 0 || val.length === 0 || val.startsWith("--")) throw new AdminCliError(`register: ${flag} requires a value`, 1);
1016
- return val;
1017
- };
1018
- for (let i = 0; i < rest.length; i++) {
1019
- const tok = rest[i];
1020
- if (tok === void 0) continue;
1021
- if (tok === "--pubkey") {
1022
- if (pubkeyPath !== void 0) throw new AdminCliError("register: --pubkey specified more than once", 1);
1023
- pubkeyPath = takeValue("--pubkey", i);
1024
- i += 1;
1025
- } else if (tok === "--name") {
1026
- if (name !== void 0) throw new AdminCliError("register: --name specified more than once", 1);
1027
- name = takeValue("--name", i);
1028
- i += 1;
1029
- } else if (tok === "--ns") {
1030
- if (nsCsv !== void 0) throw new AdminCliError("register: --ns specified more than once", 1);
1031
- nsCsv = takeValue("--ns", i);
1032
- i += 1;
1033
- } else if (tok === "--caps") {
1034
- if (capsCsv !== void 0) throw new AdminCliError("register: --caps specified more than once", 1);
1035
- capsCsv = takeValue("--caps", i);
1036
- i += 1;
1037
- } else if (tok === "--allow-admin") {
1038
- if (allowAdmin) throw new AdminCliError("register: --allow-admin specified more than once", 1);
1039
- allowAdmin = true;
1040
- } else if (tok === "--allow-unknown-ns") allowUnknownNs = true;
1041
- else if (tok === "--url") {
1042
- if (direct) throw new AdminCliError("register: --direct and --url are mutually exclusive", 1);
1043
- if (url !== void 0) throw new AdminCliError("register: --url specified more than once", 1);
1044
- url = takeValue("--url", i);
1045
- i += 1;
1046
- } else if (tok === "--direct") {
1047
- if (url !== void 0) throw new AdminCliError("register: --direct and --url are mutually exclusive", 1);
1048
- direct = true;
1049
- url = "";
1050
- } else if (tok === "--no-directory") noDirectory = true;
1051
- else if (tok === "--no-broadcast") noBroadcast = true;
1052
- else if (tok === "--project") {
1053
- if (project !== void 0) throw new AdminCliError("register: --project specified more than once", 1);
1054
- project = takeValue("--project", i);
1055
- i += 1;
1056
- } else kid = tok;
1057
- }
1058
- if (kid === void 0 || kid.length === 0) throw new AdminCliError("register requires a <kid> positional arg", 1);
1059
- if (pubkeyPath === void 0 || pubkeyPath.length === 0) throw new AdminCliError("register requires --pubkey <path>", 1);
1060
- const splitCsv = (csv) => csv.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
1061
- if (nsCsv === void 0) throw new AdminCliError("register requires --ns <csv> — namespaces are granted explicitly, never by default. Pass the namespaces this identity needs (e.g. --ns notes,recall), or --ns '*' to deliberately grant every namespace.", 1);
1062
- const namespaces = splitCsv(nsCsv);
1063
- if (namespaces.length === 0) throw new AdminCliError(`register: --ns '${nsCsv}' resolves to an empty namespace list — an identity that can reach nothing is almost certainly a mistake. Pass real namespaces, or --ns '*'.`, 1);
1064
- const nsError = grantEntryError(namespaces, ["read", "mutate"]);
1065
- if (nsError !== null) throw new AdminCliError(`register: ${nsError} — e.g. --ns inventory:read,notes:read+mutate`, 1);
1066
- const capabilities = capsCsv === void 0 ? ["read", "mutate"] : splitCsv(capsCsv);
1067
- return {
1068
- kid,
1069
- pubkeyPath,
1070
- name: name ?? kid,
1071
- namespaces,
1072
- capabilities,
1073
- allowAdmin,
1074
- allowUnknownNs,
1075
- url: url ?? null,
1076
- noDirectory,
1077
- noBroadcast,
1078
- project: project ?? null
1079
- };
1080
- }
1081
- /**
1082
- * Register an existing Ed25519 public key as an agent Key row directly
1083
- * in postgres, with one `key_registered` audit row written in the SAME tx.
1084
- *
1085
- * Unlike `bootstrap`/`rotate`, the kid is operator-chosen. The row id is a
1086
- * freshly-minted UUID; the kid is the principal field stored separately. A
1087
- * previously-revoked same-kid row is re-registered (same UUID id, clears
1088
- * revokedAt). A LIVE same-kid row is refused — rotate/revoke is the path.
1089
- */
1090
- async function runRegister(args, env, openDataset = openPgDataset) {
1091
- if (grantEntriesConfer(args.namespaces, args.capabilities, "admin") && !args.allowAdmin) throw new AdminCliError("register: 'admin' capability requires --allow-admin (bootstrap is the deliberate admin path)", 1);
1092
- const publicKeyPem = readEd25519PublicKey(args.pubkeyPath);
1093
- const shaFull = createHash("sha256").update(publicKeyPem).digest();
1094
- const fingerprint = `sha256:${base64Url(shaFull).slice(0, 8)}`;
1095
- const namespaces = encodeList(args.namespaces);
1096
- const capabilities = encodeList(args.capabilities);
1097
- const { dataset, close } = await openDataset(env);
1098
- try {
1099
- const replacedRevoked = await dataset.withTransaction(async (tx) => {
1100
- const { rows: existingRows } = await tx.read("Key", { where: { kid: { eq: args.kid } } });
1101
- const existing = existingRows.find((r) => r.revokedAt == null) ?? existingRows[0];
1102
- let wasRevoked = false;
1103
- let rowId = randomUUID();
1104
- if (existing !== void 0) {
1105
- if ((existing.revokedAt instanceof Date ? existing.revokedAt : typeof existing.revokedAt === "string" ? existing.revokedAt : null) == null) throw new AdminCliError(`kid '${args.kid}' is already registered and live — rotate or revoke it instead`, 3);
1106
- wasRevoked = true;
1107
- rowId = existing.id;
1108
- }
1109
- const now = /* @__PURE__ */ new Date();
1110
- await tx.write("Key", [{
1111
- id: rowId,
1112
- kid: args.kid,
1113
- name: args.name,
1114
- algorithm: "EdDSA",
1115
- publicKey: publicKeyPem,
1116
- namespaces,
1117
- capabilities,
1118
- revokedAt: null
1119
- }], ACTOR_HINT);
1120
- await tx.write(AUDIT_EVENT_TYPE, [buildAuditRow({
1121
- actorKid: CLI_ACTOR_KID,
1122
- kind: "key_registered",
1123
- targetKid: args.kid,
1124
- details: {
1125
- kid: args.kid,
1126
- name: args.name,
1127
- namespaces,
1128
- capabilities,
1129
- fingerprint,
1130
- replacedRevoked: wasRevoked
1131
- },
1132
- now
1133
- })], ACTOR_HINT);
1134
- return wasRevoked;
1135
- });
1136
- return {
1137
- kid: args.kid,
1138
- name: args.name,
1139
- fingerprint,
1140
- namespaces,
1141
- capabilities,
1142
- replacedRevoked,
1143
- via: "direct",
1144
- directoryCreated: false,
1145
- directoryDetail: "direct-to-postgres cannot reach a plugin namespace"
1146
- };
1147
- } finally {
1148
- await close();
1149
- }
1150
- }
1151
- /**
1152
- * Register a key through the admin-gated `POST /substrate/v1/_system/keys` route,
1153
- * which needs an `admin` identity rather than postgres write access, and
1154
- * writes the directory row in the same transaction. Throws `AdminCliError`
1155
- * on a non-2xx response.
1156
- */
1157
- async function runRegisterViaRoute(args, baseUrl, env, fetchImpl = fetch) {
1158
- if (grantEntriesConfer(args.namespaces, args.capabilities, "admin") && !args.allowAdmin) throw new AdminCliError("register: 'admin' capability requires --allow-admin (bootstrap is the deliberate admin path)", 1);
1159
- const publicKeyPem = readEd25519PublicKey(args.pubkeyPath);
1160
- const fingerprint = `sha256:${base64Url(createHash("sha256").update(publicKeyPem).digest()).slice(0, 8)}`;
1161
- const auth = resolveAdminAuth(env, baseUrl);
1162
- if ("error" in auth) throw new AdminCliError(`register: ${auth.error}`, 1);
1163
- const directoryParams = {};
1164
- if (args.noBroadcast) directoryParams.broadcastEligible = false;
1165
- if (args.project !== null) directoryParams.project = args.project;
1166
- const body = {
1167
- kid: args.kid,
1168
- publicKey: publicKeyPem,
1169
- name: args.name,
1170
- algorithm: "EdDSA",
1171
- namespaces: args.namespaces,
1172
- capabilities: args.capabilities,
1173
- allowAdmin: args.allowAdmin,
1174
- allowUnknownNs: args.allowUnknownNs,
1175
- directory: {
1176
- create: !args.noDirectory,
1177
- ...Object.keys(directoryParams).length > 0 ? { params: directoryParams } : {}
1178
- }
1179
- };
1180
- const url = `${baseUrl.replace(/\/+$/, "")}/substrate/v1/_system/keys`;
1181
- let res;
1182
- try {
1183
- res = await fetchImpl(url, {
1184
- method: "POST",
1185
- headers: {
1186
- "content-type": "application/json",
1187
- authorization: auth.ok
1188
- },
1189
- body: JSON.stringify(body),
1190
- redirect: "error"
1191
- });
1192
- } catch (err) {
1193
- const msg = err instanceof Error ? err.message : String(err);
1194
- throw new AdminCliError(`register: could not reach ${url}: ${msg}. Pass --direct to write to postgres instead (break-glass; leaves no directory row).`, 2);
1195
- }
1196
- const text = await res.text();
1197
- let parsed = null;
1198
- try {
1199
- parsed = JSON.parse(text);
1200
- } catch {}
1201
- if (!res.ok) {
1202
- const code = typeof parsed?.code === "string" ? parsed.code : `http_${res.status}`;
1203
- const message = typeof parsed?.message === "string" ? parsed.message : text.slice(0, 500);
1204
- if (res.status === 404) throw new AdminCliError(`register: ${url} returned 404 — this server predates the keys route. Upgrade it, or pass --direct.`, 2);
1205
- throw new AdminCliError(`register: ${code}: ${message}`, 3);
1206
- }
1207
- const dir = parsed?.directory ?? {};
1208
- return {
1209
- kid: typeof parsed?.kid === "string" ? parsed.kid : args.kid,
1210
- name: args.name,
1211
- fingerprint: typeof parsed?.fingerprint === "string" ? parsed.fingerprint : fingerprint,
1212
- namespaces: encodeList(args.namespaces),
1213
- capabilities: encodeList(args.capabilities),
1214
- replacedRevoked: parsed?.replacedRevoked === true,
1215
- via: "route",
1216
- directoryCreated: dir.created === true,
1217
- directoryDetail: dir.created === true ? typeof dir.frame === "string" ? dir.frame : "created" : typeof dir.reason === "string" ? dir.reason : "not created"
1218
- };
1219
- }
1220
- function formatRegisterOutput(result, opts = {}) {
1221
- const lines = [
1222
- "substrate-admin register complete.",
1223
- `kid: ${result.kid}`,
1224
- `name: ${result.name}`,
1225
- `fingerprint: ${result.fingerprint}`,
1226
- ...grantLines("grant: ", result.namespaces, result.capabilities),
1227
- ` (stored as: namespaces='${result.namespaces}' capabilities='${result.capabilities}')`,
1228
- `transport: ${result.via === "route" ? "POST /substrate/v1/_system/keys" : "direct-to-postgres (--direct)"}`,
1229
- `directory row: ${result.directoryCreated ? `created in ${result.directoryDetail}` : `NOT created — ${result.directoryDetail}`}`
1230
- ];
1231
- if (result.replacedRevoked) lines.push("re-registered over a previously-revoked kid.");
1232
- lines.push("");
1233
- if (result.via === "route") {
1234
- lines.push("This build refreshes the key registry post-commit, so no restart should be needed.");
1235
- lines.push("Verify before relying on it: mint a token with this kid's private key and call /substrate/v1/whoami.");
1236
- } else lines.push("A RUNNING binary will not see this key until its registry re-primes —", "restart it (e.g. `sudo systemctl restart substrate-binary`) for the key to verify.");
1237
- if (!result.directoryCreated && opts.adminRoot === true) lines.push("", "No directory row, by design: admin roots are exempt by capability, like the bootstrap key.");
1238
- else if (!result.directoryCreated) lines.push("", "WARNING: this identity has a credential but NO directory row. It will", "authenticate normally and be invisible to fleet listing and mail routing.", result.via === "direct" ? "Re-run without --direct (or with --url) to write both rows in one transaction." : result.directoryDetail === "not_configured" ? "This deployment has no identity directory configured, so there is nowhere to write one. Expected for a substrate with no mailbox; alarming for a fleet member. Configure SUBSTRATE_AGENT_DIRECTORY_TYPE if it should have one." : "Create the directory row by hand, or re-run without --no-directory.");
1239
- lines.push("");
1240
- return lines.join("\n");
1241
- }
1242
-
1243
- //#endregion
1244
- //#region src/admin/commands/onboard.ts
1245
- /**
1246
- * `substrate-admin onboard` — guided onboarding. Runs diagnose, plans the steps,
1247
- * stops at the first one still to do, and offers to run its fix when a client
1248
- * can. Every action is confirmed; nothing runs unattended.
1249
- */
1250
- function formatChecklist(steps) {
1251
- const current = currentStep(steps);
1252
- const width = Math.max(...steps.map((s) => s.name.length));
1253
- return `${steps.map((s) => {
1254
- const mark = s === current ? "▶" : STEP_MARKS[s.status];
1255
- const tag = s.optional ? " (optional)" : "";
1256
- return ` ${mark} ${s.name.padEnd(width)} ${s.detail}${tag}`;
1257
- }).join("\n")}\n`;
1258
- }
1259
- function describeAction(action, store, adminCapability) {
1260
- switch (action.kind) {
1261
- case "bootstrap": return `substrate-admin bootstrap — writes straight to SUBSTRATE_DATABASE_URL=${store ?? "(unset)"}. It must be the same database the server you named serves; nothing here can check that.`;
1262
- case "register-admin": return `substrate-admin register <kid> --pubkey <path> --ns '*' --caps ${seedCapabilities(adminCapability).join(",")} --allow-admin --no-directory`;
1263
- case "register-agent": return "substrate-admin register <kid> --pubkey <path> --ns <namespace,…>";
1264
- case "revoke": return action.kids.map((k) => `substrate-admin revoke ${k}`).join(" && ");
1265
- }
1266
- }
1267
- /** Thrown when input ends mid-action; the loop turns it into a quit. */
1268
- var EndOfInput = class extends Error {};
1269
- async function need(io, prompt) {
1270
- const line = await io.ask(prompt);
1271
- if (line === null) throw new EndOfInput();
1272
- return line.trim();
1273
- }
1274
- /** Asks for a public key, offering to generate a keypair when the operator has none. */
1275
- async function publicKeyPath(io, actions, kid) {
1276
- const given = await need(io, "public key path (Enter to generate a keypair here): ");
1277
- if (given.length > 0) return given;
1278
- io.out("A private key must live with whoever will use it, and never travel. Generate it on the machine that will sign with it.\n");
1279
- const target = await need(io, "write the new private key to (Enter to cancel): ");
1280
- if (target.length === 0) return null;
1281
- const written = actions.generateKeypair(target, kid);
1282
- io.out(`wrote ${written.privateKeyPath} (0600) and ${written.publicKeyPath}\n`);
1283
- if (written.kidPath !== void 0) io.out(`wrote ${written.kidPath} — point the signing-key variable at the private key and the kid is read from beside it.
1284
- `);
1285
- return written.publicKeyPath;
1286
- }
1287
- /** Runs one action. Returns the output to show, or null when the operator cancelled. */
1288
- async function perform(action, io, actions) {
1289
- switch (action.kind) {
1290
- case "bootstrap": return actions.bootstrap();
1291
- case "register-admin": {
1292
- const kid = await need(io, "kid for the second admin: ");
1293
- if (kid.length === 0) return null;
1294
- const pub = await publicKeyPath(io, actions, kid);
1295
- return pub === null ? null : actions.registerAdmin(kid, pub);
1296
- }
1297
- case "register-agent": {
1298
- const kid = await need(io, "kid for the agent (e.g. myrepo-claude@host): ");
1299
- if (kid.length === 0) return null;
1300
- const pub = await publicKeyPath(io, actions, kid);
1301
- if (pub === null) return null;
1302
- const ns = await need(io, "grant namespaces (comma-separated): ");
1303
- const namespaces = ns.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
1304
- if (namespaces.length === 0) {
1305
- io.out("a namespace is required\n");
1306
- return null;
1307
- }
1308
- const grantError = grantEntryError(namespaces, ["read", "mutate"]);
1309
- if (grantError !== null) {
1310
- io.out(`grant '${ns}' refused: ${grantError}\n`);
1311
- return null;
1312
- }
1313
- return actions.registerAgent(kid, pub, namespaces);
1314
- }
1315
- case "revoke": {
1316
- const done = [];
1317
- for (const kid of action.kids) {
1318
- const typed = await need(io, `type '${kid}' to revoke it: `);
1319
- if (typed !== kid) {
1320
- io.out(`'${typed}' did not match — ${kid} left alone\n`);
1321
- continue;
1322
- }
1323
- try {
1324
- done.push(await actions.revoke(kid));
1325
- } catch (err) {
1326
- done.push(`failed: ${kid}: ${err instanceof Error ? err.message : String(err)}`);
1327
- }
1328
- }
1329
- return done.length > 0 ? done.join("\n") : null;
1330
- }
1331
- }
1332
- }
1333
- function summary(steps, stopped) {
1334
- const skipped = steps.filter((s) => s.status === "skipped").map((s) => s.name);
1335
- const blocked = steps.filter((s) => s.status === "blocked").map((s) => s.name);
1336
- const lines = [stopped ? "onboarding stopped before it finished." : requiredOutstanding(steps) ? "onboarding has required steps outstanding." : "onboarding complete."];
1337
- if (skipped.length > 0) lines.push(`skipped: ${skipped.join(", ")}`);
1338
- if (blocked.length > 0) lines.push(`not checked: ${blocked.join(", ")}`);
1339
- return `\n${lines.join("\n")}\n`;
1340
- }
1341
- async function runOnboard(opts) {
1342
- const { io, actions } = opts;
1343
- const adminCapability = opts.adminCapability ?? "admin";
1344
- const skipped = /* @__PURE__ */ new Set();
1345
- let declined = null;
1346
- for (;;) {
1347
- let result;
1348
- try {
1349
- result = await opts.diagnose();
1350
- } catch (err) {
1351
- io.out(`diagnose failed: ${err instanceof Error ? err.message : String(err)}\n`);
1352
- return 2;
1353
- }
1354
- const steps = planOnboarding(result, {
1355
- canBootstrap: opts.canBootstrap,
1356
- skipped
1357
- });
1358
- io.out(`\n${formatChecklist(steps)}`);
1359
- const step = currentStep(steps);
1360
- const exitCode = requiredOutstanding(steps) ? 1 : 0;
1361
- if (step === void 0 || !opts.interactive) {
1362
- io.out(summary(steps, false));
1363
- return exitCode;
1364
- }
1365
- if (declined !== step.name) declined = null;
1366
- io.out(`\n${step.name}: ${step.detail}\n`);
1367
- try {
1368
- if (step.action !== void 0 && declined === null) {
1369
- io.out(` would run: ${describeAction(step.action, opts.bootstrapStore, adminCapability)}\n`);
1370
- if ((await need(io, "Run it? [y/N] ")).toLowerCase() === "y") {
1371
- try {
1372
- const output = await perform(step.action, io, actions);
1373
- if (output !== null) io.out(`${output}\n`);
1374
- } catch (err) {
1375
- if (err instanceof EndOfInput) throw err;
1376
- io.out(`failed: ${err instanceof Error ? err.message : String(err)}\n`);
1377
- }
1378
- continue;
1379
- }
1380
- declined = step.name;
1381
- }
1382
- if (step.fix !== void 0) io.out(` fix: ${step.fix}\n`);
1383
- const offerRun = step.action !== void 0 && declined === step.name;
1384
- const choice = (await need(io, `Enter re-checks${offerRun ? ", r runs the fix" : ""}${step.skippable ? ", s skips" : ""}, q quits: `)).toLowerCase();
1385
- if (choice === "q") {
1386
- io.out(summary(steps, true));
1387
- return exitCode;
1388
- }
1389
- if (choice === "r" && offerRun) declined = null;
1390
- if (choice === "s") {
1391
- if (SKIPPABLE_STEPS.has(step.name)) skipped.add(step.name);
1392
- else io.out(`${step.name} cannot be skipped\n`);
1393
- }
1394
- } catch (err) {
1395
- if (!(err instanceof EndOfInput)) throw err;
1396
- io.out(summary(steps, true));
1397
- return exitCode;
1398
- }
1399
- }
1400
- }
1401
- /** A postgres URL fit to print: the password is never echoed. */
1402
- function redactStore(url) {
1403
- let u;
1404
- try {
1405
- u = new URL(url);
1406
- } catch {
1407
- return "(an unparseable postgres URL)";
1408
- }
1409
- const auth = u.username.length > 0 ? `${u.username}${u.password.length > 0 ? ":***" : ""}@` : "";
1410
- return `${u.protocol}//${auth}${u.host}${u.pathname}`;
1411
- }
1412
- function registerArgs(kid, pubkeyPath, over) {
1413
- return {
1414
- kid,
1415
- pubkeyPath,
1416
- name: kid,
1417
- namespaces: [],
1418
- capabilities: ["read", "mutate"],
1419
- allowAdmin: false,
1420
- allowUnknownNs: false,
1421
- url: null,
1422
- noDirectory: false,
1423
- noBroadcast: false,
1424
- project: null,
1425
- ...over
1426
- };
1427
- }
1428
- /** The production action runners: the same functions the standalone subcommands call. */
1429
- function realOnboardActions(env, baseUrl, fetchImpl = fetch) {
1430
- const cap = env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? env.SUBSTRATE_ADMIN_CAPABILITY : DEFAULT_ADMIN_CAPABILITY;
1431
- return {
1432
- bootstrap: async () => formatBootstrapOutput(await runBootstrap(env)),
1433
- registerAdmin: async (kid, pub) => formatRegisterOutput(await runRegisterViaRoute(registerArgs(kid, pub, {
1434
- namespaces: ["*"],
1435
- capabilities: seedCapabilities(cap),
1436
- allowAdmin: true,
1437
- noDirectory: true
1438
- }), baseUrl, env, fetchImpl), { adminRoot: true }),
1439
- registerAgent: async (kid, pub, namespaces) => formatRegisterOutput(await runRegisterViaRoute(registerArgs(kid, pub, { namespaces: [...namespaces] }), baseUrl, env, fetchImpl)),
1440
- revoke: async (kid) => {
1441
- await runKeyPatchViaRoute({
1442
- kid,
1443
- revoke: true
1444
- }, baseUrl, env, REVOKE_EXIT_CODES, fetchImpl);
1445
- return `revoked ${kid}`;
1446
- },
1447
- generateKeypair: (path, kid) => writeKeypair(env, path, kid)
1448
- };
1449
- }
1450
- /** Parse argv, resolve the target, and run — the shape `main` dispatches to. */
1451
- async function onboardCommand(argv, env, io, interactive, fetchImpl = fetch) {
1452
- validateArgv("onboard", argv);
1453
- let url;
1454
- let direct = false;
1455
- let check = false;
1456
- for (let i = 0; i < argv.length; i++) {
1457
- const tok = argv[i];
1458
- if (tok === "--url") {
1459
- if (url !== void 0) throw argvError("onboard", "onboard: --url specified more than once", 1);
1460
- url = argv[i + 1] ?? "";
1461
- i += 1;
1462
- } else if (tok === "--direct") direct = true;
1463
- else if (tok === "--check") check = true;
1464
- }
1465
- const target = resolveAdminTarget(direct ? "" : url ?? null, env);
1466
- if (target.kind !== "route") {
1467
- io.out(formatDoctorReport({
1468
- checks: [DIRECT_TARGET_REFUSAL],
1469
- exitCode: 1
1470
- }));
1471
- return 1;
1472
- }
1473
- const store = env.SUBSTRATE_DATABASE_URL ?? "";
1474
- const canBootstrap = (store.startsWith("postgres://") || store.startsWith("postgresql://")) && bootstrapBlockers(env).length === 0;
1475
- return runOnboard({
1476
- diagnose: () => diagnoseTarget(env, target.baseUrl, fetchImpl),
1477
- canBootstrap,
1478
- ...canBootstrap ? { bootstrapStore: redactStore(store) } : {},
1479
- ...env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? { adminCapability: env.SUBSTRATE_ADMIN_CAPABILITY } : {},
1480
- interactive: interactive && !check,
1481
- io,
1482
- actions: realOnboardActions(env, target.baseUrl, fetchImpl)
1483
- });
1484
- }
1485
-
1486
- //#endregion
1487
- //#region src/admin/dataset.ts
1488
- /**
1489
- * Direct-to-pg dataset opener shared by every CLI path that writes `_system`
1490
- * rows without going through the running binary, including
1491
- * `substrate federate enroll`.
1492
- *
1493
- * It never migrates: only `bootstrap` and the server change the schema. A
1494
- * store missing a migration this CLI knows is refused.
1495
- */
1496
- async function openPgDataset(env, openSql$1 = openSql) {
1497
- const storeSpec = env.SUBSTRATE_DATABASE_URL;
1498
- if (storeSpec === void 0 || storeSpec.length === 0) throw new AdminCliError("SUBSTRATE_DATABASE_URL is required (must be a postgres:// URL)");
1499
- if (!storeSpec.startsWith("postgres://") && !storeSpec.startsWith("postgresql://")) throw new AdminCliError(`SUBSTRATE_DATABASE_URL must be a postgres:// URL (got '${redactStore(storeSpec)}'). Memory-backed stores cannot persist admin state across restarts.`);
1500
- const sql = openSql$1(storeSpec);
1501
- let pending;
1502
- try {
1503
- pending = await pendingMigrations(sql);
1504
- } catch (err) {
1505
- await closeQuietly(sql);
1506
- throw err;
1507
- }
1508
- if (pending.length > 0) {
1509
- await closeQuietly(sql);
1510
- throw new AdminCliError(`the store at SUBSTRATE_DATABASE_URL is missing migration(s) ${pending.join(", ")}. This command does not migrate: start the server (or run bootstrap) against it, or use a substrate-admin matching the server version.`);
1511
- }
1512
- return {
1513
- dataset: new PgDataset({
1514
- namespace: SYSTEM_NAMESPACE,
1515
- sql
1516
- }),
1517
- close: () => closeQuietly(sql)
1518
- };
1519
- }
1520
- async function closeQuietly(sql) {
1521
- try {
1522
- await sql.end();
1523
- } catch {}
1524
- }
1525
-
1526
- //#endregion
1527
- export { describeAdminTarget as A, version as B, CLI_ACTOR_KID as C, listActiveAdminKeys as D, generateAdminKeypair as E, RESTART_NOTE as F, USAGE as I, argvError as L, resolveAdminTarget as M, ARGV_SPEC as N, readEd25519PublicKey as O, validateArgv as P, openSql as R, BootstrapError as S, forUpdate as T, REVOKE_EXIT_CODES as _, formatRegisterOutput as a, runKeyPatchViaRoute as b, runRegisterViaRoute as c, formatDoctorReport as d, runDoctor as f, bootstrapKidPath as g, runBootstrap as h, runOnboard as i, resolveAdminAuth as j, readKeyById as k, grantLines as l, parseBootstrapArgs as m, formatChecklist as n, parseRegisterArgs as o, formatBootstrapOutput as p, onboardCommand as r, runRegister as s, openPgDataset as t, doctorCommand as u, UPDATE_EXIT_CODES as v, base64Url as w, ACTOR_HINT as x, runKeyListViaRoute as y, AdminCliError as z };