@mnmal-ai/substrate 1.0.0-alpha.1 → 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.
- package/README.md +48 -6
- package/dist/boot-store-BVqfFxh1.js +4060 -0
- package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-Cp4PaIYO.d.ts} +2 -87
- package/dist/cli-hSCBywhE.js +3126 -0
- package/dist/client.d.ts +130 -8
- package/dist/client.js +6 -5
- package/dist/{plugin-t2g2wX0b.d.ts → dataset-CejF-Fr_.d.ts} +1640 -1320
- package/dist/{agent-token-BIboWOU0.js → env-utils-CGNazUNt.js} +31 -2
- package/dist/{errors-D4vKuwz8.d.ts → errors-7mycvNGq.d.ts} +1 -1
- package/dist/{index-D7mSOFlM.d.ts → index-DgSfwx7M.d.ts} +1 -1
- package/dist/node-version-C5FSmwJX.js +26 -0
- package/dist/pack.d.ts +2 -2
- package/dist/pack.js +1 -1
- package/dist/pg-edges-store-Lxsl5ZnK.js +381 -0
- package/dist/{plugin-BuQQEzL-.js → plugin-CtwOINCM.js} +171 -18
- package/dist/proposals-bootstrap.js +6 -4
- package/dist/proposals.config.schema.json +5 -0
- package/dist/proposals.d.ts +15 -4
- package/dist/proposals.default-config.json +2 -1
- package/dist/proposals.js +2 -2
- package/dist/recall-bootstrap.js +13 -4
- package/dist/recall.config.schema.json +12 -0
- package/dist/recall.d.ts +54 -9
- package/dist/recall.js +2 -2
- package/dist/{repl-C52wyfMs.js → repl-DqfHelK7.js} +62 -29
- package/dist/{row-ByLFE2Wx.d.ts → row-BKKCXIG6.d.ts} +5 -3
- package/dist/run-B5dTbZ3g.js +1997 -0
- package/dist/{schema-g4FQLr0V.d.ts → schema-DoSc-4ig.d.ts} +44 -7
- package/dist/script-C6DSa_Na.js +134 -0
- package/dist/sdk.d.ts +90 -12
- package/dist/sdk.js +5 -110
- package/dist/{src-YXlv_RyL.js → src-5SJ5GEIM.js} +1555 -326
- package/dist/{src-DuopV8u7.js → src-7CUSMK66.js} +148 -19
- package/dist/{src-zcyUofMJ.js → src-Bi849yhn.js} +39 -15
- package/dist/{src-5hVbeiAu.js → src-CqT-QWZ_.js} +697 -57
- package/dist/src-CyvV7dCK.js +4333 -0
- package/dist/{row-DK7lPZVe.js → src-Da0t6si5.js} +11 -11
- package/dist/{src-C4DzaIQZ.js → src-hZb8wfvg.js} +12 -1
- package/dist/substrate-admin.js +17 -781
- package/dist/substrate.js +4 -5476
- package/dist/testing.d.ts +557 -8
- package/dist/testing.js +39 -3
- package/dist/{ws-C72iVS5T.d.ts → ws-ByZyHk7m.d.ts} +3 -3
- package/package.json +21 -20
- package/dist/dataset-DOXGRz50.js +0 -1535
- package/dist/env-utils-B7SGmoeJ.js +0 -21
- package/dist/src-CjEwiKXw.js +0 -2327
package/dist/dataset-DOXGRz50.js
DELETED
|
@@ -1,1535 +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-YXlv_RyL.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-CjEwiKXw.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.1";
|
|
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 = failureText(payload, 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 = failureText(payload, 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
|
-
/** A refusal body as one line: its `message`, else `code (reason): detail`, else the status. */
|
|
631
|
-
function failureText(payload, status) {
|
|
632
|
-
if (typeof payload.message === "string") return payload.message;
|
|
633
|
-
if (typeof payload.code !== "string") return `HTTP ${status}`;
|
|
634
|
-
const reason = typeof payload.reason === "string" ? ` (${payload.reason})` : "";
|
|
635
|
-
const detail = typeof payload.detail === "string" ? `: ${payload.detail}` : "";
|
|
636
|
-
return `${payload.code}${reason}${detail}`;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
//#endregion
|
|
640
|
-
//#region src/admin/env.ts
|
|
641
|
-
/**
|
|
642
|
-
* Where the admin CLI's key files live, and the env it reads them from.
|
|
643
|
-
*
|
|
644
|
-
* These resolvers live together because they answer one question — *which
|
|
645
|
-
* file is this deployment's admin identity?* — and `bootstrap` (the writer)
|
|
646
|
-
* and `resolveAdminAuth` (the reader) must agree on it.
|
|
647
|
-
*/
|
|
648
|
-
/**
|
|
649
|
-
* Where `bootstrap` writes the kid. Beside the key when one was named
|
|
650
|
-
* explicitly, else the default path.
|
|
651
|
-
*/
|
|
652
|
-
function bootstrapKidPath(env) {
|
|
653
|
-
return env.SUBSTRATE_ADMIN_KEY_PATH !== void 0 && env.SUBSTRATE_ADMIN_KEY_PATH.length > 0 ? `${resolveDefaultKeyPath(env).replace(/\.key$/, "")}.kid` : resolveDefaultKidPath(env);
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
//#endregion
|
|
657
|
-
//#region src/admin/commands/bootstrap.ts
|
|
658
|
-
/**
|
|
659
|
-
* `bootstrap` — seed the genesis admin Key on a fresh `_system` namespace.
|
|
660
|
-
*
|
|
661
|
-
* The one subcommand that CANNOT go through the route: it exists to create the
|
|
662
|
-
* first admin identity, so there is none to present. Direct-to-postgres is not
|
|
663
|
-
* a legacy path here, it is the only possible one.
|
|
664
|
-
*/
|
|
665
|
-
/**
|
|
666
|
-
* What the genesis row grants: the admin capability plus `read` / `mutate`.
|
|
667
|
-
*
|
|
668
|
-
* `resolveAdminAuth` mints with `adminClaimCapabilities`, a superset of this
|
|
669
|
-
* row for any `adminCapability`, and `auth.ts` intersects that claim against
|
|
670
|
-
* the row, so the row is the ceiling. Derived from the same constant so the
|
|
671
|
-
* two cannot drift; `admin` alone does not satisfy the per-frame `read` /
|
|
672
|
-
* `mutate` gates.
|
|
673
|
-
*/
|
|
674
|
-
function seedCapabilities(adminCapability) {
|
|
675
|
-
return [...ADMIN_CAPABILITIES.filter((c) => c !== DEFAULT_ADMIN_CAPABILITY), adminCapability];
|
|
676
|
-
}
|
|
677
|
-
/**
|
|
678
|
-
* Perform the bootstrap.
|
|
679
|
-
*
|
|
680
|
-
* `wantsEncrypt` controls whether the on-disk private-key PEM is
|
|
681
|
-
* PBES2-encrypted with `SUBSTRATE_ADMIN_KEY_PASSPHRASE`. Defaults to false.
|
|
682
|
-
*/
|
|
683
|
-
async function runBootstrap(env, wantsEncrypt = false, openSql = postgres) {
|
|
684
|
-
const storeSpec = env.SUBSTRATE_DATABASE_URL;
|
|
685
|
-
if (storeSpec === void 0 || storeSpec.length === 0) throw new BootstrapError("SUBSTRATE_DATABASE_URL is required (must be a postgres:// URL)");
|
|
686
|
-
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.`);
|
|
687
|
-
const adminCapability = env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? env.SUBSTRATE_ADMIN_CAPABILITY : DEFAULT_ADMIN_CAPABILITY;
|
|
688
|
-
const seededCapabilities = seedCapabilities(adminCapability);
|
|
689
|
-
const privateKeyPath = resolveDefaultKeyPath(env);
|
|
690
|
-
if (existsSync(privateKeyPath)) throw new BootstrapError(`private key path '${privateKeyPath}' already exists — move it aside and retry`);
|
|
691
|
-
const kidPath = bootstrapKidPath(env);
|
|
692
|
-
if (existsSync(kidPath)) throw new BootstrapError(`kid path '${kidPath}' already exists — move it aside and retry`);
|
|
693
|
-
const { publicKeyPem, privateKeyPem, encrypted } = generateAdminKeypair(env, wantsEncrypt);
|
|
694
|
-
const sql = openSql(storeSpec);
|
|
695
|
-
let dataset;
|
|
696
|
-
try {
|
|
697
|
-
await runMigrations(sql);
|
|
698
|
-
dataset = new PgDataset({
|
|
699
|
-
namespace: SYSTEM_NAMESPACE,
|
|
700
|
-
sql
|
|
701
|
-
});
|
|
702
|
-
return await dataset.withAdvisoryLock("substrate:bootstrap", async () => {
|
|
703
|
-
const existing = await firstAdminKey(dataset, adminCapability);
|
|
704
|
-
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.`);
|
|
705
|
-
const kid = randomUUID();
|
|
706
|
-
const shaFull = createHash("sha256").update(publicKeyPem).digest();
|
|
707
|
-
const fingerprint = `sha256:${base64Url(shaFull).slice(0, 8)}`;
|
|
708
|
-
const parentDir = dirname(privateKeyPath);
|
|
709
|
-
mkdirSync(parentDir, {
|
|
710
|
-
recursive: true,
|
|
711
|
-
mode: 448
|
|
712
|
-
});
|
|
713
|
-
writeFileSync(privateKeyPath, privateKeyPem, {
|
|
714
|
-
mode: 384,
|
|
715
|
-
flag: "wx"
|
|
716
|
-
});
|
|
717
|
-
writeFileSync(kidPath, `${kid}\n`, {
|
|
718
|
-
mode: 384,
|
|
719
|
-
flag: "wx"
|
|
720
|
-
});
|
|
721
|
-
const now = /* @__PURE__ */ new Date();
|
|
722
|
-
await dataset.write("Key", [{
|
|
723
|
-
id: kid,
|
|
724
|
-
kid,
|
|
725
|
-
name: "bootstrap-admin",
|
|
726
|
-
algorithm: "EdDSA",
|
|
727
|
-
publicKey: publicKeyPem,
|
|
728
|
-
namespaces: "*",
|
|
729
|
-
capabilities: encodeList(seededCapabilities),
|
|
730
|
-
revokedAt: null
|
|
731
|
-
}], {
|
|
732
|
-
identity: {
|
|
733
|
-
kind: "system",
|
|
734
|
-
id: "bootstrap"
|
|
735
|
-
},
|
|
736
|
-
now
|
|
737
|
-
});
|
|
738
|
-
return {
|
|
739
|
-
kid,
|
|
740
|
-
fingerprint,
|
|
741
|
-
privateKeyPath,
|
|
742
|
-
namespaces: "*",
|
|
743
|
-
capabilities: seededCapabilities.join(","),
|
|
744
|
-
encrypted
|
|
745
|
-
};
|
|
746
|
-
});
|
|
747
|
-
} finally {
|
|
748
|
-
try {
|
|
749
|
-
await sql.end();
|
|
750
|
-
} catch {}
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
function formatBootstrapOutput(result) {
|
|
754
|
-
const encLabel = result.encrypted ? "encrypted: aes-256-cbc+pbes2" : "unencrypted";
|
|
755
|
-
return [
|
|
756
|
-
"substrate-admin bootstrap complete.",
|
|
757
|
-
`kid: ${result.kid}`,
|
|
758
|
-
`fingerprint: ${result.fingerprint}`,
|
|
759
|
-
`private key: ${result.privateKeyPath} (mode 0600, ${encLabel})`,
|
|
760
|
-
`namespaces: ${result.namespaces}`,
|
|
761
|
-
`capabilities: ${result.capabilities}`,
|
|
762
|
-
"",
|
|
763
|
-
`Use the private key to sign JWTs with kid=${result.kid} to authenticate as admin.`,
|
|
764
|
-
"",
|
|
765
|
-
RESTART_NOTE,
|
|
766
|
-
""
|
|
767
|
-
].join("\n");
|
|
768
|
-
}
|
|
769
|
-
function parseBootstrapArgs(argv) {
|
|
770
|
-
try {
|
|
771
|
-
return parseBootstrapArgsInner(argv);
|
|
772
|
-
} catch (err) {
|
|
773
|
-
if (err instanceof AdminCliError) throw argvError("bootstrap", err.message, err.exitCode);
|
|
774
|
-
throw err;
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
function parseBootstrapArgsInner(argv) {
|
|
778
|
-
const rest = argv.slice(1);
|
|
779
|
-
validateArgv("bootstrap", rest);
|
|
780
|
-
let wantsEncrypt = false;
|
|
781
|
-
for (const tok of rest) if (tok === "--encrypt") {
|
|
782
|
-
if (wantsEncrypt) throw new AdminCliError("bootstrap: --encrypt specified more than once", 1);
|
|
783
|
-
wantsEncrypt = true;
|
|
784
|
-
}
|
|
785
|
-
return { wantsEncrypt };
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
//#endregion
|
|
789
|
-
//#region src/admin/commands/doctor.ts
|
|
790
|
-
/**
|
|
791
|
-
* `substrate-admin doctor` — diagnoses an admin deployment through checks that
|
|
792
|
-
* can each answer NO.
|
|
793
|
-
*
|
|
794
|
-
* 1. **Route-only.** Every auth claim is checked through the running server;
|
|
795
|
-
* a direct postgres read never authenticates, so it cannot test auth.
|
|
796
|
-
* 2. **A SKIP is not an OK.** A check whose precondition failed renders as
|
|
797
|
-
* `skip` with the reason — never as a pass, and never omitted.
|
|
798
|
-
* 3. **Shared classifiers.** Admin checks use `isActiveAdminKeyRow` and
|
|
799
|
-
* `capabilitiesFor`, the same predicates the server's guards use, so the
|
|
800
|
-
* doctor cannot agree with a copy that has drifted from the guard.
|
|
801
|
-
*/
|
|
802
|
-
/** The NO a non-route target gets: doctor and onboard both refuse to measure through postgres. */
|
|
803
|
-
const DIRECT_TARGET_REFUSAL = {
|
|
804
|
-
name: "target",
|
|
805
|
-
status: "no",
|
|
806
|
-
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).",
|
|
807
|
-
fix: "Pass `--url <base>`, or set SUBSTRATE_URL, so the checks go through the server that is doing the refusing."
|
|
808
|
-
};
|
|
809
|
-
/**
|
|
810
|
-
* Runs every check against `target`, in dependency order. A failure
|
|
811
|
-
* short-circuits its dependants into explicit skips.
|
|
812
|
-
*/
|
|
813
|
-
async function runDoctor(env, target, fetchImpl = fetch) {
|
|
814
|
-
if (target.kind !== "route") return {
|
|
815
|
-
checks: [DIRECT_TARGET_REFUSAL, ...DIAGNOSE_CHECKS.map((name) => ({
|
|
816
|
-
name,
|
|
817
|
-
status: "skip",
|
|
818
|
-
detail: "not asked — target answered no"
|
|
819
|
-
}))],
|
|
820
|
-
exitCode: 1
|
|
821
|
-
};
|
|
822
|
-
const result = await diagnoseTarget(env, target.baseUrl, fetchImpl);
|
|
823
|
-
return {
|
|
824
|
-
checks: [{
|
|
825
|
-
name: "target",
|
|
826
|
-
status: "ok",
|
|
827
|
-
detail: describeAdminTarget("doctor", target).replace(/^doctor: /, "")
|
|
828
|
-
}, ...result.checks],
|
|
829
|
-
exitCode: result.exitCode
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
/** Diagnose `baseUrl` with the admin credential `env` resolves — shared by doctor and onboard. */
|
|
833
|
-
async function diagnoseTarget(env, baseUrl, fetchImpl = fetch) {
|
|
834
|
-
const auth = resolveAdminAuth(env, baseUrl);
|
|
835
|
-
return diagnose({
|
|
836
|
-
baseUrl,
|
|
837
|
-
credential: "error" in auth ? { error: auth.error } : {
|
|
838
|
-
authorization: () => auth.ok,
|
|
839
|
-
label: describeCredential(env)
|
|
840
|
-
},
|
|
841
|
-
...env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? { adminCapability: env.SUBSTRATE_ADMIN_CAPABILITY } : {},
|
|
842
|
-
fetch: (input, init) => fetchImpl(input, {
|
|
843
|
-
...init,
|
|
844
|
-
redirect: "error"
|
|
845
|
-
})
|
|
846
|
-
});
|
|
847
|
-
}
|
|
848
|
-
/** Which credential the run used, without printing any of it. */
|
|
849
|
-
function describeCredential(env) {
|
|
850
|
-
if (env.SUBSTRATE_ADMIN_TOKEN !== void 0 && env.SUBSTRATE_ADMIN_TOKEN.length > 0) return "SUBSTRATE_ADMIN_TOKEN";
|
|
851
|
-
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)`;
|
|
852
|
-
}
|
|
853
|
-
const GLYPH = {
|
|
854
|
-
ok: "ok ",
|
|
855
|
-
no: "NO ",
|
|
856
|
-
skip: "skip"
|
|
857
|
-
};
|
|
858
|
-
/**
|
|
859
|
-
* Renders the report. The trailer counts skips separately from passes so a
|
|
860
|
-
* reader cannot sum unasked checks into a verdict.
|
|
861
|
-
*/
|
|
862
|
-
function formatDoctorReport(report) {
|
|
863
|
-
const width = Math.max(...report.checks.map((c) => c.name.length));
|
|
864
|
-
const lines = ["substrate-admin doctor", ""];
|
|
865
|
-
for (const check of report.checks) {
|
|
866
|
-
lines.push(` ${GLYPH[check.status]} ${check.name.padEnd(width)} ${check.detail}`);
|
|
867
|
-
if (check.fix !== void 0) lines.push(` ${" ".repeat(width)} fix: ${check.fix}`);
|
|
868
|
-
}
|
|
869
|
-
const ok = report.checks.filter((c) => c.status === "ok").length;
|
|
870
|
-
const no = report.checks.filter((c) => c.status === "no").length;
|
|
871
|
-
const skipped = report.checks.filter((c) => c.status === "skip").length;
|
|
872
|
-
lines.push("", skipped > 0 ? `${ok} ok, ${no} failed, ${skipped} NOT ASKED (a skipped check is not a passing one).` : `${ok} ok, ${no} failed.`);
|
|
873
|
-
return `${lines.join("\n")}\n`;
|
|
874
|
-
}
|
|
875
|
-
/** Resolve the target and run — the shape `main` dispatches to. */
|
|
876
|
-
async function doctorCommand(argv, env, fetchImpl = fetch) {
|
|
877
|
-
validateArgv("doctor", argv);
|
|
878
|
-
let url;
|
|
879
|
-
let direct = false;
|
|
880
|
-
for (let i = 0; i < argv.length; i++) {
|
|
881
|
-
const tok = argv[i];
|
|
882
|
-
if (tok === void 0) continue;
|
|
883
|
-
if (tok === "--url") {
|
|
884
|
-
if (url !== void 0) throw argvError("doctor", "doctor: --url specified more than once", 1);
|
|
885
|
-
url = argv[i + 1] ?? "";
|
|
886
|
-
i += 1;
|
|
887
|
-
continue;
|
|
888
|
-
}
|
|
889
|
-
if (tok === "--direct") direct = true;
|
|
890
|
-
}
|
|
891
|
-
return runDoctor(env, resolveAdminTarget(direct ? "" : url ?? null, env), fetchImpl);
|
|
892
|
-
}
|
|
893
|
-
|
|
894
|
-
//#endregion
|
|
895
|
-
//#region src/admin/commands/onboard-keys.ts
|
|
896
|
-
/**
|
|
897
|
-
* Key-file helpers for onboarding: generating a keypair for the register steps, and
|
|
898
|
-
* knowing in advance when `bootstrap` would refuse. Both refuse to overwrite, like
|
|
899
|
-
* `bootstrap`: clobbering key material destroys an identity silently.
|
|
900
|
-
*/
|
|
901
|
-
/** `~` and `~/…` against HOME; a shell would have done this, a prompt does not. */
|
|
902
|
-
function expandHome(env, path) {
|
|
903
|
-
if (path !== "~" && !path.startsWith("~/")) return path;
|
|
904
|
-
return join(env.HOME ?? homedir(), path.slice(1));
|
|
905
|
-
}
|
|
906
|
-
/**
|
|
907
|
-
* Writes `<path>` (0600) and `<path>.pub`, plus `<path minus .key>.kid` when a kid is
|
|
908
|
-
* given — the file the credential resolver reads beside a named key. Creates missing
|
|
909
|
-
* parent directories 0700. On a failed write, removes whatever this call already wrote.
|
|
910
|
-
*/
|
|
911
|
-
function writeKeypair(env, path, kid) {
|
|
912
|
-
const privateKeyPath = expandHome(env, path);
|
|
913
|
-
const publicKeyPath = `${privateKeyPath}.pub`;
|
|
914
|
-
const kidPath = kid === void 0 ? void 0 : `${privateKeyPath.replace(/\.key$/, "")}.kid`;
|
|
915
|
-
const targets = [
|
|
916
|
-
privateKeyPath,
|
|
917
|
-
publicKeyPath,
|
|
918
|
-
...kidPath === void 0 ? [] : [kidPath]
|
|
919
|
-
];
|
|
920
|
-
for (const p of targets) if (existsSync(p)) throw new AdminCliError(`'${p}' already exists — choose another path`, 1);
|
|
921
|
-
const { publicKeyPem, privateKeyPem } = generateAdminKeypair(env, false);
|
|
922
|
-
mkdirSync(dirname(privateKeyPath), {
|
|
923
|
-
recursive: true,
|
|
924
|
-
mode: 448
|
|
925
|
-
});
|
|
926
|
-
const written = [];
|
|
927
|
-
try {
|
|
928
|
-
writeFileSync(privateKeyPath, privateKeyPem, {
|
|
929
|
-
mode: 384,
|
|
930
|
-
flag: "wx"
|
|
931
|
-
});
|
|
932
|
-
written.push(privateKeyPath);
|
|
933
|
-
writeFileSync(publicKeyPath, publicKeyPem, {
|
|
934
|
-
mode: 420,
|
|
935
|
-
flag: "wx"
|
|
936
|
-
});
|
|
937
|
-
written.push(publicKeyPath);
|
|
938
|
-
if (kidPath !== void 0 && kid !== void 0) writeFileSync(kidPath, `${kid}\n`, {
|
|
939
|
-
mode: 384,
|
|
940
|
-
flag: "wx"
|
|
941
|
-
});
|
|
942
|
-
} catch (err) {
|
|
943
|
-
for (const p of written) rmSync(p, { force: true });
|
|
944
|
-
throw err;
|
|
945
|
-
}
|
|
946
|
-
return {
|
|
947
|
-
privateKeyPath,
|
|
948
|
-
publicKeyPath,
|
|
949
|
-
...kidPath === void 0 ? {} : { kidPath }
|
|
950
|
-
};
|
|
951
|
-
}
|
|
952
|
-
/**
|
|
953
|
-
* The files whose presence makes `bootstrap` refuse — its own guards, checked without
|
|
954
|
-
* opening postgres, so onboard offers bootstrap only when it can succeed.
|
|
955
|
-
*/
|
|
956
|
-
function bootstrapBlockers(env) {
|
|
957
|
-
return [resolveDefaultKeyPath(env), bootstrapKidPath(env)].filter((p) => existsSync(p));
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
//#endregion
|
|
961
|
-
//#region src/admin/grant-display.ts
|
|
962
|
-
/**
|
|
963
|
-
* Rendering a stored grant as the AUTHORITY it confers, rather than as the two
|
|
964
|
-
* columns it happens to be stored in.
|
|
965
|
-
*
|
|
966
|
-
* The two columns only mean anything jointly: `capabilities` is the default
|
|
967
|
-
* for BARE `--ns` entries only, so `--ns 'notes:read'` with default
|
|
968
|
-
* capabilities `read,mutate` is a read-only grant, not a write grant.
|
|
969
|
-
*/
|
|
970
|
-
/**
|
|
971
|
-
* `describeGrant` laid out under a label, continuation lines aligned.
|
|
972
|
-
*
|
|
973
|
-
* The label is passed in rather than fixed so `register` and `update` can align
|
|
974
|
-
* the grant block with their own existing columns.
|
|
975
|
-
*/
|
|
976
|
-
function grantLines(label, namespaces, capabilities) {
|
|
977
|
-
const entries = describeGrant(namespaces, capabilities);
|
|
978
|
-
const pad = " ".repeat(label.length);
|
|
979
|
-
return entries.map((e, i) => `${i === 0 ? label : pad}${e}`);
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
//#endregion
|
|
983
|
-
//#region src/admin/commands/register.ts
|
|
984
|
-
/**
|
|
985
|
-
* `register` — add an existing ed25519 public key as an agent Key.
|
|
986
|
-
*
|
|
987
|
-
* `--ns` is REQUIRED and has no default, because a default here is an unbounded
|
|
988
|
-
* grant nobody chose. The route path also writes the directory row in the same
|
|
989
|
-
* transaction: a credential with no directory row keeps authenticating while
|
|
990
|
-
* mail routing and agent listing quietly break.
|
|
991
|
-
*/
|
|
992
|
-
/**
|
|
993
|
-
* Parse `register <kid> --pubkey <path> --ns <csv> [--name <n>] [--caps <csv>]
|
|
994
|
-
* [--allow-admin]`. Positional <kid> exactly once, single-valued flags.
|
|
995
|
-
* Defaults (kid as name, caps read,mutate) are resolved here; `--ns` has no
|
|
996
|
-
* default and its absence throws `AdminCliError`.
|
|
997
|
-
*/
|
|
998
|
-
function parseRegisterArgs(argv) {
|
|
999
|
-
try {
|
|
1000
|
-
return parseRegisterArgsInner(argv);
|
|
1001
|
-
} catch (err) {
|
|
1002
|
-
if (err instanceof AdminCliError) throw argvError("register", err.message, err.exitCode);
|
|
1003
|
-
throw err;
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
function parseRegisterArgsInner(argv) {
|
|
1007
|
-
const rest = argv.slice(1);
|
|
1008
|
-
validateArgv("register", rest);
|
|
1009
|
-
let kid;
|
|
1010
|
-
let pubkeyPath;
|
|
1011
|
-
let name;
|
|
1012
|
-
let nsCsv;
|
|
1013
|
-
let capsCsv;
|
|
1014
|
-
let allowAdmin = false;
|
|
1015
|
-
let allowUnknownNs = false;
|
|
1016
|
-
let url;
|
|
1017
|
-
let direct = false;
|
|
1018
|
-
let noDirectory = false;
|
|
1019
|
-
let noBroadcast = false;
|
|
1020
|
-
let project;
|
|
1021
|
-
const takeValue = (flag, i) => {
|
|
1022
|
-
const val = rest[i + 1];
|
|
1023
|
-
if (val === void 0 || val.length === 0 || val.startsWith("--")) throw new AdminCliError(`register: ${flag} requires a value`, 1);
|
|
1024
|
-
return val;
|
|
1025
|
-
};
|
|
1026
|
-
for (let i = 0; i < rest.length; i++) {
|
|
1027
|
-
const tok = rest[i];
|
|
1028
|
-
if (tok === void 0) continue;
|
|
1029
|
-
if (tok === "--pubkey") {
|
|
1030
|
-
if (pubkeyPath !== void 0) throw new AdminCliError("register: --pubkey specified more than once", 1);
|
|
1031
|
-
pubkeyPath = takeValue("--pubkey", i);
|
|
1032
|
-
i += 1;
|
|
1033
|
-
} else if (tok === "--name") {
|
|
1034
|
-
if (name !== void 0) throw new AdminCliError("register: --name specified more than once", 1);
|
|
1035
|
-
name = takeValue("--name", i);
|
|
1036
|
-
i += 1;
|
|
1037
|
-
} else if (tok === "--ns") {
|
|
1038
|
-
if (nsCsv !== void 0) throw new AdminCliError("register: --ns specified more than once", 1);
|
|
1039
|
-
nsCsv = takeValue("--ns", i);
|
|
1040
|
-
i += 1;
|
|
1041
|
-
} else if (tok === "--caps") {
|
|
1042
|
-
if (capsCsv !== void 0) throw new AdminCliError("register: --caps specified more than once", 1);
|
|
1043
|
-
capsCsv = takeValue("--caps", i);
|
|
1044
|
-
i += 1;
|
|
1045
|
-
} else if (tok === "--allow-admin") {
|
|
1046
|
-
if (allowAdmin) throw new AdminCliError("register: --allow-admin specified more than once", 1);
|
|
1047
|
-
allowAdmin = true;
|
|
1048
|
-
} else if (tok === "--allow-unknown-ns") allowUnknownNs = true;
|
|
1049
|
-
else if (tok === "--url") {
|
|
1050
|
-
if (direct) throw new AdminCliError("register: --direct and --url are mutually exclusive", 1);
|
|
1051
|
-
if (url !== void 0) throw new AdminCliError("register: --url specified more than once", 1);
|
|
1052
|
-
url = takeValue("--url", i);
|
|
1053
|
-
i += 1;
|
|
1054
|
-
} else if (tok === "--direct") {
|
|
1055
|
-
if (url !== void 0) throw new AdminCliError("register: --direct and --url are mutually exclusive", 1);
|
|
1056
|
-
direct = true;
|
|
1057
|
-
url = "";
|
|
1058
|
-
} else if (tok === "--no-directory") noDirectory = true;
|
|
1059
|
-
else if (tok === "--no-broadcast") noBroadcast = true;
|
|
1060
|
-
else if (tok === "--project") {
|
|
1061
|
-
if (project !== void 0) throw new AdminCliError("register: --project specified more than once", 1);
|
|
1062
|
-
project = takeValue("--project", i);
|
|
1063
|
-
i += 1;
|
|
1064
|
-
} else kid = tok;
|
|
1065
|
-
}
|
|
1066
|
-
if (kid === void 0 || kid.length === 0) throw new AdminCliError("register requires a <kid> positional arg", 1);
|
|
1067
|
-
if (pubkeyPath === void 0 || pubkeyPath.length === 0) throw new AdminCliError("register requires --pubkey <path>", 1);
|
|
1068
|
-
const splitCsv = (csv) => csv.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1069
|
-
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);
|
|
1070
|
-
const namespaces = splitCsv(nsCsv);
|
|
1071
|
-
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);
|
|
1072
|
-
const nsError = grantEntryError(namespaces, ["read", "mutate"]);
|
|
1073
|
-
if (nsError !== null) throw new AdminCliError(`register: ${nsError} — e.g. --ns inventory:read,notes:read+mutate`, 1);
|
|
1074
|
-
const capabilities = capsCsv === void 0 ? ["read", "mutate"] : splitCsv(capsCsv);
|
|
1075
|
-
return {
|
|
1076
|
-
kid,
|
|
1077
|
-
pubkeyPath,
|
|
1078
|
-
name: name ?? kid,
|
|
1079
|
-
namespaces,
|
|
1080
|
-
capabilities,
|
|
1081
|
-
allowAdmin,
|
|
1082
|
-
allowUnknownNs,
|
|
1083
|
-
url: url ?? null,
|
|
1084
|
-
noDirectory,
|
|
1085
|
-
noBroadcast,
|
|
1086
|
-
project: project ?? null
|
|
1087
|
-
};
|
|
1088
|
-
}
|
|
1089
|
-
/**
|
|
1090
|
-
* Register an existing Ed25519 public key as an agent Key row directly
|
|
1091
|
-
* in postgres, with one `key_registered` audit row written in the SAME tx.
|
|
1092
|
-
*
|
|
1093
|
-
* Unlike `bootstrap`/`rotate`, the kid is operator-chosen. The row id is a
|
|
1094
|
-
* freshly-minted UUID; the kid is the principal field stored separately. A
|
|
1095
|
-
* previously-revoked same-kid row is re-registered (same UUID id, clears
|
|
1096
|
-
* revokedAt). A LIVE same-kid row is refused — rotate/revoke is the path.
|
|
1097
|
-
*/
|
|
1098
|
-
async function runRegister(args, env, openDataset = openPgDataset) {
|
|
1099
|
-
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);
|
|
1100
|
-
const publicKeyPem = readEd25519PublicKey(args.pubkeyPath);
|
|
1101
|
-
const shaFull = createHash("sha256").update(publicKeyPem).digest();
|
|
1102
|
-
const fingerprint = `sha256:${base64Url(shaFull).slice(0, 8)}`;
|
|
1103
|
-
const namespaces = encodeList(args.namespaces);
|
|
1104
|
-
const capabilities = encodeList(args.capabilities);
|
|
1105
|
-
const { dataset, close } = await openDataset(env);
|
|
1106
|
-
try {
|
|
1107
|
-
const replacedRevoked = await dataset.withTransaction(async (tx) => {
|
|
1108
|
-
const { rows: existingRows } = await tx.read("Key", { where: { kid: { eq: args.kid } } });
|
|
1109
|
-
const existing = existingRows.find((r) => r.revokedAt == null) ?? existingRows[0];
|
|
1110
|
-
let wasRevoked = false;
|
|
1111
|
-
let rowId = randomUUID();
|
|
1112
|
-
if (existing !== void 0) {
|
|
1113
|
-
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);
|
|
1114
|
-
wasRevoked = true;
|
|
1115
|
-
rowId = existing.id;
|
|
1116
|
-
}
|
|
1117
|
-
const now = /* @__PURE__ */ new Date();
|
|
1118
|
-
await tx.write("Key", [{
|
|
1119
|
-
id: rowId,
|
|
1120
|
-
kid: args.kid,
|
|
1121
|
-
name: args.name,
|
|
1122
|
-
algorithm: "EdDSA",
|
|
1123
|
-
publicKey: publicKeyPem,
|
|
1124
|
-
namespaces,
|
|
1125
|
-
capabilities,
|
|
1126
|
-
revokedAt: null
|
|
1127
|
-
}], ACTOR_HINT);
|
|
1128
|
-
await tx.write(AUDIT_EVENT_TYPE, [buildAuditRow({
|
|
1129
|
-
actorKid: CLI_ACTOR_KID,
|
|
1130
|
-
kind: "key_registered",
|
|
1131
|
-
targetKid: args.kid,
|
|
1132
|
-
details: {
|
|
1133
|
-
kid: args.kid,
|
|
1134
|
-
name: args.name,
|
|
1135
|
-
namespaces,
|
|
1136
|
-
capabilities,
|
|
1137
|
-
fingerprint,
|
|
1138
|
-
replacedRevoked: wasRevoked
|
|
1139
|
-
},
|
|
1140
|
-
now
|
|
1141
|
-
})], ACTOR_HINT);
|
|
1142
|
-
return wasRevoked;
|
|
1143
|
-
});
|
|
1144
|
-
return {
|
|
1145
|
-
kid: args.kid,
|
|
1146
|
-
name: args.name,
|
|
1147
|
-
fingerprint,
|
|
1148
|
-
namespaces,
|
|
1149
|
-
capabilities,
|
|
1150
|
-
replacedRevoked,
|
|
1151
|
-
via: "direct",
|
|
1152
|
-
directoryCreated: false,
|
|
1153
|
-
directoryDetail: "direct-to-postgres cannot reach a plugin namespace"
|
|
1154
|
-
};
|
|
1155
|
-
} finally {
|
|
1156
|
-
await close();
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
/**
|
|
1160
|
-
* Register a key through the admin-gated `POST /substrate/v1/_system/keys` route,
|
|
1161
|
-
* which needs an `admin` identity rather than postgres write access, and
|
|
1162
|
-
* writes the directory row in the same transaction. Throws `AdminCliError`
|
|
1163
|
-
* on a non-2xx response.
|
|
1164
|
-
*/
|
|
1165
|
-
async function runRegisterViaRoute(args, baseUrl, env, fetchImpl = fetch) {
|
|
1166
|
-
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);
|
|
1167
|
-
const publicKeyPem = readEd25519PublicKey(args.pubkeyPath);
|
|
1168
|
-
const fingerprint = `sha256:${base64Url(createHash("sha256").update(publicKeyPem).digest()).slice(0, 8)}`;
|
|
1169
|
-
const auth = resolveAdminAuth(env, baseUrl);
|
|
1170
|
-
if ("error" in auth) throw new AdminCliError(`register: ${auth.error}`, 1);
|
|
1171
|
-
const directoryParams = {};
|
|
1172
|
-
if (args.noBroadcast) directoryParams.broadcastEligible = false;
|
|
1173
|
-
if (args.project !== null) directoryParams.project = args.project;
|
|
1174
|
-
const body = {
|
|
1175
|
-
kid: args.kid,
|
|
1176
|
-
publicKey: publicKeyPem,
|
|
1177
|
-
name: args.name,
|
|
1178
|
-
algorithm: "EdDSA",
|
|
1179
|
-
namespaces: args.namespaces,
|
|
1180
|
-
capabilities: args.capabilities,
|
|
1181
|
-
allowAdmin: args.allowAdmin,
|
|
1182
|
-
allowUnknownNs: args.allowUnknownNs,
|
|
1183
|
-
directory: {
|
|
1184
|
-
create: !args.noDirectory,
|
|
1185
|
-
...Object.keys(directoryParams).length > 0 ? { params: directoryParams } : {}
|
|
1186
|
-
}
|
|
1187
|
-
};
|
|
1188
|
-
const url = `${baseUrl.replace(/\/+$/, "")}/substrate/v1/_system/keys`;
|
|
1189
|
-
let res;
|
|
1190
|
-
try {
|
|
1191
|
-
res = await fetchImpl(url, {
|
|
1192
|
-
method: "POST",
|
|
1193
|
-
headers: {
|
|
1194
|
-
"content-type": "application/json",
|
|
1195
|
-
authorization: auth.ok
|
|
1196
|
-
},
|
|
1197
|
-
body: JSON.stringify(body),
|
|
1198
|
-
redirect: "error"
|
|
1199
|
-
});
|
|
1200
|
-
} catch (err) {
|
|
1201
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
1202
|
-
throw new AdminCliError(`register: could not reach ${url}: ${msg}. Pass --direct to write to postgres instead (break-glass; leaves no directory row).`, 2);
|
|
1203
|
-
}
|
|
1204
|
-
const text = await res.text();
|
|
1205
|
-
let parsed = null;
|
|
1206
|
-
try {
|
|
1207
|
-
parsed = JSON.parse(text);
|
|
1208
|
-
} catch {}
|
|
1209
|
-
if (!res.ok) {
|
|
1210
|
-
const code = typeof parsed?.code === "string" ? parsed.code : `http_${res.status}`;
|
|
1211
|
-
const message = typeof parsed?.message === "string" ? parsed.message : text.slice(0, 500);
|
|
1212
|
-
if (res.status === 404) throw new AdminCliError(`register: ${url} returned 404 — this server predates the keys route. Upgrade it, or pass --direct.`, 2);
|
|
1213
|
-
throw new AdminCliError(`register: ${code}: ${message}`, 3);
|
|
1214
|
-
}
|
|
1215
|
-
const dir = parsed?.directory ?? {};
|
|
1216
|
-
return {
|
|
1217
|
-
kid: typeof parsed?.kid === "string" ? parsed.kid : args.kid,
|
|
1218
|
-
name: args.name,
|
|
1219
|
-
fingerprint: typeof parsed?.fingerprint === "string" ? parsed.fingerprint : fingerprint,
|
|
1220
|
-
namespaces: encodeList(args.namespaces),
|
|
1221
|
-
capabilities: encodeList(args.capabilities),
|
|
1222
|
-
replacedRevoked: parsed?.replacedRevoked === true,
|
|
1223
|
-
via: "route",
|
|
1224
|
-
directoryCreated: dir.created === true,
|
|
1225
|
-
directoryDetail: dir.created === true ? typeof dir.frame === "string" ? dir.frame : "created" : typeof dir.reason === "string" ? dir.reason : "not created"
|
|
1226
|
-
};
|
|
1227
|
-
}
|
|
1228
|
-
function formatRegisterOutput(result, opts = {}) {
|
|
1229
|
-
const lines = [
|
|
1230
|
-
"substrate-admin register complete.",
|
|
1231
|
-
`kid: ${result.kid}`,
|
|
1232
|
-
`name: ${result.name}`,
|
|
1233
|
-
`fingerprint: ${result.fingerprint}`,
|
|
1234
|
-
...grantLines("grant: ", result.namespaces, result.capabilities),
|
|
1235
|
-
` (stored as: namespaces='${result.namespaces}' capabilities='${result.capabilities}')`,
|
|
1236
|
-
`transport: ${result.via === "route" ? "POST /substrate/v1/_system/keys" : "direct-to-postgres (--direct)"}`,
|
|
1237
|
-
`directory row: ${result.directoryCreated ? `created in ${result.directoryDetail}` : `NOT created — ${result.directoryDetail}`}`
|
|
1238
|
-
];
|
|
1239
|
-
if (result.replacedRevoked) lines.push("re-registered over a previously-revoked kid.");
|
|
1240
|
-
lines.push("");
|
|
1241
|
-
if (result.via === "route") {
|
|
1242
|
-
lines.push("This build refreshes the key registry post-commit, so no restart should be needed.");
|
|
1243
|
-
lines.push("Verify before relying on it: mint a token with this kid's private key and call /substrate/v1/whoami.");
|
|
1244
|
-
} 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.");
|
|
1245
|
-
if (!result.directoryCreated && opts.adminRoot === true) lines.push("", "No directory row, by design: admin roots are exempt by capability, like the bootstrap key.");
|
|
1246
|
-
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.");
|
|
1247
|
-
lines.push("");
|
|
1248
|
-
return lines.join("\n");
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
//#endregion
|
|
1252
|
-
//#region src/admin/commands/onboard.ts
|
|
1253
|
-
/**
|
|
1254
|
-
* `substrate-admin onboard` — guided onboarding. Runs diagnose, plans the steps,
|
|
1255
|
-
* stops at the first one still to do, and offers to run its fix when a client
|
|
1256
|
-
* can. Every action is confirmed; nothing runs unattended.
|
|
1257
|
-
*/
|
|
1258
|
-
function formatChecklist(steps) {
|
|
1259
|
-
const current = currentStep(steps);
|
|
1260
|
-
const width = Math.max(...steps.map((s) => s.name.length));
|
|
1261
|
-
return `${steps.map((s) => {
|
|
1262
|
-
const mark = s === current ? "▶" : STEP_MARKS[s.status];
|
|
1263
|
-
const tag = s.optional ? " (optional)" : "";
|
|
1264
|
-
return ` ${mark} ${s.name.padEnd(width)} ${s.detail}${tag}`;
|
|
1265
|
-
}).join("\n")}\n`;
|
|
1266
|
-
}
|
|
1267
|
-
function describeAction(action, store, adminCapability) {
|
|
1268
|
-
switch (action.kind) {
|
|
1269
|
-
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.`;
|
|
1270
|
-
case "register-admin": return `substrate-admin register <kid> --pubkey <path> --ns '*' --caps ${seedCapabilities(adminCapability).join(",")} --allow-admin --no-directory`;
|
|
1271
|
-
case "register-agent": return "substrate-admin register <kid> --pubkey <path> --ns <namespace,…>";
|
|
1272
|
-
case "revoke": return action.kids.map((k) => `substrate-admin revoke ${k}`).join(" && ");
|
|
1273
|
-
}
|
|
1274
|
-
}
|
|
1275
|
-
/** Thrown when input ends mid-action; the loop turns it into a quit. */
|
|
1276
|
-
var EndOfInput = class extends Error {};
|
|
1277
|
-
async function need(io, prompt) {
|
|
1278
|
-
const line = await io.ask(prompt);
|
|
1279
|
-
if (line === null) throw new EndOfInput();
|
|
1280
|
-
return line.trim();
|
|
1281
|
-
}
|
|
1282
|
-
/** Asks for a public key, offering to generate a keypair when the operator has none. */
|
|
1283
|
-
async function publicKeyPath(io, actions, kid) {
|
|
1284
|
-
const given = await need(io, "public key path (Enter to generate a keypair here): ");
|
|
1285
|
-
if (given.length > 0) return given;
|
|
1286
|
-
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");
|
|
1287
|
-
const target = await need(io, "write the new private key to (Enter to cancel): ");
|
|
1288
|
-
if (target.length === 0) return null;
|
|
1289
|
-
const written = actions.generateKeypair(target, kid);
|
|
1290
|
-
io.out(`wrote ${written.privateKeyPath} (0600) and ${written.publicKeyPath}\n`);
|
|
1291
|
-
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.
|
|
1292
|
-
`);
|
|
1293
|
-
return written.publicKeyPath;
|
|
1294
|
-
}
|
|
1295
|
-
/** Runs one action. Returns the output to show, or null when the operator cancelled. */
|
|
1296
|
-
async function perform(action, io, actions) {
|
|
1297
|
-
switch (action.kind) {
|
|
1298
|
-
case "bootstrap": return actions.bootstrap();
|
|
1299
|
-
case "register-admin": {
|
|
1300
|
-
const kid = await need(io, "kid for the second admin: ");
|
|
1301
|
-
if (kid.length === 0) return null;
|
|
1302
|
-
const pub = await publicKeyPath(io, actions, kid);
|
|
1303
|
-
return pub === null ? null : actions.registerAdmin(kid, pub);
|
|
1304
|
-
}
|
|
1305
|
-
case "register-agent": {
|
|
1306
|
-
const kid = await need(io, "kid for the agent (e.g. myrepo-claude@host): ");
|
|
1307
|
-
if (kid.length === 0) return null;
|
|
1308
|
-
const pub = await publicKeyPath(io, actions, kid);
|
|
1309
|
-
if (pub === null) return null;
|
|
1310
|
-
const ns = await need(io, "grant namespaces (comma-separated): ");
|
|
1311
|
-
const namespaces = ns.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1312
|
-
if (namespaces.length === 0) {
|
|
1313
|
-
io.out("a namespace is required\n");
|
|
1314
|
-
return null;
|
|
1315
|
-
}
|
|
1316
|
-
const grantError = grantEntryError(namespaces, ["read", "mutate"]);
|
|
1317
|
-
if (grantError !== null) {
|
|
1318
|
-
io.out(`grant '${ns}' refused: ${grantError}\n`);
|
|
1319
|
-
return null;
|
|
1320
|
-
}
|
|
1321
|
-
return actions.registerAgent(kid, pub, namespaces);
|
|
1322
|
-
}
|
|
1323
|
-
case "revoke": {
|
|
1324
|
-
const done = [];
|
|
1325
|
-
for (const kid of action.kids) {
|
|
1326
|
-
const typed = await need(io, `type '${kid}' to revoke it: `);
|
|
1327
|
-
if (typed !== kid) {
|
|
1328
|
-
io.out(`'${typed}' did not match — ${kid} left alone\n`);
|
|
1329
|
-
continue;
|
|
1330
|
-
}
|
|
1331
|
-
try {
|
|
1332
|
-
done.push(await actions.revoke(kid));
|
|
1333
|
-
} catch (err) {
|
|
1334
|
-
done.push(`failed: ${kid}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1335
|
-
}
|
|
1336
|
-
}
|
|
1337
|
-
return done.length > 0 ? done.join("\n") : null;
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
function summary(steps, stopped) {
|
|
1342
|
-
const skipped = steps.filter((s) => s.status === "skipped").map((s) => s.name);
|
|
1343
|
-
const blocked = steps.filter((s) => s.status === "blocked").map((s) => s.name);
|
|
1344
|
-
const lines = [stopped ? "onboarding stopped before it finished." : requiredOutstanding(steps) ? "onboarding has required steps outstanding." : "onboarding complete."];
|
|
1345
|
-
if (skipped.length > 0) lines.push(`skipped: ${skipped.join(", ")}`);
|
|
1346
|
-
if (blocked.length > 0) lines.push(`not checked: ${blocked.join(", ")}`);
|
|
1347
|
-
return `\n${lines.join("\n")}\n`;
|
|
1348
|
-
}
|
|
1349
|
-
async function runOnboard(opts) {
|
|
1350
|
-
const { io, actions } = opts;
|
|
1351
|
-
const adminCapability = opts.adminCapability ?? "admin";
|
|
1352
|
-
const skipped = /* @__PURE__ */ new Set();
|
|
1353
|
-
let declined = null;
|
|
1354
|
-
for (;;) {
|
|
1355
|
-
let result;
|
|
1356
|
-
try {
|
|
1357
|
-
result = await opts.diagnose();
|
|
1358
|
-
} catch (err) {
|
|
1359
|
-
io.out(`diagnose failed: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
1360
|
-
return 2;
|
|
1361
|
-
}
|
|
1362
|
-
const steps = planOnboarding(result, {
|
|
1363
|
-
canBootstrap: opts.canBootstrap,
|
|
1364
|
-
skipped
|
|
1365
|
-
});
|
|
1366
|
-
io.out(`\n${formatChecklist(steps)}`);
|
|
1367
|
-
const step = currentStep(steps);
|
|
1368
|
-
const exitCode = requiredOutstanding(steps) ? 1 : 0;
|
|
1369
|
-
if (step === void 0 || !opts.interactive) {
|
|
1370
|
-
io.out(summary(steps, false));
|
|
1371
|
-
return exitCode;
|
|
1372
|
-
}
|
|
1373
|
-
if (declined !== step.name) declined = null;
|
|
1374
|
-
io.out(`\n${step.name}: ${step.detail}\n`);
|
|
1375
|
-
try {
|
|
1376
|
-
if (step.action !== void 0 && declined === null) {
|
|
1377
|
-
io.out(` would run: ${describeAction(step.action, opts.bootstrapStore, adminCapability)}\n`);
|
|
1378
|
-
if ((await need(io, "Run it? [y/N] ")).toLowerCase() === "y") {
|
|
1379
|
-
try {
|
|
1380
|
-
const output = await perform(step.action, io, actions);
|
|
1381
|
-
if (output !== null) io.out(`${output}\n`);
|
|
1382
|
-
} catch (err) {
|
|
1383
|
-
if (err instanceof EndOfInput) throw err;
|
|
1384
|
-
io.out(`failed: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
1385
|
-
}
|
|
1386
|
-
continue;
|
|
1387
|
-
}
|
|
1388
|
-
declined = step.name;
|
|
1389
|
-
}
|
|
1390
|
-
if (step.fix !== void 0) io.out(` fix: ${step.fix}\n`);
|
|
1391
|
-
const offerRun = step.action !== void 0 && declined === step.name;
|
|
1392
|
-
const choice = (await need(io, `Enter re-checks${offerRun ? ", r runs the fix" : ""}${step.skippable ? ", s skips" : ""}, q quits: `)).toLowerCase();
|
|
1393
|
-
if (choice === "q") {
|
|
1394
|
-
io.out(summary(steps, true));
|
|
1395
|
-
return exitCode;
|
|
1396
|
-
}
|
|
1397
|
-
if (choice === "r" && offerRun) declined = null;
|
|
1398
|
-
if (choice === "s") {
|
|
1399
|
-
if (SKIPPABLE_STEPS.has(step.name)) skipped.add(step.name);
|
|
1400
|
-
else io.out(`${step.name} cannot be skipped\n`);
|
|
1401
|
-
}
|
|
1402
|
-
} catch (err) {
|
|
1403
|
-
if (!(err instanceof EndOfInput)) throw err;
|
|
1404
|
-
io.out(summary(steps, true));
|
|
1405
|
-
return exitCode;
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
/** A postgres URL fit to print: the password is never echoed. */
|
|
1410
|
-
function redactStore(url) {
|
|
1411
|
-
let u;
|
|
1412
|
-
try {
|
|
1413
|
-
u = new URL(url);
|
|
1414
|
-
} catch {
|
|
1415
|
-
return "(an unparseable postgres URL)";
|
|
1416
|
-
}
|
|
1417
|
-
const auth = u.username.length > 0 ? `${u.username}${u.password.length > 0 ? ":***" : ""}@` : "";
|
|
1418
|
-
return `${u.protocol}//${auth}${u.host}${u.pathname}`;
|
|
1419
|
-
}
|
|
1420
|
-
function registerArgs(kid, pubkeyPath, over) {
|
|
1421
|
-
return {
|
|
1422
|
-
kid,
|
|
1423
|
-
pubkeyPath,
|
|
1424
|
-
name: kid,
|
|
1425
|
-
namespaces: [],
|
|
1426
|
-
capabilities: ["read", "mutate"],
|
|
1427
|
-
allowAdmin: false,
|
|
1428
|
-
allowUnknownNs: false,
|
|
1429
|
-
url: null,
|
|
1430
|
-
noDirectory: false,
|
|
1431
|
-
noBroadcast: false,
|
|
1432
|
-
project: null,
|
|
1433
|
-
...over
|
|
1434
|
-
};
|
|
1435
|
-
}
|
|
1436
|
-
/** The production action runners: the same functions the standalone subcommands call. */
|
|
1437
|
-
function realOnboardActions(env, baseUrl, fetchImpl = fetch) {
|
|
1438
|
-
const cap = env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? env.SUBSTRATE_ADMIN_CAPABILITY : DEFAULT_ADMIN_CAPABILITY;
|
|
1439
|
-
return {
|
|
1440
|
-
bootstrap: async () => formatBootstrapOutput(await runBootstrap(env)),
|
|
1441
|
-
registerAdmin: async (kid, pub) => formatRegisterOutput(await runRegisterViaRoute(registerArgs(kid, pub, {
|
|
1442
|
-
namespaces: ["*"],
|
|
1443
|
-
capabilities: seedCapabilities(cap),
|
|
1444
|
-
allowAdmin: true,
|
|
1445
|
-
noDirectory: true
|
|
1446
|
-
}), baseUrl, env, fetchImpl), { adminRoot: true }),
|
|
1447
|
-
registerAgent: async (kid, pub, namespaces) => formatRegisterOutput(await runRegisterViaRoute(registerArgs(kid, pub, { namespaces: [...namespaces] }), baseUrl, env, fetchImpl)),
|
|
1448
|
-
revoke: async (kid) => {
|
|
1449
|
-
await runKeyPatchViaRoute({
|
|
1450
|
-
kid,
|
|
1451
|
-
revoke: true
|
|
1452
|
-
}, baseUrl, env, REVOKE_EXIT_CODES, fetchImpl);
|
|
1453
|
-
return `revoked ${kid}`;
|
|
1454
|
-
},
|
|
1455
|
-
generateKeypair: (path, kid) => writeKeypair(env, path, kid)
|
|
1456
|
-
};
|
|
1457
|
-
}
|
|
1458
|
-
/** Parse argv, resolve the target, and run — the shape `main` dispatches to. */
|
|
1459
|
-
async function onboardCommand(argv, env, io, interactive, fetchImpl = fetch) {
|
|
1460
|
-
validateArgv("onboard", argv);
|
|
1461
|
-
let url;
|
|
1462
|
-
let direct = false;
|
|
1463
|
-
let check = false;
|
|
1464
|
-
for (let i = 0; i < argv.length; i++) {
|
|
1465
|
-
const tok = argv[i];
|
|
1466
|
-
if (tok === "--url") {
|
|
1467
|
-
if (url !== void 0) throw argvError("onboard", "onboard: --url specified more than once", 1);
|
|
1468
|
-
url = argv[i + 1] ?? "";
|
|
1469
|
-
i += 1;
|
|
1470
|
-
} else if (tok === "--direct") direct = true;
|
|
1471
|
-
else if (tok === "--check") check = true;
|
|
1472
|
-
}
|
|
1473
|
-
const target = resolveAdminTarget(direct ? "" : url ?? null, env);
|
|
1474
|
-
if (target.kind !== "route") {
|
|
1475
|
-
io.out(formatDoctorReport({
|
|
1476
|
-
checks: [DIRECT_TARGET_REFUSAL],
|
|
1477
|
-
exitCode: 1
|
|
1478
|
-
}));
|
|
1479
|
-
return 1;
|
|
1480
|
-
}
|
|
1481
|
-
const store = env.SUBSTRATE_DATABASE_URL ?? "";
|
|
1482
|
-
const canBootstrap = (store.startsWith("postgres://") || store.startsWith("postgresql://")) && bootstrapBlockers(env).length === 0;
|
|
1483
|
-
return runOnboard({
|
|
1484
|
-
diagnose: () => diagnoseTarget(env, target.baseUrl, fetchImpl),
|
|
1485
|
-
canBootstrap,
|
|
1486
|
-
...canBootstrap ? { bootstrapStore: redactStore(store) } : {},
|
|
1487
|
-
...env.SUBSTRATE_ADMIN_CAPABILITY !== void 0 && env.SUBSTRATE_ADMIN_CAPABILITY.length > 0 ? { adminCapability: env.SUBSTRATE_ADMIN_CAPABILITY } : {},
|
|
1488
|
-
interactive: interactive && !check,
|
|
1489
|
-
io,
|
|
1490
|
-
actions: realOnboardActions(env, target.baseUrl, fetchImpl)
|
|
1491
|
-
});
|
|
1492
|
-
}
|
|
1493
|
-
|
|
1494
|
-
//#endregion
|
|
1495
|
-
//#region src/admin/dataset.ts
|
|
1496
|
-
/**
|
|
1497
|
-
* Direct-to-pg dataset opener shared by every CLI path that writes `_system`
|
|
1498
|
-
* rows without going through the running binary, including
|
|
1499
|
-
* `substrate federate enroll`.
|
|
1500
|
-
*
|
|
1501
|
-
* It never migrates: only `bootstrap` and the server change the schema. A
|
|
1502
|
-
* store missing a migration this CLI knows is refused.
|
|
1503
|
-
*/
|
|
1504
|
-
async function openPgDataset(env, openSql$1 = openSql) {
|
|
1505
|
-
const storeSpec = env.SUBSTRATE_DATABASE_URL;
|
|
1506
|
-
if (storeSpec === void 0 || storeSpec.length === 0) throw new AdminCliError("SUBSTRATE_DATABASE_URL is required (must be a postgres:// URL)");
|
|
1507
|
-
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.`);
|
|
1508
|
-
const sql = openSql$1(storeSpec);
|
|
1509
|
-
let pending;
|
|
1510
|
-
try {
|
|
1511
|
-
pending = await pendingMigrations(sql);
|
|
1512
|
-
} catch (err) {
|
|
1513
|
-
await closeQuietly(sql);
|
|
1514
|
-
throw err;
|
|
1515
|
-
}
|
|
1516
|
-
if (pending.length > 0) {
|
|
1517
|
-
await closeQuietly(sql);
|
|
1518
|
-
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.`);
|
|
1519
|
-
}
|
|
1520
|
-
return {
|
|
1521
|
-
dataset: new PgDataset({
|
|
1522
|
-
namespace: SYSTEM_NAMESPACE,
|
|
1523
|
-
sql
|
|
1524
|
-
}),
|
|
1525
|
-
close: () => closeQuietly(sql)
|
|
1526
|
-
};
|
|
1527
|
-
}
|
|
1528
|
-
async function closeQuietly(sql) {
|
|
1529
|
-
try {
|
|
1530
|
-
await sql.end();
|
|
1531
|
-
} catch {}
|
|
1532
|
-
}
|
|
1533
|
-
|
|
1534
|
-
//#endregion
|
|
1535
|
-
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 };
|