@cotal-ai/core 0.167.0 → 0.168.0
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/dist/endpoint-call.d.ts +4 -2
- package/dist/endpoint-call.d.ts.map +1 -1
- package/dist/endpoint-call.js +16 -7
- package/dist/endpoint-call.js.map +1 -1
- package/dist/endpoint-provenance.d.ts +11 -0
- package/dist/endpoint-provenance.d.ts.map +1 -0
- package/dist/endpoint-provenance.js +20 -0
- package/dist/endpoint-provenance.js.map +1 -0
- package/dist/endpoint-serve.d.ts.map +1 -1
- package/dist/endpoint-serve.js +1 -9
- package/dist/endpoint-serve.js.map +1 -1
- package/dist/endpoint.d.ts +19 -2
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +76 -17
- package/dist/endpoint.js.map +1 -1
- package/dist/provision-jwt.d.ts +518 -0
- package/dist/provision-jwt.d.ts.map +1 -0
- package/dist/provision-jwt.js +641 -0
- package/dist/provision-jwt.js.map +1 -0
- package/dist/provision-permissions.d.ts +72 -0
- package/dist/provision-permissions.d.ts.map +1 -0
- package/dist/provision-permissions.js +2009 -0
- package/dist/provision-permissions.js.map +1 -0
- package/dist/provision-resources.d.ts +66 -0
- package/dist/provision-resources.d.ts.map +1 -0
- package/dist/provision-resources.js +61 -0
- package/dist/provision-resources.js.map +1 -0
- package/dist/provision-server-config.d.ts +115 -0
- package/dist/provision-server-config.d.ts.map +1 -0
- package/dist/provision-server-config.js +169 -0
- package/dist/provision-server-config.js.map +1 -0
- package/dist/provision.d.ts +19 -707
- package/dist/provision.d.ts.map +1 -1
- package/dist/provision.js +4 -2860
- package/dist/provision.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
import { decodeNatsJwt, nativeNkeySigner } from "./nkey-signer.js";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { decode, encodeOperator, encodeAccount, encodeUser, fmtCreds } from "@nats-io/jwt";
|
|
4
|
+
import { createOperator, createAccount, fromPublic, fromSeed } from "@nats-io/nkeys";
|
|
5
|
+
import { token, principalKey, principalTags, assertInboxConnId, DEV_OWNER, presenceKeySubject, connzRequestSubject, accountCensusInboxPrefix } from "./subjects.js";
|
|
6
|
+
import {} from "./endpoint-grants.js";
|
|
7
|
+
import { assertServeGrantMintable, finalizeServeIssuance } from "./endpoint-service.js";
|
|
8
|
+
import { parseServiceConnectionBinding } from "./service-gate.js";
|
|
9
|
+
import { SERVICE_ACCESS_TTL_SECONDS } from "./service-authority-limits.js";
|
|
10
|
+
import { importNativeSubjectPermissions, issuedHorizon, issuedPermitsPattern, prepareListing, writeAcceptedRow } from "./issued-authority.js";
|
|
11
|
+
import {} from "./run-driver-grants.js";
|
|
12
|
+
import { credentialIdOf } from "./lifecycle-state.js";
|
|
13
|
+
import { isEnvironmentManagerProfile } from "./environment-manager-grants.js";
|
|
14
|
+
import { credsClaims, isAccountNkey, isUserNkey } from "./identity.js";
|
|
15
|
+
import {} from "./backup.js";
|
|
16
|
+
import { INSTRUMENT_PROFILES, connectionEvictorPermissions, endpointServePermissions, membershipObserverPermissions, permissionsFor } from "./provision-permissions.js";
|
|
17
|
+
const FIVE_MINUTES = 5 * 60;
|
|
18
|
+
/** The broker's pre-auth control-line cap, in bytes (`max_control_line` in the generated config —
|
|
19
|
+
* `openServerConfig` and `serverConfig` below both render this literal, so the cap and the
|
|
20
|
+
* mint-time bound derived from it below can never drift). 64 KiB clears a many-channel agent
|
|
21
|
+
* JWT (~4-8 KB) with wide margin while keeping the pre-auth allocation ~16x tighter than 1 MB
|
|
22
|
+
* under connection flooding (the CONNECT line is parsed BEFORE auth). */
|
|
23
|
+
export const MAX_CONTROL_LINE_BYTES = 65536;
|
|
24
|
+
/** The fixed bytes a NATS client wraps around the `jwt` field on the CONNECT protocol line, over
|
|
25
|
+
* and above the JWT itself: the JSON object's other keys (`nkey`, `sig`, `name`, `lang`,
|
|
26
|
+
* `version`, `protocol`, `verbose`, `pedantic`, `no_responders`, `headers`), their values, and
|
|
27
|
+
* the surrounding braces/quotes/commas. Measured live (nats-server `-DV`, the trace of the raw
|
|
28
|
+
* protocol) on a real connect with the nats.js v3 client: a control-name credential produced a
|
|
29
|
+
* 5,104-byte JWT inside a 5,291-byte CONNECT line — 187 bytes of envelope, reproduced twice.
|
|
30
|
+
* Rounded up generously (>2.5x) to absorb client/library variation this repo does not control. */
|
|
31
|
+
export const CONNECT_ENVELOPE_OVERHEAD_BYTES = 512;
|
|
32
|
+
/** The mint-time budget for a user JWT's byte size: every composition that inflates the JWT (a
|
|
33
|
+
* long single channel, many channels, the per-agent event channel, any grant a later change
|
|
34
|
+
* adds) is priced against the SAME number, because the credential is what the client sends on
|
|
35
|
+
* the CONNECT line and the CONNECT line is what the broker caps — not any one contributor to it.
|
|
36
|
+
* `assertValidName`/`assertValidChannel` bound one input each; this bounds the OUTPUT, closing
|
|
37
|
+
* the gap between "every individual grant is legal" and "the composed credential still fits"
|
|
38
|
+
* (issue #375's review finding: six distinct 4096-char channels, each individually accepted,
|
|
39
|
+
* minted a JWT the broker would silently drop). */
|
|
40
|
+
export const MAX_MINTED_JWT_BYTES = MAX_CONTROL_LINE_BYTES - CONNECT_ENVELOPE_OVERHEAD_BYTES;
|
|
41
|
+
/** Bounded lifetime for `standing-renewable` credentials whose renewal owner is ONLINE:
|
|
42
|
+
* the holder (or its launcher) re-mints at 75% of the lifetime via the endpoint's creds-source seam,
|
|
43
|
+
* so a copied cred is broker-dead within a day while renewal never involves an operator. 24h keeps
|
|
44
|
+
* the remaining-25% loud-failure window at ~6h — wide enough to notice and repair before expiry. */
|
|
45
|
+
export const STANDING_RENEWABLE_TTL_SEC = 24 * 60 * 60;
|
|
46
|
+
/** Bounded lifetime for the `rotation-renewed` $SYS credentials (membership-observer + connection-
|
|
47
|
+
* evictor). They are NOT online-renewable (the $SYS seed dies at end of `up`), so this exp is the
|
|
48
|
+
* credential-death horizon: a copied observer/evictor cred becomes broker-dead after it, and the
|
|
49
|
+
* operator is expected to have run a coordinated system-account rotation + broker restart within it
|
|
50
|
+
* (the doctor surface warns ahead). 30 days balances "copied cred eventually dies" against
|
|
51
|
+
* a comfortable monthly rotation cadence; tune here as one named knob. */
|
|
52
|
+
export const ROTATION_RENEWED_TTL_SEC = 30 * 24 * 60 * 60;
|
|
53
|
+
/** The credential lifetime matrix. This is intentionally centralized so every new mint profile must classify its
|
|
54
|
+
* credential-death behavior instead of silently inheriting non-expiring static creds. */
|
|
55
|
+
export const CREDENTIAL_LIFETIMES = {
|
|
56
|
+
agent: { class: "mixed", note: "manager children, foreground spawn/join, and `cotal mint` static outputs all use this profile; split or repair flow required before default exp" },
|
|
57
|
+
"manager-caller": { class: "mixed", note: "short-lived user-auth view bound to the bearer expiry and one manager instance" },
|
|
58
|
+
observer: { class: "static-operator-managed", note: "out-of-band dashboard/audit credential from `cotal mint`" },
|
|
59
|
+
admin: { class: "static-operator-managed", note: "out-of-band elevated dashboard/audit credential from `cotal mint`" },
|
|
60
|
+
supervisor: { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "manager's always-on endpoint; the manager holds the DATA seed and self-remints via the endpoint creds source" },
|
|
61
|
+
delivery: { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "server-side Plane-3 daemon; seed-less - the manager re-signs .cotal/delivery.creds for the SAME nkey, requests delivery-admin reloadCreds for explicit adoption, and the endpoint source re-read is only a backstop" },
|
|
62
|
+
"membership-rw": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "membership feed writer; seed-less - the manager re-signs the membership-rw.creds store key for the SAME nkey, the feed adopts it on a 75% preflight-proven renewal timer (its active self-heal), and delivery-admin reloadCreds is the explicit adoption on top" },
|
|
63
|
+
provisioner: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "setup/spawn provisioning window only" },
|
|
64
|
+
deprovisioner: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "target-pinned teardown window only" },
|
|
65
|
+
"retirement-requester": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one despawn's retirement request window; request+reply only" },
|
|
66
|
+
"lifecycle-executor": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one static lifecycle operation's 13.1 state-write window (activation / terminal / renewal ledger append)" },
|
|
67
|
+
"endpoint-serve-executor": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one endpoint registration/serve-mint window (13.1 epgate CAS + epcred stage/revoke + eprepair cursor for one (endpoint, instanceId))" },
|
|
68
|
+
operator: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "send/dm/join/probe-style operator command" },
|
|
69
|
+
purger: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "history purge command" },
|
|
70
|
+
backup: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "offline snapshot phase; exact stream and delivery subject, memory-only" },
|
|
71
|
+
restore: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "offline restore initiation or exact-ID upload phase, memory-only" },
|
|
72
|
+
probe: { class: "one-shot", defaultTtlSeconds: 60, note: "connect-only preflight" },
|
|
73
|
+
"channel-writer": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "channel registry mutation command" },
|
|
74
|
+
"channel-purger": { class: "mixed", note: "one-shot for CLI, standing inside web; split or renewal required before default exp" },
|
|
75
|
+
teardown: { class: "one-shot", note: "space teardown can be long/destructive; needs TTL budget/remint guard before default exp" },
|
|
76
|
+
"membership-store-recreate": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one stopped-space conversion of the derived membership stream from File to Memory; exact stream info/delete only" },
|
|
77
|
+
"issued-store-recreate": { class: "one-shot", defaultTtlSeconds: 30 * 60, note: "one `up --recreate-issued-stores` step: snapshot and delete the two pre-retention issued-authority stores of one space; 30 minutes bounds a large store's snapshot" },
|
|
78
|
+
"control-caller-privileged": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "ps/start control call" },
|
|
79
|
+
"control-caller-admin": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "stop/attach admin control call" },
|
|
80
|
+
deployer: { class: "one-shot", note: "manifest deploy spans planning/launch/ledger; needs near-expiry guard or remint before default exp" },
|
|
81
|
+
"endpoint-serve": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "per-instance endpoint serve credential (SPEC 13.9); the managing authority re-mints on renewal and on takeover (new epoch), and the 13.1 barrier revokes the superseded one" },
|
|
82
|
+
"goal-writer": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "self-mediated goal-writer for spawn-as-action; the manager re-mints for the SAME nkey on renewal, disjoint from the serve credential" },
|
|
83
|
+
"session-caller": { class: "one-shot", defaultTtlSeconds: 24 * 60 * 60, note: "per-session console/CLI caller cred: rails-only for ONE §13.6 session; TTL-BOUND to the session (the face mints with expiresAt = the session exp; the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred" },
|
|
84
|
+
"dm-reader": { class: "mixed", note: "user-auth own-DM reader view: one dm_ durable's INFO/NEXT/ACK, bound to the bearer expiry (which the IdP proof bounds); renewed by re-exchange, never a standing credential" },
|
|
85
|
+
"session-serving": { class: "one-shot", defaultTtlSeconds: 24 * 60 * 60, note: "per-session SERVING cred: rails-only for ONE §13.6 session, the mirror of session-caller with the directions swapped; minted at redemption and TTL-BOUND to the session (the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred, and the session's terminal revokes this one by name" },
|
|
86
|
+
"session-ledger": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "manager's session LEDGER: the dedicated sessions-bucket `session.<id>` rows and NOTHING else - no session rail of any shape. Standing because SPEC 13.6 makes it the durable revocation authority that must survive the serving endpoint; the manager re-mints for the SAME nkey on the half-TTL loop (the goal-writer precedent)" },
|
|
87
|
+
"run-driver": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "one workflow run's driver, per takeover attempt (SPEC 14.6): the hosting manager mints it when it takes the run over and re-mints for the SAME nkey on renewal; a new takeover mints a new one" },
|
|
88
|
+
"run-mediator": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "trusted workflow host operations, bound to one run and attempt; kept on the hosting process's connection" },
|
|
89
|
+
"run-operator": { class: "one-shot", defaultTtlSeconds: 60, note: "one served run-status / run-ps / run-answer call (SPEC 14.3): the hosting manager mints it per call on its own connection, never the serve rails; 60s bounds a copied cred to a minute" },
|
|
90
|
+
"registry-reader": { class: "standing-renewable", defaultTtlSeconds: 60 * 60, renewalOwner: "registry host", note: "the registry's reads (SPEC 13.20), no write of any shape; the evidence-store read is stream-scoped, so it can read every recorded ceiling in the space (a NAMED RESIDUAL), and one hour bounds a copied credential; the process hosting the registry re-mints it" },
|
|
91
|
+
issuer: { class: "mixed", defaultTtlSeconds: FIVE_MINUTES, renewalOwner: "auth-service", note: "renewed as the auth plane's held session for connect-time issuance (re-minted before exp, closed with the plane); one-shot for every other issuance window and for a lifecycle terminal's issuance retirement (SPEC 13.15)" },
|
|
92
|
+
"run-admitter": { class: "one-shot", defaultTtlSeconds: 60, note: "one hosted run's admission record create, or its revocation marker (SPEC 14.8); 60s bounds a copied cred to a minute" },
|
|
93
|
+
"transfer-writer": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one carried resume per CLI call: one object's chunk and meta subjects in one instance's transfer bucket" },
|
|
94
|
+
"transfer-reader": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one transcript-receive or sweep over the minting instance's own transfer bucket" },
|
|
95
|
+
"endpoint-evictor": { class: "one-shot", defaultTtlSeconds: 60, note: "one re-registration's verify-evict window: a scoped delivery-admin caller that kicks+verifies the SUPERSEDED serve family before the epoch advances; 60s bounds a copied cred to a minute" },
|
|
96
|
+
"remote-manager": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "auth-service", note: "the scoped remote manager lifecycle: own lease/presence plus same-owner agent provisioning; issued only by the typed supervise protocol, never by `cotal mint` or a raw view/profile string" },
|
|
97
|
+
"environment-bootstrap": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one admitted environment's bootstrap caller; explicit expiry capped by admission and five minutes" },
|
|
98
|
+
"environment-manager-supervisor": { class: "standing-renewable", renewalOwner: "environment-authority", note: "own lease/presence/liveness; explicit expiry capped by admission, no auth-store access" },
|
|
99
|
+
"environment-manager-executor": { class: "standing-renewable", renewalOwner: "environment-authority", note: "own admitted authority instance RPC; explicit expiry capped by admission, no direct store access" },
|
|
100
|
+
"environment-manager-goal-writer": { class: "standing-renewable", renewalOwner: "environment-authority", note: "manager goal rows without the auth-read belt; explicit expiry capped by admission" },
|
|
101
|
+
"membership-observer": { class: "rotation-renewed", defaultTtlSeconds: ROTATION_RENEWED_TTL_SEC, renewalOwner: "system-account rotation", note: "$SYS-account CONNZ observer; NOT online-renewable ($SYS seed dies at `up`) - bounded exp, renewed only by rotateSystemAccount + broker restart; doctor warns near expiry" },
|
|
102
|
+
"account-census": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "Host-only account CONNZ and account-qualified replies; at most five minutes, no KICK or client-side renewal" },
|
|
103
|
+
"connection-evictor": { class: "rotation-renewed", defaultTtlSeconds: ROTATION_RENEWED_TTL_SEC, renewalOwner: "system-account rotation", note: "$SYS-account KICK-only live-eviction cred; same rotation-renewed posture as the observer" },
|
|
104
|
+
};
|
|
105
|
+
// RUNTIME integrity (the afa715b class): the matrix and every policy freeze at module load
|
|
106
|
+
// (a post-import `defaultTtlSeconds = undefined` would otherwise mint a NON-EXPIRING credential
|
|
107
|
+
// out of a one-shot profile, executed repro), and the mint path below reads a PRIVATE TTL
|
|
108
|
+
// snapshot taken here, never the live export.
|
|
109
|
+
for (const p of Object.values(CREDENTIAL_LIFETIMES))
|
|
110
|
+
Object.freeze(p);
|
|
111
|
+
Object.freeze(CREDENTIAL_LIFETIMES);
|
|
112
|
+
const LIFETIME_TTL_SNAP = new Map(Object.entries(CREDENTIAL_LIFETIMES).map(([k, p]) => [k, p.defaultTtlSeconds]));
|
|
113
|
+
export function credentialLifetime(kind) {
|
|
114
|
+
return CREDENTIAL_LIFETIMES[kind];
|
|
115
|
+
}
|
|
116
|
+
export function inspectCredHealth(creds, nowSec = Math.floor(Date.now() / 1000)) {
|
|
117
|
+
let claims;
|
|
118
|
+
try {
|
|
119
|
+
claims = credsClaims(creds);
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
return { state: "unreadable", error: e.message };
|
|
123
|
+
}
|
|
124
|
+
const { iat, exp } = claims;
|
|
125
|
+
if (typeof exp !== "number")
|
|
126
|
+
return { state: "unbounded", iat };
|
|
127
|
+
if (typeof iat !== "number")
|
|
128
|
+
return { state: "unreadable", iat: undefined, exp, error: "user JWT carries exp but no iat - cannot place the renewal point" };
|
|
129
|
+
const renewAt = Math.floor(iat + 0.75 * (exp - iat));
|
|
130
|
+
if (nowSec >= exp)
|
|
131
|
+
return { state: "expired", iat, exp, renewAt };
|
|
132
|
+
if (nowSec >= renewAt)
|
|
133
|
+
return { state: "near-expiry", iat, exp, renewAt };
|
|
134
|
+
return { state: "healthy", iat, exp, renewAt };
|
|
135
|
+
}
|
|
136
|
+
/** Compose the read view from its two persisted authorities. Fails loud when the space account was
|
|
137
|
+
* not signed by THIS broker's operator: a self-consistent account signed by a FOREIGN operator is
|
|
138
|
+
* perfectly valid on its own and would otherwise be rendered into the resolver as untrusted trust. */
|
|
139
|
+
export function composeSpaceAuth(broker, spaceAccount) {
|
|
140
|
+
assertAccountSignedByBroker(broker, spaceAccount);
|
|
141
|
+
return { ...broker, ...spaceAccount };
|
|
142
|
+
}
|
|
143
|
+
/** The binding check behind {@link composeSpaceAuth} and registry admission: this space's data
|
|
144
|
+
* account JWT must be issued by this broker's operator identity. */
|
|
145
|
+
export function assertAccountSignedByBroker(broker, spaceAccount) {
|
|
146
|
+
if (!broker.operator.seed)
|
|
147
|
+
throw new Error("assertAccountSignedByBroker: broker operator material is required to verify the account binding");
|
|
148
|
+
let operatorPub;
|
|
149
|
+
try {
|
|
150
|
+
operatorPub = nativeNkeySigner(new TextEncoder().encode(broker.operator.seed)).getPublicKey();
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
throw new Error("assertAccountSignedByBroker: the broker operator seed is not a valid operator seed");
|
|
154
|
+
}
|
|
155
|
+
const claims = decodeNatsJwt(spaceAccount.account.jwt);
|
|
156
|
+
if (claims.iss !== operatorPub)
|
|
157
|
+
throw new Error(`space "${spaceAccount.space}" account was signed by ${claims.iss ?? "an unknown issuer"}, not this broker's operator ${operatorPub} - refusing to compose trust across brokers`);
|
|
158
|
+
}
|
|
159
|
+
// Unlimited account limits — without explicit limits a JWT account defaults to 0 conns
|
|
160
|
+
// (every connect denied). JetStream needs storage on the data account but MUST stay off
|
|
161
|
+
// the system account (the server refuses to start otherwise).
|
|
162
|
+
const BASE_LIMITS = {
|
|
163
|
+
subs: -1, conn: -1, leaf: -1, imports: -1, exports: -1,
|
|
164
|
+
data: -1, payload: -1, wildcards: true,
|
|
165
|
+
};
|
|
166
|
+
const DATA_LIMITS = { ...BASE_LIMITS, mem_storage: -1, disk_storage: -1 };
|
|
167
|
+
const SYS_LIMITS = { ...BASE_LIMITS, mem_storage: 0, disk_storage: 0 };
|
|
168
|
+
/** Reduce a {@link SpaceAuth} to just the material a *minting* host needs: `space`,
|
|
169
|
+
* `account.pub`, and `account.signingSeed` (the only fields {@link mintCreds} reads).
|
|
170
|
+
* The operator root-of-trust, system account, and the account's own seed are blanked.
|
|
171
|
+
*
|
|
172
|
+
* This is the file you hand a manager that should mint per-agent creds but must never
|
|
173
|
+
* hold the operator key — e.g. a containerized team. A leaked stripped file only lets
|
|
174
|
+
* someone mint *users within this one account*, which the account boundary already
|
|
175
|
+
* contains; it cannot mint new accounts or touch the system account. */
|
|
176
|
+
export function stripSpaceAuth(auth) {
|
|
177
|
+
return {
|
|
178
|
+
space: auth.space,
|
|
179
|
+
operator: { seed: "", jwt: "" },
|
|
180
|
+
account: {
|
|
181
|
+
pub: auth.account.pub,
|
|
182
|
+
seed: "",
|
|
183
|
+
jwt: "",
|
|
184
|
+
signingSeed: auth.account.signingSeed,
|
|
185
|
+
signingPub: "",
|
|
186
|
+
},
|
|
187
|
+
sys: { pub: "", jwt: "" },
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/** The user public keys a data-account JWT revokes, each with the Unix second it was revoked at. The
|
|
191
|
+
* broker refuses a user JWT for that key issued at or before that second. */
|
|
192
|
+
export function accountRevocations(accountJwt) {
|
|
193
|
+
return { ...decode(accountJwt).nats.revocations };
|
|
194
|
+
}
|
|
195
|
+
/** Re-issue the data-account JWT with the user key `userPub` revoked at `at` (Unix seconds), keeping
|
|
196
|
+
* every other claim. A key already revoked keeps its first time and the auth is returned unchanged.
|
|
197
|
+
* The broker applies it when it next loads its configuration. */
|
|
198
|
+
export async function revokeAccountUser(auth, userPub, at) {
|
|
199
|
+
if (!auth.operator.seed)
|
|
200
|
+
throw new Error("revokeAccountUser: the broker operator seed is required - a stripped broker cannot re-sign the space account");
|
|
201
|
+
if (!isUserNkey(userPub))
|
|
202
|
+
throw new Error("revokeAccountUser: not a user public key");
|
|
203
|
+
const claims = decode(auth.account.jwt);
|
|
204
|
+
const revocations = claims.nats.revocations ?? {};
|
|
205
|
+
if (revocations[userPub] !== undefined)
|
|
206
|
+
return auth;
|
|
207
|
+
const okp = fromSeed(new TextEncoder().encode(auth.operator.seed));
|
|
208
|
+
const jwt = await encodeAccount(claims.name, auth.account.pub, { ...claims.nats, revocations: { ...revocations, [userPub]: at } }, { signer: okp });
|
|
209
|
+
return { ...auth, account: { ...auth.account, jwt } };
|
|
210
|
+
}
|
|
211
|
+
/** Re-issue an account JWT that this broker's operator signed so the account serves nobody: every
|
|
212
|
+
* user key issued at or before `at` (Unix seconds) is revoked, and the account admits no client or
|
|
213
|
+
* leaf connection, so a user minted later is refused as well. Every other claim is kept, so the
|
|
214
|
+
* account's JetStream data stays where it is. Push the result with {@link pushAccountClaim} to stop
|
|
215
|
+
* a space on a running full-resolver broker; its live connections close without a reload. */
|
|
216
|
+
export async function retireAccountClaim(broker, accountJwt, at) {
|
|
217
|
+
if (!broker.operator.seed)
|
|
218
|
+
throw new Error("retireAccountClaim: the broker operator seed is required - a stripped broker cannot re-sign the account");
|
|
219
|
+
if (!Number.isSafeInteger(at) || at <= 0)
|
|
220
|
+
throw new Error("retireAccountClaim: at must be a positive whole number of Unix seconds");
|
|
221
|
+
const okp = fromSeed(new TextEncoder().encode(broker.operator.seed));
|
|
222
|
+
const claims = decode(accountJwt);
|
|
223
|
+
if (claims.iss !== okp.getPublicKey() || !isAccountNkey(claims.sub ?? ""))
|
|
224
|
+
throw new Error("retireAccountClaim: the account was not signed by this broker's operator - refusing to re-sign it");
|
|
225
|
+
return encodeAccount(claims.name, claims.sub, {
|
|
226
|
+
...claims.nats,
|
|
227
|
+
limits: { ...claims.nats.limits, conn: 0, leaf: 0 },
|
|
228
|
+
revocations: { ...claims.nats.revocations, "*": at },
|
|
229
|
+
}, { signer: okp });
|
|
230
|
+
}
|
|
231
|
+
/** Rotate the SYSTEM account and re-issue the operator JWT so persisted system-account users (currently
|
|
232
|
+
* `membership-observer`) become broker-dead once the broker loads the returned auth. The fresh
|
|
233
|
+
* `sys.signingSeed` is intentionally in-memory only; callers must mint replacement observer creds before
|
|
234
|
+
* persisting via `saveSpaceAuth`, which strips the seed again. */
|
|
235
|
+
export async function rotateSystemAccount(auth) {
|
|
236
|
+
if (!auth.operator.seed)
|
|
237
|
+
throw new Error("rotateSystemAccount: operator seed material is required (a stripped auth cannot rotate the system account)");
|
|
238
|
+
const okp = fromSeed(new TextEncoder().encode(auth.operator.seed));
|
|
239
|
+
const syskp = createAccount();
|
|
240
|
+
const sysPub = syskp.getPublicKey();
|
|
241
|
+
const operatorJwt = await encodeOperator(`cotal-${token(auth.space)}`, okp, { system_account: sysPub });
|
|
242
|
+
const sysJwt = await encodeAccount("SYS", syskp, { limits: SYS_LIMITS }, { signer: okp });
|
|
243
|
+
// The rotated value IS the next generation of whatever it derived from — persistence refuses a
|
|
244
|
+
// sys change that is not the direct successor of the current record (see BrokerAuth.gen). The
|
|
245
|
+
// input generation is runtime-validated: persisted records reach here through a bare JSON cast,
|
|
246
|
+
// and a string/float/unsafe value would launder through the arithmetic ("0"+1 is "01"; at 2^53,
|
|
247
|
+
// gen+1 === gen) and destroy the successor discriminator.
|
|
248
|
+
// ONLY absence reads 0 (the pre-generation shape); an explicit null is tampering, same as any
|
|
249
|
+
// other malformed value - `?? 0` would launder it into a valid generation-0 predecessor.
|
|
250
|
+
const gen = auth.gen === undefined ? 0 : auth.gen;
|
|
251
|
+
if (typeof gen !== "number" || !Number.isSafeInteger(gen) || gen < 0)
|
|
252
|
+
throw new Error(`rotateSystemAccount: broker generation ${JSON.stringify(gen)} is not a non-negative integer - the loaded record is corrupt; restore it from backup`);
|
|
253
|
+
return {
|
|
254
|
+
...auth,
|
|
255
|
+
operator: { ...auth.operator, jwt: operatorJwt },
|
|
256
|
+
sys: { pub: sysPub, jwt: sysJwt, signingSeed: new TextDecoder().decode(syskp.getSeed()) },
|
|
257
|
+
gen: gen + 1,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/** Generate a fresh BROKER trust root: operator → system account. One per broker, NOT one per space.
|
|
261
|
+
* `label` names the operator (cosmetic, but it lands in the operator JWT); multi-space brokers pass
|
|
262
|
+
* a broker label, and the single-space compatibility path passes the space name so existing
|
|
263
|
+
* operator names are unchanged.
|
|
264
|
+
*
|
|
265
|
+
* The returned `sys.signingSeed` is the ONLY window in which system-account users (the membership
|
|
266
|
+
* observer and the connection evictor) can be minted, because the local filesystem persistence does
|
|
267
|
+
* not write it. Callers that need to add spaces later must retain it in a broker-scoped store. */
|
|
268
|
+
export async function createBrokerAuth(label) {
|
|
269
|
+
const okp = createOperator();
|
|
270
|
+
const syskp = createAccount();
|
|
271
|
+
const sysPub = syskp.getPublicKey();
|
|
272
|
+
const operatorJwt = await encodeOperator(`cotal-${token(label)}`, okp, { system_account: sysPub });
|
|
273
|
+
const sysJwt = await encodeAccount("SYS", syskp, { limits: SYS_LIMITS }, { signer: okp });
|
|
274
|
+
const dec = (u) => new TextDecoder().decode(u);
|
|
275
|
+
return {
|
|
276
|
+
operator: { seed: dec(okp.getSeed()), jwt: operatorJwt },
|
|
277
|
+
sys: { pub: sysPub, jwt: sysJwt, signingSeed: dec(syskp.getSeed()) },
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
/** Generate one space's data account (+ signing key), signed by an EXISTING broker operator. This is
|
|
281
|
+
* the per-tenant half of provisioning: call it once per space against the same {@link BrokerAuth}
|
|
282
|
+
* to put many spaces on one broker, each in its own NATS account. Key generation and JWT
|
|
283
|
+
* construction stay with NATS; the existing native signer derives public keys and signs. */
|
|
284
|
+
export async function createSpaceAccountAuth(broker, space) {
|
|
285
|
+
if (!broker.operator.seed)
|
|
286
|
+
throw new Error("createSpaceAccountAuth: the broker operator seed is required - a stripped broker cannot sign a new space account");
|
|
287
|
+
const okp = nativeNkeySigner(new TextEncoder().encode(broker.operator.seed));
|
|
288
|
+
const akp = nativeNkeySigner(createAccount().getSeed());
|
|
289
|
+
const askp = nativeNkeySigner(createAccount().getSeed()); // account signing key - what mints users
|
|
290
|
+
const accountJwt = await encodeAccount(token(space), akp, { signing_keys: [askp.getPublicKey()], limits: DATA_LIMITS }, { signer: okp });
|
|
291
|
+
const dec = (u) => new TextDecoder().decode(u);
|
|
292
|
+
return {
|
|
293
|
+
space,
|
|
294
|
+
account: {
|
|
295
|
+
pub: akp.getPublicKey(),
|
|
296
|
+
seed: dec(akp.getSeed()),
|
|
297
|
+
jwt: accountJwt,
|
|
298
|
+
signingSeed: dec(askp.getSeed()),
|
|
299
|
+
signingPub: askp.getPublicKey(),
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/** Generate a fresh operator → account(+signing key) → system-account chain for a space.
|
|
304
|
+
* The single-space composition of {@link createBrokerAuth} + {@link createSpaceAccountAuth}: one
|
|
305
|
+
* broker whose only tenant is this space. */
|
|
306
|
+
export async function createSpaceAuth(space) {
|
|
307
|
+
const broker = await createBrokerAuth(space);
|
|
308
|
+
const spaceAccount = await createSpaceAccountAuth(broker, space);
|
|
309
|
+
return { ...broker, ...spaceAccount };
|
|
310
|
+
}
|
|
311
|
+
/** The principal tags every user JWT carries, plus one random issuance tag on a goal-writer or
|
|
312
|
+
* session-ledger credential. Those two profiles carry no epoch-pinned grant, so two mints for one
|
|
313
|
+
* nkey within one second would otherwise sign identical bytes, and their ledger row is keyed by the
|
|
314
|
+
* JWT digest: a restart's re-mint would re-sign the credential its barrier just revoked under the
|
|
315
|
+
* revoked row's id (SPEC 13.1). */
|
|
316
|
+
function userTags(profile, pr) {
|
|
317
|
+
const tags = principalTags(pr.owner, pr.actor);
|
|
318
|
+
return profile === "goal-writer" || profile === "session-ledger" ? [...tags, `issuance:${randomBytes(16).toString("hex")}`] : tags;
|
|
319
|
+
}
|
|
320
|
+
/** Compute a minted credential's `{ exp? }` from an explicit override or the centralized matrix
|
|
321
|
+
* default. Widened to {@link CredentialKind} (not just {@link Profile}) so the bespoke $SYS minters
|
|
322
|
+
* — `membership-observer` / `connection-evictor`, which are kinds, not profiles — thread the same
|
|
323
|
+
* bounded-lifetime policy instead of minting non-expiring $SYS creds. */
|
|
324
|
+
function userValidDates(kind, opts) {
|
|
325
|
+
if (isEnvironmentManagerProfile(kind)) {
|
|
326
|
+
const now = Math.floor(Date.now() / 1000);
|
|
327
|
+
const admissionExpiry = opts.environmentManager?.expiresAt;
|
|
328
|
+
const expiry = opts.expiresAt;
|
|
329
|
+
if (typeof admissionExpiry !== "number" || !Number.isSafeInteger(admissionExpiry) || admissionExpiry <= now ||
|
|
330
|
+
typeof expiry !== "number" || !Number.isSafeInteger(expiry) || expiry <= now || expiry > admissionExpiry)
|
|
331
|
+
throw new Error(`mintCreds: ${kind} requires a current explicit expiresAt no later than admission expiry`);
|
|
332
|
+
if (kind === "environment-bootstrap" && expiry > now + FIVE_MINUTES)
|
|
333
|
+
throw new Error("mintCreds: environment-bootstrap expiry exceeds its five-minute lifetime");
|
|
334
|
+
}
|
|
335
|
+
if (opts.expiresAt !== undefined && opts.expiresInSeconds !== undefined)
|
|
336
|
+
throw new Error("mintCreds: pass only one of expiresAt or expiresInSeconds");
|
|
337
|
+
if (opts.expiresAt !== undefined) {
|
|
338
|
+
if (!Number.isInteger(opts.expiresAt) || opts.expiresAt < 0)
|
|
339
|
+
throw new Error("mintCreds: expiresAt must be a non-negative integer timestamp (seconds)");
|
|
340
|
+
return { exp: opts.expiresAt };
|
|
341
|
+
}
|
|
342
|
+
const ttl = opts.expiresInSeconds ?? LIFETIME_TTL_SNAP.get(kind);
|
|
343
|
+
if (ttl === undefined)
|
|
344
|
+
return {};
|
|
345
|
+
if (!Number.isInteger(ttl) || ttl <= 0)
|
|
346
|
+
throw new Error("mintCreds: expiresInSeconds must be a positive integer");
|
|
347
|
+
return { exp: Math.floor(Date.now() / 1000) + ttl };
|
|
348
|
+
}
|
|
349
|
+
/** Resolve a {@link MintPrincipal} for the STATIC/dev mint path from an {@link Identity} + optional
|
|
350
|
+
* explicit principal. No-login dev default: owner = {@link DEV_OWNER} ("local"), actor = the connection
|
|
351
|
+
* id, so the agent's lane is `local.<id>`. The connection nkey is always the identity's id here (the
|
|
352
|
+
* creds bind to it). User mode does NOT flow through here — the callout mints directly with the
|
|
353
|
+
* server-derived owner + ledger actor. */
|
|
354
|
+
function principalOf(identity, principal, lifecycleUid) {
|
|
355
|
+
return {
|
|
356
|
+
owner: principal?.owner ?? DEV_OWNER,
|
|
357
|
+
actor: principal?.actor ?? identity.id,
|
|
358
|
+
connId: identity.id,
|
|
359
|
+
...(lifecycleUid !== undefined ? { lifecycleUid } : {}),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
/** Mint a user creds file for an agent {@link Identity} (its stable id+seed from
|
|
363
|
+
* {@link newIdentity}). The account signing key signs over ONLY the public key
|
|
364
|
+
* (`fromPublic`) — the agent seed is never part of the signature, it's only folded into
|
|
365
|
+
* the resulting creds file. The "agent" profile is scoped to publish only as itself and only to
|
|
366
|
+
* its declared `allowPublish` channels (post ACL, default-deny), and to read only within
|
|
367
|
+
* `allowSubscribe` (live tail bind-only + per-channel history grants). Every profile is now
|
|
368
|
+
* enumerated least-privilege — there is no allow-all cred (the former `manager` is deleted). */
|
|
369
|
+
export async function mintCreds(auth, identity, profile, opts = {}) {
|
|
370
|
+
// For third-party endpoints, an issued static agent credential carries only untargeted,
|
|
371
|
+
// unjournaled commands. The static lifecycle terminal has no SPEC 13.1 obligation drain, so a
|
|
372
|
+
// targeted or journaled grant could leave accepted work keyed to a retired lifecycle that nothing
|
|
373
|
+
// settles. Refused before anything is signed or staged. The guard covers every issued agent mint:
|
|
374
|
+
// the managed spawn (through provisionAgent), the managed renewal and the foreground spawn. An
|
|
375
|
+
// unissued mint skips it, so a future caller that hands a static agent endpoint commands must mint
|
|
376
|
+
// it issued. The guard skips every reference endpoint, meaning any single-label name such as
|
|
377
|
+
// `manager` (SPEC 13.2). The skip goes by the name and does not check which command a row names.
|
|
378
|
+
// The rows an instance-pinned caller passes here are the manager's own, the ones the `spawn`,
|
|
379
|
+
// `run` and `admin` capabilities mint, and issued agent mints carried them before this guard
|
|
380
|
+
// existed. A persona cannot name a reference endpoint, so the hand-on path never reaches the skip.
|
|
381
|
+
if (profile === "agent" && opts.issued) {
|
|
382
|
+
const drained = opts.endpointCapabilities?.find((c) => c.endpoint.includes(".") && (c.target !== undefined || c.journal));
|
|
383
|
+
if (drained)
|
|
384
|
+
throw new Error(`mintCreds: for third-party endpoints, an issued static agent credential carries only untargeted, unjournaled commands; "${drained.endpoint} ${drained.command}" is ${drained.target !== undefined ? "targeted" : "journaled"}, and the static lifecycle terminal has no obligation drain to settle what it could leave (SPEC 13.1, 13.15)`);
|
|
385
|
+
}
|
|
386
|
+
const signer = nativeNkeySigner(new TextEncoder().encode(auth.account.signingSeed));
|
|
387
|
+
const pr = principalOf(identity, opts.principal, opts.lifecycleUid);
|
|
388
|
+
// Serve rows are INTERNAL to mintCreds behind the §13.1 fence: the exported permissionsFor
|
|
389
|
+
// refuses "endpoint-serve" (so a direct caller can never obtain unfenced serve rows), and only
|
|
390
|
+
// this fenced path calls the row builder.
|
|
391
|
+
const validDates = userValidDates(profile, opts);
|
|
392
|
+
const listing = await prepareStaticListing(auth.space, profile, pr, opts, validDates.exp);
|
|
393
|
+
const perms = profile === "endpoint-serve"
|
|
394
|
+
? endpointServePermissions(auth.space, pr, opts)
|
|
395
|
+
: listing?.permissions ?? permissionsFor(profile, auth.space, pr, opts);
|
|
396
|
+
const userJwt = await encodeUser(profile, fromPublic(identity.id), fromPublic(auth.account.pub),
|
|
397
|
+
// Stamp the principal `tags` so this connection's identity is CONNZ-recoverable by the membership
|
|
398
|
+
// feed — the SAME tags the auth callout stamps (user mode), via core's single-source builder. The
|
|
399
|
+
// JWT `name` stays the profile label (a debug breadcrumb; not a surfaced/queryable CONNZ field).
|
|
400
|
+
{ ...perms, tags: userTags(profile, pr) }, { signer, ...validDates });
|
|
401
|
+
// Build the credential string FULLY before the fence: nothing fallible may run AFTER a winning
|
|
402
|
+
// CAS, or a post-CAS throw would leave a committed ledger row with no released credential (an
|
|
403
|
+
// orphan authority record). fmtCreds only wraps the already-signed JWT with the seed, so it is
|
|
404
|
+
// done here and the fence is the mint's LAST step.
|
|
405
|
+
const creds = new TextDecoder().decode(fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed))));
|
|
406
|
+
// The composed-credential bound (SPEC 13.9, issue #375's review finding): every individual grant
|
|
407
|
+
// input can pass its own validator (assertValidName, assertValidChannel) and the COMPOSED JWT
|
|
408
|
+
// still exceed the CONNECT line the broker caps, because nothing bounded the COUNT of channels
|
|
409
|
+
// an agent's allowSubscribe/allowPublish may carry. Refuse here, BEFORE releaseIssuance (the
|
|
410
|
+
// file's own no-fallible-work-after-a-winning-CAS rule, stated above) — a refusal here has
|
|
411
|
+
// released no ledger row, unlike a refusal after.
|
|
412
|
+
const userJwtBytes = Buffer.byteLength(userJwt, "utf8");
|
|
413
|
+
if (userJwtBytes > MAX_MINTED_JWT_BYTES) {
|
|
414
|
+
const channelCount = (opts.allowSubscribe?.length ?? 0) + (opts.allowPublish?.length ?? 0);
|
|
415
|
+
throw new Error(`mintCreds: minted JWT is ${userJwtBytes} bytes, exceeding the ${MAX_MINTED_JWT_BYTES}-byte ` +
|
|
416
|
+
`mint bound (${channelCount} allowSubscribe+allowPublish channel(s)) - the composed credential ` +
|
|
417
|
+
`would exceed the broker's CONNECT line and the connect would hang silently (issue #375)`);
|
|
418
|
+
}
|
|
419
|
+
await listing?.commit();
|
|
420
|
+
await releaseIssuance(auth.space, profile, pr, opts, perms, validDates.exp, credentialIdOf(creds));
|
|
421
|
+
// §13.1 mint fence for the serve credential: the credential is BUILT, but released only when its
|
|
422
|
+
// NORMATIVE ledger row (holderPrincipal/lifecycleUid/sourceChain/state/exp + the currency
|
|
423
|
+
// coordinates) is durably staged and its revision-pinned CAS wins the instance's single issuance
|
|
424
|
+
// gate (still `open` at the authorized epoch + registrationRevision + nameAuthorityRevision). A
|
|
425
|
+
// takeover, re-registration, or name transfer that froze the gate first makes this lose and
|
|
426
|
+
// release nothing. A read is never a fence, so this is a CAS write, not an in-memory mark.
|
|
427
|
+
if (profile === "endpoint-serve") {
|
|
428
|
+
if (!opts.serveIssuance)
|
|
429
|
+
throw new Error("mintCreds: endpoint-serve requires opts.serveIssuance (the durable issuance-gate seam; the mint releases only on its revision-pinned CAS win, SPEC 13.1)");
|
|
430
|
+
await finalizeServeIssuance(opts.serveIssuance, opts.endpointServe, {
|
|
431
|
+
// PER-ISSUED-JWT id (digest of the credential): `exp` and `iat` have whole-second Unix
|
|
432
|
+
// resolution and `jti` is derived from the claims, so what keeps a re-registered successor
|
|
433
|
+
// serve credential off its revoked predecessor's row within the same second is the
|
|
434
|
+
// epoch-pinned serve grant (`endpointServe.epoch` in the permission rows). A renewal in a
|
|
435
|
+
// later second gets a fresh `iat`/`exp` and writes a new ledger row; a same-second renewal
|
|
436
|
+
// at one epoch signs identical bytes and re-stages the same active row, which the
|
|
437
|
+
// create-only / idempotent-if-identical stage seam accepts as a retry while refusing a
|
|
438
|
+
// revoked row with `conflict`. The stable nkey rides separately as `credentialKey` for
|
|
439
|
+
// broker revocation. KEY-SAFE digest form (`sha256-<hex>`, never the §13.7 `sha256:`
|
|
440
|
+
// artifact form): the id becomes a segment of the durable `epcred.` KV key, whose grammar
|
|
441
|
+
// has no ":".
|
|
442
|
+
credentialId: credentialIdOf(creds),
|
|
443
|
+
credentialKey: identity.id,
|
|
444
|
+
holderActor: pr.actor,
|
|
445
|
+
// A serve credential is minted directly by the provisioner authority, so its §13.1 issuance
|
|
446
|
+
// lineage is the root anchor (not owner/actor principal components).
|
|
447
|
+
sourceChain: ["root"],
|
|
448
|
+
...(validDates.exp !== undefined ? { exp: validDates.exp } : {}),
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
return creds;
|
|
452
|
+
}
|
|
453
|
+
/** A static `agent` mint's listing generation (SPEC 13.15, "Listing issuance"), decided before the
|
|
454
|
+
* credential is signed. Its horizon is the credential's own expiry, so a mint with none gets no
|
|
455
|
+
* listing generation. Bound to no gate: the evidence's expiry is its liveness. */
|
|
456
|
+
async function prepareStaticListing(space, profile, pr, opts, exp) {
|
|
457
|
+
const seam = opts.listingSeam;
|
|
458
|
+
if (!seam)
|
|
459
|
+
return undefined;
|
|
460
|
+
if (profile !== "agent")
|
|
461
|
+
throw new Error(`mintCreds: a listing seam rides the static agent mint only, not "${profile}"`);
|
|
462
|
+
if (opts.issued || opts.listing)
|
|
463
|
+
throw new Error("mintCreds: a listing seam decides the listing generation itself; opts.issued and opts.listing are refused beside it");
|
|
464
|
+
if (exp === undefined)
|
|
465
|
+
return undefined;
|
|
466
|
+
if (!pr.lifecycleUid)
|
|
467
|
+
throw new Error("mintCreds: a listing generation is lifecycle-keyed; mint with opts.lifecycleUid");
|
|
468
|
+
return prepareListing(seam, { space, owner: pr.owner, actor: pr.actor, uid: pr.lifecycleUid, connId: pr.connId, horizon: exp, sources: [], expiresAt: exp }, (binding) => permissionsFor(profile, space, pr, { ...opts, ...(binding ? { listing: binding } : {}) }));
|
|
469
|
+
}
|
|
470
|
+
/** The SPEC 13.15 issuance fence: an issuing mint persists the ceiling it is handing out BEFORE
|
|
471
|
+
* the material is returned, and the material expires by its generation's horizon. The evidence is the minted permission set itself (deny rules
|
|
472
|
+
* included), imported from the same object the JWT was encoded from, so the record and the
|
|
473
|
+
* credential cannot disagree. `sources` name the gates the issuance depends on; an issuance bound
|
|
474
|
+
* to none (a one-shot instrument) carries the credential's own expiry as its liveness. A renewal
|
|
475
|
+
* confirms the existing generation's ceiling is unchanged and records nothing new. */
|
|
476
|
+
async function releaseIssuance(space, profile, pr, opts, perms, exp, credentialId) {
|
|
477
|
+
if (!opts.issued) {
|
|
478
|
+
if (opts.issuance)
|
|
479
|
+
throw new Error("mintCreds: opts.issuance without opts.issued; an issuance names its generation");
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
const seam = opts.issuance;
|
|
483
|
+
if (!seam)
|
|
484
|
+
throw new Error(`mintCreds: an issued "${profile}" mint requires opts.issuance (the evidence store seam); the material is released only after its evidence is durable (SPEC 13.15)`);
|
|
485
|
+
if (!pr.lifecycleUid)
|
|
486
|
+
throw new Error("mintCreds: an issuance is lifecycle-keyed; mint with opts.lifecycleUid");
|
|
487
|
+
const ref = { space, owner: pr.owner, actor: pr.actor, uid: pr.lifecycleUid, generation: opts.issued.generation };
|
|
488
|
+
// Every credential minted on a generation ends by its horizon: past it the generation authorizes
|
|
489
|
+
// nothing and its rows may be gone, so material outliving it would ride a dead binding.
|
|
490
|
+
if (exp === undefined || exp > issuedHorizon(ref.generation))
|
|
491
|
+
throw new Error(`mintCreds: an issued credential must expire by its generation's horizon ${issuedHorizon(ref.generation)} (SPEC 13.15)`);
|
|
492
|
+
const permissions = importNativeSubjectPermissions(perms);
|
|
493
|
+
if (seam.mode === "renew") {
|
|
494
|
+
await seam.store.confirm(ref, permissions);
|
|
495
|
+
await seam.finalize?.(credentialId);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
// The spawn bound reads an issuance with no source and no presence key of its own as an operator
|
|
499
|
+
// instrument (grant-bound.ts, issuedSpawnerStanding), so only an instrument profile is issued that
|
|
500
|
+
// way. Any other profile issued without a source must carry its own presence key.
|
|
501
|
+
if (seam.sources.length === 0 && !INSTRUMENT_PROFILES.has(profile) && !issuedPermitsPattern(permissions.publish, presenceKeySubject(space, pr.owner, pr.actor)))
|
|
502
|
+
throw new Error(`mintCreds: a "${profile}" issuance with no source must carry its own presence key, or the spawn bound would read it as an operator instrument (SPEC 13.15)`);
|
|
503
|
+
const prepared = await seam.store.stage({
|
|
504
|
+
version: 1,
|
|
505
|
+
ref,
|
|
506
|
+
sources: seam.sources,
|
|
507
|
+
permissions,
|
|
508
|
+
...(seam.sources.length === 0 ? { expiresAt: exp } : {}),
|
|
509
|
+
});
|
|
510
|
+
await seam.store.release(prepared, async () => { await seam.finalize?.(credentialId); });
|
|
511
|
+
await writeAcceptedRow(seam.accepted, opts.issued.acceptedToken, ref);
|
|
512
|
+
}
|
|
513
|
+
/** Issue a host-signed NATS user JWT for a caller-generated nkey. The private seed stays with
|
|
514
|
+
* the remote manager. This is deliberately narrower than {@link mintCreds}: only the typed remote
|
|
515
|
+
* manager protocol may request it, and every profile still goes through the same permission and
|
|
516
|
+
* lifetime builders. It signs with the space account's signing key alone, so a host that holds
|
|
517
|
+
* only that key passes no placeholder broker trust. */
|
|
518
|
+
export async function mintPublicUserJwt(auth, publicId, profile, opts) {
|
|
519
|
+
if (!isUserNkey(publicId))
|
|
520
|
+
throw new Error("mintPublicUserJwt: publicId must be a user nkey");
|
|
521
|
+
if (!isEnvironmentManagerProfile(profile) && !["remote-manager", "endpoint-serve", "goal-writer", "session-ledger", "session-serving", "retirement-requester", "run-driver", "run-mediator", "run-operator", "transfer-reader"].includes(profile))
|
|
522
|
+
throw new Error(`mintPublicUserJwt: profile "${profile}" is not part of the closed remote manager protocol`);
|
|
523
|
+
const pr = {
|
|
524
|
+
owner: opts.principal?.owner ?? DEV_OWNER,
|
|
525
|
+
actor: opts.principal?.actor ?? publicId,
|
|
526
|
+
connId: publicId,
|
|
527
|
+
...(opts.lifecycleUid ? { lifecycleUid: opts.lifecycleUid } : {}),
|
|
528
|
+
};
|
|
529
|
+
const perms = profile === "endpoint-serve"
|
|
530
|
+
? endpointServePermissions(auth.space, pr, opts)
|
|
531
|
+
: permissionsFor(profile, auth.space, pr, opts);
|
|
532
|
+
const validDates = userValidDates(profile, opts);
|
|
533
|
+
if (validDates.exp === undefined)
|
|
534
|
+
throw new Error(`mintPublicUserJwt: profile "${profile}" must be bounded`);
|
|
535
|
+
const jwt = await encodeUser(profile, fromPublic(publicId), fromPublic(auth.account.pub), { ...perms, tags: userTags(profile, pr) }, { signer: nativeNkeySigner(new TextEncoder().encode(auth.account.signingSeed)), ...validDates });
|
|
536
|
+
// Same composed-credential bound as mintCreds (see MAX_MINTED_JWT_BYTES): this JWT is presented
|
|
537
|
+
// on a real CONNECT line by the remote manager, so it is priced against the same budget before
|
|
538
|
+
// any fallible finalize step below. None of this function's profiles read allowSubscribe/
|
|
539
|
+
// allowPublish today (each returns through its own dedicated permission builder), so the count
|
|
540
|
+
// is always 0 here - the check stays live in case a future profile addition changes that.
|
|
541
|
+
const jwtBytes = Buffer.byteLength(jwt, "utf8");
|
|
542
|
+
if (jwtBytes > MAX_MINTED_JWT_BYTES) {
|
|
543
|
+
const channelCount = (opts.allowSubscribe?.length ?? 0) + (opts.allowPublish?.length ?? 0);
|
|
544
|
+
throw new Error(`mintPublicUserJwt: minted JWT is ${jwtBytes} bytes, exceeding the ${MAX_MINTED_JWT_BYTES}-byte ` +
|
|
545
|
+
`mint bound (${channelCount} allowSubscribe+allowPublish channel(s)) - the composed credential ` +
|
|
546
|
+
`would exceed the broker's CONNECT line and the connect would hang silently (issue #375)`);
|
|
547
|
+
}
|
|
548
|
+
if (profile === "endpoint-serve") {
|
|
549
|
+
if (!opts.serveIssuance)
|
|
550
|
+
throw new Error("mintPublicUserJwt: endpoint-serve requires serveIssuance");
|
|
551
|
+
await finalizeServeIssuance(opts.serveIssuance, opts.endpointServe, {
|
|
552
|
+
credentialId: credentialIdOf(jwt),
|
|
553
|
+
credentialKey: publicId,
|
|
554
|
+
holderActor: pr.actor,
|
|
555
|
+
sourceChain: ["root"],
|
|
556
|
+
exp: validDates.exp,
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
return { jwt, exp: validDates.exp };
|
|
560
|
+
}
|
|
561
|
+
/** Host-only service-callout mint. The host authenticates the connection and bearer, fixes
|
|
562
|
+
* expiry before authority reads, and keeps this JWT inside its encrypted authorization response.
|
|
563
|
+
* Native root reauthorization and natkey recording remain the host's final release obligations.
|
|
564
|
+
*/
|
|
565
|
+
export async function mintServiceCalloutJwt(auth, args) {
|
|
566
|
+
const connection = parseServiceConnectionBinding(args.connection), inboxNonce = assertInboxConnId(args.inboxNonce);
|
|
567
|
+
const principal = { ...args.principal }, { serve, gate, admittedAt, accessExpiresAt, expiresAt } = args;
|
|
568
|
+
const now = Math.floor(Date.now() / 1000);
|
|
569
|
+
if (![admittedAt, accessExpiresAt, expiresAt].every((v) => Number.isSafeInteger(v) && v > 0)
|
|
570
|
+
|| admittedAt > now || expiresAt <= now || expiresAt > accessExpiresAt || expiresAt > admittedAt + SERVICE_ACCESS_TTL_SECONDS)
|
|
571
|
+
throw new Error("service callout mint requires the original admission-bounded expiry");
|
|
572
|
+
const identity = principalKey(principal.owner, principal.actor);
|
|
573
|
+
const snapshot = assertServeGrantMintable(serve, { space: auth.space, holderOwner: principal.owner });
|
|
574
|
+
if (snapshot.journalClass || snapshot.pools.length || snapshot.commands.some((command) => serve.surface[command].class !== "ephemeral"))
|
|
575
|
+
throw new Error("service callout mint supports only standalone ephemeral serving grants");
|
|
576
|
+
const permissions = endpointServePermissions(auth.space, { ...principal, connId: inboxNonce }, { endpointServe: serve, serveIssuance: gate });
|
|
577
|
+
const jwt = await encodeUser(identity.name, fromPublic(connection.userNkey), fromPublic(auth.account.pub), { ...permissions, tags: principalTags(principal.owner, principal.actor) }, { signer: nativeNkeySigner(new TextEncoder().encode(auth.account.signingSeed)), exp: expiresAt });
|
|
578
|
+
if (Buffer.byteLength(jwt, "utf8") > MAX_MINTED_JWT_BYTES)
|
|
579
|
+
throw new Error("service callout mint exceeds the native JWT byte limit");
|
|
580
|
+
const credentialId = credentialIdOf(jwt);
|
|
581
|
+
await finalizeServeIssuance(gate, serve, { credentialId, credentialKey: connection.userNkey,
|
|
582
|
+
serviceConnection: connection, holderActor: principal.actor, sourceChain: ["root"], exp: expiresAt });
|
|
583
|
+
if (expiresAt <= Math.floor(Date.now() / 1000))
|
|
584
|
+
throw new Error("service callout mint expired before release; its fixed expiry is not extended");
|
|
585
|
+
return { jwt, credentialId, iat: decode(jwt).iat, exp: expiresAt };
|
|
586
|
+
}
|
|
587
|
+
/** Mint the scoped `membership-observer` creds — a SYSTEM-account user (conn A of the graph feed),
|
|
588
|
+
* signed with the in-memory `auth.sys.signingSeed` from a fresh {@link createSpaceAuth}. THROWS if that
|
|
589
|
+
* seed is absent (a re-`up` of an already-provisioned space, whose `$SYS` seed was discarded at its
|
|
590
|
+
* original `up`): the observer can only be minted at the (re-)provision that creates the account — a
|
|
591
|
+
* documented migration property, not a silent no-op. The CONNZ/event subjects pin the DATA account id
|
|
592
|
+
* (`auth.account.pub`). Mirrors {@link mintCreds} but issues into the system account. */
|
|
593
|
+
export async function mintMembershipObserverCreds(auth, identity, opts = {}) {
|
|
594
|
+
if (!auth.sys.signingSeed)
|
|
595
|
+
throw new Error("mintMembershipObserverCreds: no in-memory system-account signing seed - the observer can only be minted from a system account that is being (re)provisioned, because the trust record carries no $SYS seed. Rotate the system account to mint a fresh one (`cotal down` then `cotal up --rotate-sys`); a plain re-`up` reuses the existing account and its existing creds.");
|
|
596
|
+
const signer = nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed));
|
|
597
|
+
const perms = membershipObserverPermissions(auth.account.pub);
|
|
598
|
+
// Bounded exp: the observer is `rotation-renewed` — it carries the matrix's default
|
|
599
|
+
// lifetime so a copied cred becomes broker-dead, but there is NO online renewal (the $SYS seed is
|
|
600
|
+
// gone after `up`); renewal is a coordinated system-account rotation + restart.
|
|
601
|
+
const validDates = userValidDates("membership-observer", opts);
|
|
602
|
+
const userJwt = await encodeUser("membership-observer", fromPublic(identity.id), fromPublic(auth.sys.pub), perms, { signer, ...validDates });
|
|
603
|
+
const creds = fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed)));
|
|
604
|
+
return new TextDecoder().decode(creds);
|
|
605
|
+
}
|
|
606
|
+
/** Host-only read-only census credential. A registered system signer is required; no fallback
|
|
607
|
+
* to a broader observer or eviction credential. Reissuing with a retained registered signer
|
|
608
|
+
* needs no broker restart. The helper does not discover or persist that signer.
|
|
609
|
+
*/
|
|
610
|
+
export async function mintAccountCensusCreds(auth, identity, opts = {}) {
|
|
611
|
+
const prefix = accountCensusInboxPrefix(auth.account.pub);
|
|
612
|
+
if (!auth.sys.signingSeed)
|
|
613
|
+
throw new Error("account census requires the registered system-account signer");
|
|
614
|
+
const { exp } = userValidDates("account-census", opts), now = Math.floor(Date.now() / 1000);
|
|
615
|
+
if (exp === undefined || !Number.isSafeInteger(exp) || exp <= now || exp > now + FIVE_MINUTES)
|
|
616
|
+
throw new Error("account census requires a bounded future credential expiry");
|
|
617
|
+
const user = fromSeed(new TextEncoder().encode(identity.seed));
|
|
618
|
+
if (!isUserNkey(identity.id) || user.getPublicKey() !== identity.id)
|
|
619
|
+
throw new Error("account census identity does not match its user key");
|
|
620
|
+
const jwt = await encodeUser("account-census", fromPublic(identity.id), fromPublic(auth.sys.pub), {
|
|
621
|
+
pub: { allow: [connzRequestSubject(auth.account.pub)] }, sub: { allow: [`${prefix}.>`] },
|
|
622
|
+
}, { signer: nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed)), exp });
|
|
623
|
+
if (exp <= Math.floor(Date.now() / 1000))
|
|
624
|
+
throw new Error("account census credential expired before release");
|
|
625
|
+
return new TextDecoder().decode(fmtCreds(jwt, user));
|
|
626
|
+
}
|
|
627
|
+
/** Mint the scoped `connection-evictor` creds — the kick-only SYSTEM-account user for live
|
|
628
|
+
* eviction. Same mint-only-at-provision property as the observer (the $SYS seed is in-memory
|
|
629
|
+
* only), same fail-loud when it's absent. Paired with the observer at `up`. */
|
|
630
|
+
export async function mintConnectionEvictorCreds(auth, identity, opts = {}) {
|
|
631
|
+
if (!auth.sys.signingSeed)
|
|
632
|
+
throw new Error("mintConnectionEvictorCreds: no in-memory system-account signing seed - the evictor can only be minted from a system account that is being (re)provisioned, because the trust record carries no $SYS seed. Rotate the system account to mint a fresh one (`cotal down` then `cotal up --rotate-sys`); a plain re-`up` reuses the existing account and its existing creds.");
|
|
633
|
+
const signer = nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed));
|
|
634
|
+
// Bounded exp: `rotation-renewed`, same posture as the observer above.
|
|
635
|
+
const validDates = userValidDates("connection-evictor", opts);
|
|
636
|
+
const userJwt = await encodeUser("connection-evictor", fromPublic(identity.id), fromPublic(auth.sys.pub), connectionEvictorPermissions(), { signer, ...validDates });
|
|
637
|
+
const creds = fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed)));
|
|
638
|
+
return new TextDecoder().decode(creds);
|
|
639
|
+
}
|
|
640
|
+
export { principalOf };
|
|
641
|
+
//# sourceMappingURL=provision-jwt.js.map
|