@cotal-ai/core 0.166.3 → 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.
Files changed (88) hide show
  1. package/dist/agent-endpoint.d.ts +242 -0
  2. package/dist/agent-endpoint.d.ts.map +1 -0
  3. package/dist/agent-endpoint.js +183 -0
  4. package/dist/agent-endpoint.js.map +1 -0
  5. package/dist/backup-config.d.ts +2 -2
  6. package/dist/endpoint-call.d.ts +36 -1
  7. package/dist/endpoint-call.d.ts.map +1 -1
  8. package/dist/endpoint-call.js +218 -116
  9. package/dist/endpoint-call.js.map +1 -1
  10. package/dist/endpoint-cluster.d.ts +6 -1
  11. package/dist/endpoint-cluster.d.ts.map +1 -1
  12. package/dist/endpoint-cluster.js +25 -1
  13. package/dist/endpoint-cluster.js.map +1 -1
  14. package/dist/endpoint-delivery-lease.d.ts +184 -0
  15. package/dist/endpoint-delivery-lease.d.ts.map +1 -0
  16. package/dist/endpoint-delivery-lease.js +270 -0
  17. package/dist/endpoint-delivery-lease.js.map +1 -0
  18. package/dist/endpoint-envelope.d.ts +4 -3
  19. package/dist/endpoint-envelope.d.ts.map +1 -1
  20. package/dist/endpoint-envelope.js +19 -2
  21. package/dist/endpoint-envelope.js.map +1 -1
  22. package/dist/endpoint-grants.d.ts +31 -1
  23. package/dist/endpoint-grants.d.ts.map +1 -1
  24. package/dist/endpoint-grants.js +62 -1
  25. package/dist/endpoint-grants.js.map +1 -1
  26. package/dist/endpoint-presence.d.ts +296 -0
  27. package/dist/endpoint-presence.d.ts.map +1 -0
  28. package/dist/endpoint-presence.js +784 -0
  29. package/dist/endpoint-presence.js.map +1 -0
  30. package/dist/endpoint-provenance.d.ts +11 -0
  31. package/dist/endpoint-provenance.d.ts.map +1 -0
  32. package/dist/endpoint-provenance.js +20 -0
  33. package/dist/endpoint-provenance.js.map +1 -0
  34. package/dist/endpoint-serve.d.ts +76 -2
  35. package/dist/endpoint-serve.d.ts.map +1 -1
  36. package/dist/endpoint-serve.js +332 -147
  37. package/dist/endpoint-serve.js.map +1 -1
  38. package/dist/endpoint-service.d.ts +5 -1
  39. package/dist/endpoint-service.d.ts.map +1 -1
  40. package/dist/endpoint-service.js +2 -1
  41. package/dist/endpoint-service.js.map +1 -1
  42. package/dist/endpoint-subjects.d.ts +76 -2
  43. package/dist/endpoint-subjects.d.ts.map +1 -1
  44. package/dist/endpoint-subjects.js +113 -2
  45. package/dist/endpoint-subjects.js.map +1 -1
  46. package/dist/endpoint-verbs.d.ts +1 -1
  47. package/dist/endpoint-verbs.d.ts.map +1 -1
  48. package/dist/endpoint-verbs.js +1 -1
  49. package/dist/endpoint-verbs.js.map +1 -1
  50. package/dist/endpoint.d.ts +132 -188
  51. package/dist/endpoint.d.ts.map +1 -1
  52. package/dist/endpoint.js +380 -790
  53. package/dist/endpoint.js.map +1 -1
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +1 -0
  57. package/dist/index.js.map +1 -1
  58. package/dist/peer-label.d.ts +6 -5
  59. package/dist/peer-label.d.ts.map +1 -1
  60. package/dist/peer-label.js +7 -6
  61. package/dist/peer-label.js.map +1 -1
  62. package/dist/provision-jwt.d.ts +518 -0
  63. package/dist/provision-jwt.d.ts.map +1 -0
  64. package/dist/provision-jwt.js +641 -0
  65. package/dist/provision-jwt.js.map +1 -0
  66. package/dist/provision-permissions.d.ts +72 -0
  67. package/dist/provision-permissions.d.ts.map +1 -0
  68. package/dist/provision-permissions.js +2009 -0
  69. package/dist/provision-permissions.js.map +1 -0
  70. package/dist/provision-resources.d.ts +66 -0
  71. package/dist/provision-resources.d.ts.map +1 -0
  72. package/dist/provision-resources.js +61 -0
  73. package/dist/provision-resources.js.map +1 -0
  74. package/dist/provision-server-config.d.ts +115 -0
  75. package/dist/provision-server-config.d.ts.map +1 -0
  76. package/dist/provision-server-config.js +169 -0
  77. package/dist/provision-server-config.js.map +1 -0
  78. package/dist/provision.d.ts +19 -701
  79. package/dist/provision.d.ts.map +1 -1
  80. package/dist/provision.js +4 -2835
  81. package/dist/provision.js.map +1 -1
  82. package/dist/subjects.d.ts +3 -2
  83. package/dist/subjects.d.ts.map +1 -1
  84. package/dist/subjects.js +10 -2
  85. package/dist/subjects.js.map +1 -1
  86. package/dist/types.d.ts +11 -0
  87. package/dist/types.d.ts.map +1 -1
  88. package/package.json +1 -1
package/dist/provision.js CHANGED
@@ -14,2839 +14,8 @@
14
14
  * Every credential kind is classified in {@link CREDENTIAL_LIFETIMES}: its lifetime class, default
15
15
  * expiry and renewal owner.
16
16
  */
17
- import { eventPayloadReadSubjects, eventPayloadStream, eventPayloadSubject } from "./event-payloads.js";
18
- import { TTL_RECONCILE_CANARY_KEY, ttlBuckets } from "./streams.js";
19
- import { decodeNatsJwt, nativeNkeySigner } from "./nkey-signer.js";
20
- import { spaceDeletionStreams } from "./space-deletion-targets.js";
21
- import { BROKER_USER_INFO_SUBJECT } from "./broker-identity.js";
22
- import { randomBytes } from "node:crypto";
23
- import { isAbsolute } from "node:path";
24
- import { decode, encodeOperator, encodeAccount, encodeUser, fmtCreds, } from "@nats-io/jwt";
25
- import { createOperator, createAccount, fromPublic, fromSeed } from "@nats-io/nkeys";
26
- import { token, spacePrefix, chatSubject, assertValidChannel, resolveReadAcl, principalKey, deprovisionTargetPrincipal, principalTags, assertInboxConnId, DEV_OWNER, unicastSubject, anycastSubject, controlServiceSubject, CONTROL_DELIVERY, CONTROL_DELIVERY_ADMIN, artifactBucket, objectStoreStream, chatStream, dmStream, taskStream, dlvStream, inboxStream, chatHistDurable, historyReaderConsumer, HISTORY_READERS, dmDurable, taskDurable, dlvDurable, presenceBucket, presenceKeySubject, channelBucket, membersBucket, aclBucket, aclKey, memberKey, assertLifecycleToken, membershipBucket, deliveryBucket, managerBucket, MANAGER_LEASE_KEY, MANAGER_RENEWAL_LEASE_KEY, connzRequestSubject, accountCensusInboxPrefix, accountConnectSubject, accountDisconnectSubject, MEMBERSHIP_INBOX_PREFIX, INBOX_READER_DURABLE, livenessSubject, livenessServeFilter, livenessReplyGrant, isTransferStream, takeSubject, takeServeFilter, takeReplyGrant, anycastBucket, } from "./subjects.js";
27
- import { LIVENESS_PLANES } from "./liveness.js";
28
- import { epCallerGrantRows, epServeGrantRows, epBaselineGrantRows, baselineCallerCapabilities, spawnCallerCapabilities, runCallerCapabilities, epRequestGrantRows, operatorInstrumentCapabilities, instanceOnlyManagerCapabilities, epDescribeAllGrantRow, BASELINE_LIFECYCLE_ENDPOINT, MANAGER_VITALS_COMMAND, MANAGER_VITALS_SCOPE, } from "./endpoint-grants.js";
29
- import { assertServeGrantMintable, finalizeServeIssuance } from "./endpoint-service.js";
30
- import { parseServiceConnectionBinding } from "./service-gate.js";
31
- import { SERVICE_ACCESS_TTL_SECONDS } from "./service-authority-limits.js";
32
- import { effectsBindGrants, poolOwnerBindGrants, goalWriterGrants, sessionLedgerGrants, epAuthBucket, epcStreamName, endpointPlaneStreamNames, eptReqStreamName, eptStreamName, hardenedAuthorityStreamNames, timerWriterDurable, timerWriterGrants } from "./endpoint-binding.js";
33
- import { epsSubject, epCallerReplyFilter, assertGeneration, isIssuedCaller, AUTH_ENDPOINT, EP_CMD_RETIRE_LIFECYCLE } from "./endpoint-subjects.js";
34
- import { acceptedReadGrant, acceptedBucket, importNativeSubjectPermissions, issuedBucket, issuedHorizon, issuedPermitsPattern, issuedStoreStreamNames, prepareListing, writeAcceptedRow } from "./issued-authority.js";
35
- import { REGISTRY_ENDPOINTS_GRANT } from "./registry-contract.js";
36
- import { admissionBucket, admissionKey, revocationKey } from "./run-admission.js";
37
- import { runSubmissionKey } from "./run-submission.js";
38
- import { runDriverGrants, runMediatorGrants, runOperatorGrants } from "./run-driver-grants.js";
39
- import { transferReaderGrants, transferWriterGrants } from "./transfer.js";
40
- import { recordsBucket, recordSpecKey, recordStatusKey, recordAtomicKey, RECORD_KINDS, GOVERN_HEAD } from "./endpoint-records.js";
41
- import { lifecycleHeadKey, uidReservationKey, issuanceGateKey, staticSlotKey, STATIC_SLOT_PREFIX, epgateKey, epcredFamilyPrefix, eprepairKey, credentialIdOf } from "./lifecycle-state.js";
42
- import { environmentManagerPermissions, isEnvironmentManagerProfile } from "./environment-manager-grants.js";
43
- import { credsClaims, isAccountNkey, isUserNkey } from "./identity.js";
44
- import { backupProfilePermissions, restoreProfilePermissions, snapshotAckGrant, } from "./backup.js";
45
- const FIVE_MINUTES = 5 * 60;
46
- /** The broker's pre-auth control-line cap, in bytes (`max_control_line` in the generated config —
47
- * `openServerConfig` and `serverConfig` below both render this literal, so the cap and the
48
- * mint-time bound derived from it below can never drift). 64 KiB clears a many-channel agent
49
- * JWT (~4-8 KB) with wide margin while keeping the pre-auth allocation ~16x tighter than 1 MB
50
- * under connection flooding (the CONNECT line is parsed BEFORE auth). */
51
- export const MAX_CONTROL_LINE_BYTES = 65536;
52
- /** The fixed bytes a NATS client wraps around the `jwt` field on the CONNECT protocol line, over
53
- * and above the JWT itself: the JSON object's other keys (`nkey`, `sig`, `name`, `lang`,
54
- * `version`, `protocol`, `verbose`, `pedantic`, `no_responders`, `headers`), their values, and
55
- * the surrounding braces/quotes/commas. Measured live (nats-server `-DV`, the trace of the raw
56
- * protocol) on a real connect with the nats.js v3 client: a control-name credential produced a
57
- * 5,104-byte JWT inside a 5,291-byte CONNECT line — 187 bytes of envelope, reproduced twice.
58
- * Rounded up generously (>2.5x) to absorb client/library variation this repo does not control. */
59
- export const CONNECT_ENVELOPE_OVERHEAD_BYTES = 512;
60
- /** The mint-time budget for a user JWT's byte size: every composition that inflates the JWT (a
61
- * long single channel, many channels, the per-agent event channel, any grant a later change
62
- * adds) is priced against the SAME number, because the credential is what the client sends on
63
- * the CONNECT line and the CONNECT line is what the broker caps — not any one contributor to it.
64
- * `assertValidName`/`assertValidChannel` bound one input each; this bounds the OUTPUT, closing
65
- * the gap between "every individual grant is legal" and "the composed credential still fits"
66
- * (issue #375's review finding: six distinct 4096-char channels, each individually accepted,
67
- * minted a JWT the broker would silently drop). */
68
- export const MAX_MINTED_JWT_BYTES = MAX_CONTROL_LINE_BYTES - CONNECT_ENVELOPE_OVERHEAD_BYTES;
69
- /** Bounded lifetime for `standing-renewable` credentials whose renewal owner is ONLINE:
70
- * the holder (or its launcher) re-mints at 75% of the lifetime via the endpoint's creds-source seam,
71
- * so a copied cred is broker-dead within a day while renewal never involves an operator. 24h keeps
72
- * the remaining-25% loud-failure window at ~6h — wide enough to notice and repair before expiry. */
73
- export const STANDING_RENEWABLE_TTL_SEC = 24 * 60 * 60;
74
- /** Bounded lifetime for the `rotation-renewed` $SYS credentials (membership-observer + connection-
75
- * evictor). They are NOT online-renewable (the $SYS seed dies at end of `up`), so this exp is the
76
- * credential-death horizon: a copied observer/evictor cred becomes broker-dead after it, and the
77
- * operator is expected to have run a coordinated system-account rotation + broker restart within it
78
- * (the doctor surface warns ahead). 30 days balances "copied cred eventually dies" against
79
- * a comfortable monthly rotation cadence; tune here as one named knob. */
80
- export const ROTATION_RENEWED_TTL_SEC = 30 * 24 * 60 * 60;
81
- /** The credential lifetime matrix. This is intentionally centralized so every new mint profile must classify its
82
- * credential-death behavior instead of silently inheriting non-expiring static creds. */
83
- export const CREDENTIAL_LIFETIMES = {
84
- 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" },
85
- "manager-caller": { class: "mixed", note: "short-lived user-auth view bound to the bearer expiry and one manager instance" },
86
- observer: { class: "static-operator-managed", note: "out-of-band dashboard/audit credential from `cotal mint`" },
87
- admin: { class: "static-operator-managed", note: "out-of-band elevated dashboard/audit credential from `cotal mint`" },
88
- 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" },
89
- 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" },
90
- "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" },
91
- provisioner: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "setup/spawn provisioning window only" },
92
- deprovisioner: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "target-pinned teardown window only" },
93
- "retirement-requester": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one despawn's retirement request window; request+reply only" },
94
- "lifecycle-executor": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one static lifecycle operation's 13.1 state-write window (activation / terminal / renewal ledger append)" },
95
- "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))" },
96
- operator: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "send/dm/join/probe-style operator command" },
97
- purger: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "history purge command" },
98
- backup: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "offline snapshot phase; exact stream and delivery subject, memory-only" },
99
- restore: { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "offline restore initiation or exact-ID upload phase, memory-only" },
100
- probe: { class: "one-shot", defaultTtlSeconds: 60, note: "connect-only preflight" },
101
- "channel-writer": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "channel registry mutation command" },
102
- "channel-purger": { class: "mixed", note: "one-shot for CLI, standing inside web; split or renewal required before default exp" },
103
- teardown: { class: "one-shot", note: "space teardown can be long/destructive; needs TTL budget/remint guard before default exp" },
104
- "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" },
105
- "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" },
106
- "control-caller-privileged": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "ps/start control call" },
107
- "control-caller-admin": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "stop/attach admin control call" },
108
- deployer: { class: "one-shot", note: "manifest deploy spans planning/launch/ledger; needs near-expiry guard or remint before default exp" },
109
- "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" },
110
- "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" },
111
- "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" },
112
- "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" },
113
- "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" },
114
- "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)" },
115
- "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" },
116
- "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" },
117
- "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" },
118
- "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" },
119
- 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)" },
120
- "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" },
121
- "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" },
122
- "transfer-reader": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one transcript-receive or sweep over the minting instance's own transfer bucket" },
123
- "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" },
124
- "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" },
125
- "environment-bootstrap": { class: "one-shot", defaultTtlSeconds: FIVE_MINUTES, note: "one admitted environment's bootstrap caller; explicit expiry capped by admission and five minutes" },
126
- "environment-manager-supervisor": { class: "standing-renewable", renewalOwner: "environment-authority", note: "own lease/presence/liveness; explicit expiry capped by admission, no auth-store access" },
127
- "environment-manager-executor": { class: "standing-renewable", renewalOwner: "environment-authority", note: "own admitted authority instance RPC; explicit expiry capped by admission, no direct store access" },
128
- "environment-manager-goal-writer": { class: "standing-renewable", renewalOwner: "environment-authority", note: "manager goal rows without the auth-read belt; explicit expiry capped by admission" },
129
- "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" },
130
- "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" },
131
- "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" },
132
- };
133
- // RUNTIME integrity (the afa715b class): the matrix and every policy freeze at module load
134
- // (a post-import `defaultTtlSeconds = undefined` would otherwise mint a NON-EXPIRING credential
135
- // out of a one-shot profile, executed repro), and the mint path below reads a PRIVATE TTL
136
- // snapshot taken here, never the live export.
137
- for (const p of Object.values(CREDENTIAL_LIFETIMES))
138
- Object.freeze(p);
139
- Object.freeze(CREDENTIAL_LIFETIMES);
140
- const LIFETIME_TTL_SNAP = new Map(Object.entries(CREDENTIAL_LIFETIMES).map(([k, p]) => [k, p.defaultTtlSeconds]));
141
- export function credentialLifetime(kind) {
142
- return CREDENTIAL_LIFETIMES[kind];
143
- }
144
- export function inspectCredHealth(creds, nowSec = Math.floor(Date.now() / 1000)) {
145
- let claims;
146
- try {
147
- claims = credsClaims(creds);
148
- }
149
- catch (e) {
150
- return { state: "unreadable", error: e.message };
151
- }
152
- const { iat, exp } = claims;
153
- if (typeof exp !== "number")
154
- return { state: "unbounded", iat };
155
- if (typeof iat !== "number")
156
- return { state: "unreadable", iat: undefined, exp, error: "user JWT carries exp but no iat - cannot place the renewal point" };
157
- const renewAt = Math.floor(iat + 0.75 * (exp - iat));
158
- if (nowSec >= exp)
159
- return { state: "expired", iat, exp, renewAt };
160
- if (nowSec >= renewAt)
161
- return { state: "near-expiry", iat, exp, renewAt };
162
- return { state: "healthy", iat, exp, renewAt };
163
- }
164
- /** Compose the read view from its two persisted authorities. Fails loud when the space account was
165
- * not signed by THIS broker's operator: a self-consistent account signed by a FOREIGN operator is
166
- * perfectly valid on its own and would otherwise be rendered into the resolver as untrusted trust. */
167
- export function composeSpaceAuth(broker, spaceAccount) {
168
- assertAccountSignedByBroker(broker, spaceAccount);
169
- return { ...broker, ...spaceAccount };
170
- }
171
- /** The binding check behind {@link composeSpaceAuth} and registry admission: this space's data
172
- * account JWT must be issued by this broker's operator identity. */
173
- export function assertAccountSignedByBroker(broker, spaceAccount) {
174
- if (!broker.operator.seed)
175
- throw new Error("assertAccountSignedByBroker: broker operator material is required to verify the account binding");
176
- let operatorPub;
177
- try {
178
- operatorPub = nativeNkeySigner(new TextEncoder().encode(broker.operator.seed)).getPublicKey();
179
- }
180
- catch {
181
- throw new Error("assertAccountSignedByBroker: the broker operator seed is not a valid operator seed");
182
- }
183
- const claims = decodeNatsJwt(spaceAccount.account.jwt);
184
- if (claims.iss !== operatorPub)
185
- 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`);
186
- }
187
- // Unlimited account limits — without explicit limits a JWT account defaults to 0 conns
188
- // (every connect denied). JetStream needs storage on the data account but MUST stay off
189
- // the system account (the server refuses to start otherwise).
190
- const BASE_LIMITS = {
191
- subs: -1, conn: -1, leaf: -1, imports: -1, exports: -1,
192
- data: -1, payload: -1, wildcards: true,
193
- };
194
- const DATA_LIMITS = { ...BASE_LIMITS, mem_storage: -1, disk_storage: -1 };
195
- const SYS_LIMITS = { ...BASE_LIMITS, mem_storage: 0, disk_storage: 0 };
196
- /** Reduce a {@link SpaceAuth} to just the material a *minting* host needs: `space`,
197
- * `account.pub`, and `account.signingSeed` (the only fields {@link mintCreds} reads).
198
- * The operator root-of-trust, system account, and the account's own seed are blanked.
199
- *
200
- * This is the file you hand a manager that should mint per-agent creds but must never
201
- * hold the operator key — e.g. a containerized team. A leaked stripped file only lets
202
- * someone mint *users within this one account*, which the account boundary already
203
- * contains; it cannot mint new accounts or touch the system account. */
204
- export function stripSpaceAuth(auth) {
205
- return {
206
- space: auth.space,
207
- operator: { seed: "", jwt: "" },
208
- account: {
209
- pub: auth.account.pub,
210
- seed: "",
211
- jwt: "",
212
- signingSeed: auth.account.signingSeed,
213
- signingPub: "",
214
- },
215
- sys: { pub: "", jwt: "" },
216
- };
217
- }
218
- /** The user public keys a data-account JWT revokes, each with the Unix second it was revoked at. The
219
- * broker refuses a user JWT for that key issued at or before that second. */
220
- export function accountRevocations(accountJwt) {
221
- return { ...decode(accountJwt).nats.revocations };
222
- }
223
- /** Re-issue the data-account JWT with the user key `userPub` revoked at `at` (Unix seconds), keeping
224
- * every other claim. A key already revoked keeps its first time and the auth is returned unchanged.
225
- * The broker applies it when it next loads its configuration. */
226
- export async function revokeAccountUser(auth, userPub, at) {
227
- if (!auth.operator.seed)
228
- throw new Error("revokeAccountUser: the broker operator seed is required - a stripped broker cannot re-sign the space account");
229
- if (!isUserNkey(userPub))
230
- throw new Error("revokeAccountUser: not a user public key");
231
- const claims = decode(auth.account.jwt);
232
- const revocations = claims.nats.revocations ?? {};
233
- if (revocations[userPub] !== undefined)
234
- return auth;
235
- const okp = fromSeed(new TextEncoder().encode(auth.operator.seed));
236
- const jwt = await encodeAccount(claims.name, auth.account.pub, { ...claims.nats, revocations: { ...revocations, [userPub]: at } }, { signer: okp });
237
- return { ...auth, account: { ...auth.account, jwt } };
238
- }
239
- /** Re-issue an account JWT that this broker's operator signed so the account serves nobody: every
240
- * user key issued at or before `at` (Unix seconds) is revoked, and the account admits no client or
241
- * leaf connection, so a user minted later is refused as well. Every other claim is kept, so the
242
- * account's JetStream data stays where it is. Push the result with {@link pushAccountClaim} to stop
243
- * a space on a running full-resolver broker; its live connections close without a reload. */
244
- export async function retireAccountClaim(broker, accountJwt, at) {
245
- if (!broker.operator.seed)
246
- throw new Error("retireAccountClaim: the broker operator seed is required - a stripped broker cannot re-sign the account");
247
- if (!Number.isSafeInteger(at) || at <= 0)
248
- throw new Error("retireAccountClaim: at must be a positive whole number of Unix seconds");
249
- const okp = fromSeed(new TextEncoder().encode(broker.operator.seed));
250
- const claims = decode(accountJwt);
251
- if (claims.iss !== okp.getPublicKey() || !isAccountNkey(claims.sub ?? ""))
252
- throw new Error("retireAccountClaim: the account was not signed by this broker's operator - refusing to re-sign it");
253
- return encodeAccount(claims.name, claims.sub, {
254
- ...claims.nats,
255
- limits: { ...claims.nats.limits, conn: 0, leaf: 0 },
256
- revocations: { ...claims.nats.revocations, "*": at },
257
- }, { signer: okp });
258
- }
259
- /** Rotate the SYSTEM account and re-issue the operator JWT so persisted system-account users (currently
260
- * `membership-observer`) become broker-dead once the broker loads the returned auth. The fresh
261
- * `sys.signingSeed` is intentionally in-memory only; callers must mint replacement observer creds before
262
- * persisting via `saveSpaceAuth`, which strips the seed again. */
263
- export async function rotateSystemAccount(auth) {
264
- if (!auth.operator.seed)
265
- throw new Error("rotateSystemAccount: operator seed material is required (a stripped auth cannot rotate the system account)");
266
- const okp = fromSeed(new TextEncoder().encode(auth.operator.seed));
267
- const syskp = createAccount();
268
- const sysPub = syskp.getPublicKey();
269
- const operatorJwt = await encodeOperator(`cotal-${token(auth.space)}`, okp, { system_account: sysPub });
270
- const sysJwt = await encodeAccount("SYS", syskp, { limits: SYS_LIMITS }, { signer: okp });
271
- // The rotated value IS the next generation of whatever it derived from — persistence refuses a
272
- // sys change that is not the direct successor of the current record (see BrokerAuth.gen). The
273
- // input generation is runtime-validated: persisted records reach here through a bare JSON cast,
274
- // and a string/float/unsafe value would launder through the arithmetic ("0"+1 is "01"; at 2^53,
275
- // gen+1 === gen) and destroy the successor discriminator.
276
- // ONLY absence reads 0 (the pre-generation shape); an explicit null is tampering, same as any
277
- // other malformed value - `?? 0` would launder it into a valid generation-0 predecessor.
278
- const gen = auth.gen === undefined ? 0 : auth.gen;
279
- if (typeof gen !== "number" || !Number.isSafeInteger(gen) || gen < 0)
280
- throw new Error(`rotateSystemAccount: broker generation ${JSON.stringify(gen)} is not a non-negative integer - the loaded record is corrupt; restore it from backup`);
281
- return {
282
- ...auth,
283
- operator: { ...auth.operator, jwt: operatorJwt },
284
- sys: { pub: sysPub, jwt: sysJwt, signingSeed: new TextDecoder().decode(syskp.getSeed()) },
285
- gen: gen + 1,
286
- };
287
- }
288
- /** Generate a fresh BROKER trust root: operator → system account. One per broker, NOT one per space.
289
- * `label` names the operator (cosmetic, but it lands in the operator JWT); multi-space brokers pass
290
- * a broker label, and the single-space compatibility path passes the space name so existing
291
- * operator names are unchanged.
292
- *
293
- * The returned `sys.signingSeed` is the ONLY window in which system-account users (the membership
294
- * observer and the connection evictor) can be minted, because the local filesystem persistence does
295
- * not write it. Callers that need to add spaces later must retain it in a broker-scoped store. */
296
- export async function createBrokerAuth(label) {
297
- const okp = createOperator();
298
- const syskp = createAccount();
299
- const sysPub = syskp.getPublicKey();
300
- const operatorJwt = await encodeOperator(`cotal-${token(label)}`, okp, { system_account: sysPub });
301
- const sysJwt = await encodeAccount("SYS", syskp, { limits: SYS_LIMITS }, { signer: okp });
302
- const dec = (u) => new TextDecoder().decode(u);
303
- return {
304
- operator: { seed: dec(okp.getSeed()), jwt: operatorJwt },
305
- sys: { pub: sysPub, jwt: sysJwt, signingSeed: dec(syskp.getSeed()) },
306
- };
307
- }
308
- /** Generate one space's data account (+ signing key), signed by an EXISTING broker operator. This is
309
- * the per-tenant half of provisioning: call it once per space against the same {@link BrokerAuth}
310
- * to put many spaces on one broker, each in its own NATS account. Key generation and JWT
311
- * construction stay with NATS; the existing native signer derives public keys and signs. */
312
- export async function createSpaceAccountAuth(broker, space) {
313
- if (!broker.operator.seed)
314
- throw new Error("createSpaceAccountAuth: the broker operator seed is required - a stripped broker cannot sign a new space account");
315
- const okp = nativeNkeySigner(new TextEncoder().encode(broker.operator.seed));
316
- const akp = nativeNkeySigner(createAccount().getSeed());
317
- const askp = nativeNkeySigner(createAccount().getSeed()); // account signing key - what mints users
318
- const accountJwt = await encodeAccount(token(space), akp, { signing_keys: [askp.getPublicKey()], limits: DATA_LIMITS }, { signer: okp });
319
- const dec = (u) => new TextDecoder().decode(u);
320
- return {
321
- space,
322
- account: {
323
- pub: akp.getPublicKey(),
324
- seed: dec(akp.getSeed()),
325
- jwt: accountJwt,
326
- signingSeed: dec(askp.getSeed()),
327
- signingPub: askp.getPublicKey(),
328
- },
329
- };
330
- }
331
- /** Generate a fresh operator → account(+signing key) → system-account chain for a space.
332
- * The single-space composition of {@link createBrokerAuth} + {@link createSpaceAccountAuth}: one
333
- * broker whose only tenant is this space. */
334
- export async function createSpaceAuth(space) {
335
- const broker = await createBrokerAuth(space);
336
- const spaceAccount = await createSpaceAccountAuth(broker, space);
337
- return { ...broker, ...spaceAccount };
338
- }
339
- /** The principal tags every user JWT carries, plus one random issuance tag on a goal-writer or
340
- * session-ledger credential. Those two profiles carry no epoch-pinned grant, so two mints for one
341
- * nkey within one second would otherwise sign identical bytes, and their ledger row is keyed by the
342
- * JWT digest: a restart's re-mint would re-sign the credential its barrier just revoked under the
343
- * revoked row's id (SPEC 13.1). */
344
- function userTags(profile, pr) {
345
- const tags = principalTags(pr.owner, pr.actor);
346
- return profile === "goal-writer" || profile === "session-ledger" ? [...tags, `issuance:${randomBytes(16).toString("hex")}`] : tags;
347
- }
348
- /** Compute a minted credential's `{ exp? }` from an explicit override or the centralized matrix
349
- * default. Widened to {@link CredentialKind} (not just {@link Profile}) so the bespoke $SYS minters
350
- * — `membership-observer` / `connection-evictor`, which are kinds, not profiles — thread the same
351
- * bounded-lifetime policy instead of minting non-expiring $SYS creds. */
352
- function userValidDates(kind, opts) {
353
- if (isEnvironmentManagerProfile(kind)) {
354
- const now = Math.floor(Date.now() / 1000);
355
- const admissionExpiry = opts.environmentManager?.expiresAt;
356
- const expiry = opts.expiresAt;
357
- if (typeof admissionExpiry !== "number" || !Number.isSafeInteger(admissionExpiry) || admissionExpiry <= now ||
358
- typeof expiry !== "number" || !Number.isSafeInteger(expiry) || expiry <= now || expiry > admissionExpiry)
359
- throw new Error(`mintCreds: ${kind} requires a current explicit expiresAt no later than admission expiry`);
360
- if (kind === "environment-bootstrap" && expiry > now + FIVE_MINUTES)
361
- throw new Error("mintCreds: environment-bootstrap expiry exceeds its five-minute lifetime");
362
- }
363
- if (opts.expiresAt !== undefined && opts.expiresInSeconds !== undefined)
364
- throw new Error("mintCreds: pass only one of expiresAt or expiresInSeconds");
365
- if (opts.expiresAt !== undefined) {
366
- if (!Number.isInteger(opts.expiresAt) || opts.expiresAt < 0)
367
- throw new Error("mintCreds: expiresAt must be a non-negative integer timestamp (seconds)");
368
- return { exp: opts.expiresAt };
369
- }
370
- const ttl = opts.expiresInSeconds ?? LIFETIME_TTL_SNAP.get(kind);
371
- if (ttl === undefined)
372
- return {};
373
- if (!Number.isInteger(ttl) || ttl <= 0)
374
- throw new Error("mintCreds: expiresInSeconds must be a positive integer");
375
- return { exp: Math.floor(Date.now() / 1000) + ttl };
376
- }
377
- /** Resolve a {@link MintPrincipal} for the STATIC/dev mint path from an {@link Identity} + optional
378
- * explicit principal. No-login dev default: owner = {@link DEV_OWNER} ("local"), actor = the connection
379
- * id, so the agent's lane is `local.<id>`. The connection nkey is always the identity's id here (the
380
- * creds bind to it). User mode does NOT flow through here — the callout mints directly with the
381
- * server-derived owner + ledger actor. */
382
- function principalOf(identity, principal, lifecycleUid) {
383
- return {
384
- owner: principal?.owner ?? DEV_OWNER,
385
- actor: principal?.actor ?? identity.id,
386
- connId: identity.id,
387
- ...(lifecycleUid !== undefined ? { lifecycleUid } : {}),
388
- };
389
- }
390
- /** Onboard an agent for launch (auth mode): pre-create its bind-only DM (+ Plane-3 DELIVER + role
391
- * TASK) durables, RECORD its read ACL in the durable registry (unless `durableMembership:false`), and
392
- * mint its scoped creds. Live delivery is the agent's own core subscription — there is no per-instance
393
- * chat durable. Boot durable MEMBERSHIP is not written here: the agent self-joins its durable channels
394
- * via the server-side delivery daemon's `ctl.delivery` op at connect. A deliberately live-only
395
- * launcher (`durableMembership:false`, e.g. `cotal spawn --live-only`) gets no ACL row, so the
396
- * daemon never authorizes a durable backstop for it. */
397
- export async function provisionAgent(provisioner, auth, identity, opts = {}) {
398
- if (!opts.lifecycleUid)
399
- throw new Error("provisionAgent: a lifecycleUid is required - the agent's broker footprint is lifecycle-keyed (SPEC 13.1); mint one with mintLifecycleUid() and persist it with the agent");
400
- const pr = principalOf(identity, opts.principal, opts.lifecycleUid);
401
- const allowSubscribe = await provisionAgentDurables(provisioner, { owner: pr.owner, actor: pr.actor, lifecycleUid: opts.lifecycleUid }, opts);
402
- return mintCreds(auth, identity, "agent", { ...opts, allowSubscribe });
403
- }
404
- /** The DURABLE half of agent onboarding, principal-keyed and credential-agnostic: pre-create the
405
- * bind-only DM durable and, when the read ACL is nonempty, the DELIVER durable; record the read ACL;
406
- * ensure the role TASK queue. The static
407
- * path ({@link provisionAgent}) follows it with a mint; the USER-MODE spawn path runs it alone —
408
- * a user agent's credential is its bearer (callout-minted per connect), never a static cred.
409
- * Returns the resolved read ACL so both callers scope from the same computed set. */
410
- export async function provisionAgentDurables(provisioner, pr, opts = {}) {
411
- const uid = assertLifecycleToken(pr.lifecycleUid); // hard cut: every provisioned footprint is lifecycle-keyed (SPEC 13.1)
412
- // An omitted/empty read set means NO channels (it does not mean `general`): a caller that names
413
- // no channel gets a footprint with no channel membership and, below, a cred with no channel row.
414
- const subscribe = opts.subscribe ?? [];
415
- // Reject channel names the wire layer would rewrite (the pre-created filter rides token() too).
416
- for (const ch of [...subscribe, ...(opts.allowSubscribe ?? [])])
417
- assertValidChannel(ch);
418
- // Re-assert the load-time invariant at the trust boundary (defense in depth): the pre-created
419
- // live filter (subscribe) must sit within the read ACL (allowSubscribe), or the provisioner
420
- // would hand the agent live delivery it isn't permitted to read.
421
- const allowSubscribe = resolveReadAcl(subscribe, opts.allowSubscribe);
422
- await provisioner.provisionDmInbox(pr.owner, pr.actor, uid);
423
- // The Plane-3 backstop carries channel copies only. A channel-less lifecycle has no authorized
424
- // DLV copy and therefore gets no consumer. Re-granting from [] to nonempty calls the unchanged
425
- // provisioner path, whose DeliverPolicy.All consumer reads every copy written since the re-grant.
426
- if (allowSubscribe.length > 0)
427
- await provisioner.provisionDlvInbox(pr.owner, pr.actor, uid);
428
- // Record the agent's read ACL in the durable registry (the same act as baking it into the JWT) so the
429
- // server-side delivery daemon can re-authorize this agent's durable entries + validate its runtime
430
- // durable-joins — it holds no in-memory ledger. The agent SELF-JOINS its durable boot channels via the
431
- // daemon at connect (no manager-written boot membership). `durableMembership:false` (an explicit
432
- // live-only launcher, e.g. `cotal spawn --live-only`) opts out of the ACL row → the daemon never
433
- // authorizes a durable backstop for it, so it stays live-only.
434
- // ACL is keyed by the lifecycle-scoped dot-form <owner>.<actor>.<uid> (per-incarnation read authority).
435
- // reissueAcl — rides THIS mint: allowSubscribe was just baked into the user JWT above. Separate
436
- // from commitAcl so an ordinary registry writer cannot raise the ceiling by passing a flag
437
- // (SPEC §9.6). Not crypto-bound to the JWT bytes — process discipline that this call stays next
438
- // to the mint.
439
- if (opts.durableMembership !== false) {
440
- await provisioner.reissueAcl(principalKey(pr.owner, pr.actor).key, uid, allowSubscribe);
441
- }
442
- for (const role of taskRoles(opts.role, opts.capabilities))
443
- await provisioner.provisionTaskQueue(role);
444
- return allowSubscribe;
445
- }
446
- const ROLE_CAPABILITY = /^role:([A-Za-z0-9_-]+)$/;
447
- /** The role a `role:<r>` capability token names, or `undefined` for any other token. */
448
- export function capabilityRole(token) {
449
- return ROLE_CAPABILITY.exec(token)?.[1];
450
- }
451
- /** The roles whose task queue an agent credential binds: its own role, and the role of each
452
- * `role:<r>` token in its capabilities, which lets it hand that role on (SPEC 13.15). */
453
- export function taskRoles(role, capabilities) {
454
- const roles = new Set(role ? [role] : []);
455
- for (const token of capabilities ?? []) {
456
- const r = capabilityRole(token);
457
- if (r !== undefined)
458
- roles.add(r);
459
- }
460
- return [...roles];
461
- }
462
- /** Mint a user creds file for an agent {@link Identity} (its stable id+seed from
463
- * {@link newIdentity}). The account signing key signs over ONLY the public key
464
- * (`fromPublic`) — the agent seed is never part of the signature, it's only folded into
465
- * the resulting creds file. The "agent" profile is scoped to publish only as itself and only to
466
- * its declared `allowPublish` channels (post ACL, default-deny), and to read only within
467
- * `allowSubscribe` (live tail bind-only + per-channel history grants). Every profile is now
468
- * enumerated least-privilege — there is no allow-all cred (the former `manager` is deleted). */
469
- export async function mintCreds(auth, identity, profile, opts = {}) {
470
- // For third-party endpoints, an issued static agent credential carries only untargeted,
471
- // unjournaled commands. The static lifecycle terminal has no SPEC 13.1 obligation drain, so a
472
- // targeted or journaled grant could leave accepted work keyed to a retired lifecycle that nothing
473
- // settles. Refused before anything is signed or staged. The guard covers every issued agent mint:
474
- // the managed spawn (through provisionAgent), the managed renewal and the foreground spawn. An
475
- // unissued mint skips it, so a future caller that hands a static agent endpoint commands must mint
476
- // it issued. The guard skips every reference endpoint, meaning any single-label name such as
477
- // `manager` (SPEC 13.2). The skip goes by the name and does not check which command a row names.
478
- // The rows an instance-pinned caller passes here are the manager's own, the ones the `spawn`,
479
- // `run` and `admin` capabilities mint, and issued agent mints carried them before this guard
480
- // existed. A persona cannot name a reference endpoint, so the hand-on path never reaches the skip.
481
- if (profile === "agent" && opts.issued) {
482
- const drained = opts.endpointCapabilities?.find((c) => c.endpoint.includes(".") && (c.target !== undefined || c.journal));
483
- if (drained)
484
- 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)`);
485
- }
486
- const signer = nativeNkeySigner(new TextEncoder().encode(auth.account.signingSeed));
487
- const pr = principalOf(identity, opts.principal, opts.lifecycleUid);
488
- // Serve rows are INTERNAL to mintCreds behind the §13.1 fence: the exported permissionsFor
489
- // refuses "endpoint-serve" (so a direct caller can never obtain unfenced serve rows), and only
490
- // this fenced path calls the row builder.
491
- const validDates = userValidDates(profile, opts);
492
- const listing = await prepareStaticListing(auth.space, profile, pr, opts, validDates.exp);
493
- const perms = profile === "endpoint-serve"
494
- ? endpointServePermissions(auth.space, pr, opts)
495
- : listing?.permissions ?? permissionsFor(profile, auth.space, pr, opts);
496
- const userJwt = await encodeUser(profile, fromPublic(identity.id), fromPublic(auth.account.pub),
497
- // Stamp the principal `tags` so this connection's identity is CONNZ-recoverable by the membership
498
- // feed — the SAME tags the auth callout stamps (user mode), via core's single-source builder. The
499
- // JWT `name` stays the profile label (a debug breadcrumb; not a surfaced/queryable CONNZ field).
500
- { ...perms, tags: userTags(profile, pr) }, { signer, ...validDates });
501
- // Build the credential string FULLY before the fence: nothing fallible may run AFTER a winning
502
- // CAS, or a post-CAS throw would leave a committed ledger row with no released credential (an
503
- // orphan authority record). fmtCreds only wraps the already-signed JWT with the seed, so it is
504
- // done here and the fence is the mint's LAST step.
505
- const creds = new TextDecoder().decode(fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed))));
506
- // The composed-credential bound (SPEC 13.9, issue #375's review finding): every individual grant
507
- // input can pass its own validator (assertValidName, assertValidChannel) and the COMPOSED JWT
508
- // still exceed the CONNECT line the broker caps, because nothing bounded the COUNT of channels
509
- // an agent's allowSubscribe/allowPublish may carry. Refuse here, BEFORE releaseIssuance (the
510
- // file's own no-fallible-work-after-a-winning-CAS rule, stated above) — a refusal here has
511
- // released no ledger row, unlike a refusal after.
512
- const userJwtBytes = Buffer.byteLength(userJwt, "utf8");
513
- if (userJwtBytes > MAX_MINTED_JWT_BYTES) {
514
- const channelCount = (opts.allowSubscribe?.length ?? 0) + (opts.allowPublish?.length ?? 0);
515
- throw new Error(`mintCreds: minted JWT is ${userJwtBytes} bytes, exceeding the ${MAX_MINTED_JWT_BYTES}-byte ` +
516
- `mint bound (${channelCount} allowSubscribe+allowPublish channel(s)) - the composed credential ` +
517
- `would exceed the broker's CONNECT line and the connect would hang silently (issue #375)`);
518
- }
519
- await listing?.commit();
520
- await releaseIssuance(auth.space, profile, pr, opts, perms, validDates.exp, credentialIdOf(creds));
521
- // §13.1 mint fence for the serve credential: the credential is BUILT, but released only when its
522
- // NORMATIVE ledger row (holderPrincipal/lifecycleUid/sourceChain/state/exp + the currency
523
- // coordinates) is durably staged and its revision-pinned CAS wins the instance's single issuance
524
- // gate (still `open` at the authorized epoch + registrationRevision + nameAuthorityRevision). A
525
- // takeover, re-registration, or name transfer that froze the gate first makes this lose and
526
- // release nothing. A read is never a fence, so this is a CAS write, not an in-memory mark.
527
- if (profile === "endpoint-serve") {
528
- if (!opts.serveIssuance)
529
- 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)");
530
- await finalizeServeIssuance(opts.serveIssuance, opts.endpointServe, {
531
- // PER-ISSUED-JWT id (digest of the credential): `exp` and `iat` have whole-second Unix
532
- // resolution and `jti` is derived from the claims, so what keeps a re-registered successor
533
- // serve credential off its revoked predecessor's row within the same second is the
534
- // epoch-pinned serve grant (`endpointServe.epoch` in the permission rows). A renewal in a
535
- // later second gets a fresh `iat`/`exp` and writes a new ledger row; a same-second renewal
536
- // at one epoch signs identical bytes and re-stages the same active row, which the
537
- // create-only / idempotent-if-identical stage seam accepts as a retry while refusing a
538
- // revoked row with `conflict`. The stable nkey rides separately as `credentialKey` for
539
- // broker revocation. KEY-SAFE digest form (`sha256-<hex>`, never the §13.7 `sha256:`
540
- // artifact form): the id becomes a segment of the durable `epcred.` KV key, whose grammar
541
- // has no ":".
542
- credentialId: credentialIdOf(creds),
543
- credentialKey: identity.id,
544
- holderActor: pr.actor,
545
- // A serve credential is minted directly by the provisioner authority, so its §13.1 issuance
546
- // lineage is the root anchor (not owner/actor principal components).
547
- sourceChain: ["root"],
548
- ...(validDates.exp !== undefined ? { exp: validDates.exp } : {}),
549
- });
550
- }
551
- return creds;
552
- }
553
- /** A static `agent` mint's listing generation (SPEC 13.15, "Listing issuance"), decided before the
554
- * credential is signed. Its horizon is the credential's own expiry, so a mint with none gets no
555
- * listing generation. Bound to no gate: the evidence's expiry is its liveness. */
556
- async function prepareStaticListing(space, profile, pr, opts, exp) {
557
- const seam = opts.listingSeam;
558
- if (!seam)
559
- return undefined;
560
- if (profile !== "agent")
561
- throw new Error(`mintCreds: a listing seam rides the static agent mint only, not "${profile}"`);
562
- if (opts.issued || opts.listing)
563
- throw new Error("mintCreds: a listing seam decides the listing generation itself; opts.issued and opts.listing are refused beside it");
564
- if (exp === undefined)
565
- return undefined;
566
- if (!pr.lifecycleUid)
567
- throw new Error("mintCreds: a listing generation is lifecycle-keyed; mint with opts.lifecycleUid");
568
- 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 } : {}) }));
569
- }
570
- /** The SPEC 13.15 issuance fence: an issuing mint persists the ceiling it is handing out BEFORE
571
- * the material is returned, and the material expires by its generation's horizon. The evidence is the minted permission set itself (deny rules
572
- * included), imported from the same object the JWT was encoded from, so the record and the
573
- * credential cannot disagree. `sources` name the gates the issuance depends on; an issuance bound
574
- * to none (a one-shot instrument) carries the credential's own expiry as its liveness. A renewal
575
- * confirms the existing generation's ceiling is unchanged and records nothing new. */
576
- async function releaseIssuance(space, profile, pr, opts, perms, exp, credentialId) {
577
- if (!opts.issued) {
578
- if (opts.issuance)
579
- throw new Error("mintCreds: opts.issuance without opts.issued; an issuance names its generation");
580
- return;
581
- }
582
- const seam = opts.issuance;
583
- if (!seam)
584
- 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)`);
585
- if (!pr.lifecycleUid)
586
- throw new Error("mintCreds: an issuance is lifecycle-keyed; mint with opts.lifecycleUid");
587
- const ref = { space, owner: pr.owner, actor: pr.actor, uid: pr.lifecycleUid, generation: opts.issued.generation };
588
- // Every credential minted on a generation ends by its horizon: past it the generation authorizes
589
- // nothing and its rows may be gone, so material outliving it would ride a dead binding.
590
- if (exp === undefined || exp > issuedHorizon(ref.generation))
591
- throw new Error(`mintCreds: an issued credential must expire by its generation's horizon ${issuedHorizon(ref.generation)} (SPEC 13.15)`);
592
- const permissions = importNativeSubjectPermissions(perms);
593
- if (seam.mode === "renew") {
594
- await seam.store.confirm(ref, permissions);
595
- await seam.finalize?.(credentialId);
596
- return;
597
- }
598
- // The spawn bound reads an issuance with no source and no presence key of its own as an operator
599
- // instrument (grant-bound.ts, issuedSpawnerStanding), so only an instrument profile is issued that
600
- // way. Any other profile issued without a source must carry its own presence key.
601
- if (seam.sources.length === 0 && !INSTRUMENT_PROFILES.has(profile) && !issuedPermitsPattern(permissions.publish, presenceKeySubject(space, pr.owner, pr.actor)))
602
- 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)`);
603
- const prepared = await seam.store.stage({
604
- version: 1,
605
- ref,
606
- sources: seam.sources,
607
- permissions,
608
- ...(seam.sources.length === 0 ? { expiresAt: exp } : {}),
609
- });
610
- await seam.store.release(prepared, async () => { await seam.finalize?.(credentialId); });
611
- await writeAcceptedRow(seam.accepted, opts.issued.acceptedToken, ref);
612
- }
613
- /** Issue a host-signed NATS user JWT for a caller-generated nkey. The private seed stays with
614
- * the remote manager. This is deliberately narrower than {@link mintCreds}: only the typed remote
615
- * manager protocol may request it, and every profile still goes through the same permission and
616
- * lifetime builders. It signs with the space account's signing key alone, so a host that holds
617
- * only that key passes no placeholder broker trust. */
618
- export async function mintPublicUserJwt(auth, publicId, profile, opts) {
619
- if (!isUserNkey(publicId))
620
- throw new Error("mintPublicUserJwt: publicId must be a user nkey");
621
- 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))
622
- throw new Error(`mintPublicUserJwt: profile "${profile}" is not part of the closed remote manager protocol`);
623
- const pr = {
624
- owner: opts.principal?.owner ?? DEV_OWNER,
625
- actor: opts.principal?.actor ?? publicId,
626
- connId: publicId,
627
- ...(opts.lifecycleUid ? { lifecycleUid: opts.lifecycleUid } : {}),
628
- };
629
- const perms = profile === "endpoint-serve"
630
- ? endpointServePermissions(auth.space, pr, opts)
631
- : permissionsFor(profile, auth.space, pr, opts);
632
- const validDates = userValidDates(profile, opts);
633
- if (validDates.exp === undefined)
634
- throw new Error(`mintPublicUserJwt: profile "${profile}" must be bounded`);
635
- 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 });
636
- // Same composed-credential bound as mintCreds (see MAX_MINTED_JWT_BYTES): this JWT is presented
637
- // on a real CONNECT line by the remote manager, so it is priced against the same budget before
638
- // any fallible finalize step below. None of this function's profiles read allowSubscribe/
639
- // allowPublish today (each returns through its own dedicated permission builder), so the count
640
- // is always 0 here - the check stays live in case a future profile addition changes that.
641
- const jwtBytes = Buffer.byteLength(jwt, "utf8");
642
- if (jwtBytes > MAX_MINTED_JWT_BYTES) {
643
- const channelCount = (opts.allowSubscribe?.length ?? 0) + (opts.allowPublish?.length ?? 0);
644
- throw new Error(`mintPublicUserJwt: minted JWT is ${jwtBytes} bytes, exceeding the ${MAX_MINTED_JWT_BYTES}-byte ` +
645
- `mint bound (${channelCount} allowSubscribe+allowPublish channel(s)) - the composed credential ` +
646
- `would exceed the broker's CONNECT line and the connect would hang silently (issue #375)`);
647
- }
648
- if (profile === "endpoint-serve") {
649
- if (!opts.serveIssuance)
650
- throw new Error("mintPublicUserJwt: endpoint-serve requires serveIssuance");
651
- await finalizeServeIssuance(opts.serveIssuance, opts.endpointServe, {
652
- credentialId: credentialIdOf(jwt),
653
- credentialKey: publicId,
654
- holderActor: pr.actor,
655
- sourceChain: ["root"],
656
- exp: validDates.exp,
657
- });
658
- }
659
- return { jwt, exp: validDates.exp };
660
- }
661
- /** Host-only service-callout mint. The host authenticates the connection and bearer, fixes
662
- * expiry before authority reads, and keeps this JWT inside its encrypted authorization response.
663
- * Native root reauthorization and natkey recording remain the host's final release obligations.
664
- */
665
- export async function mintServiceCalloutJwt(auth, args) {
666
- const connection = parseServiceConnectionBinding(args.connection), inboxNonce = assertInboxConnId(args.inboxNonce);
667
- const principal = { ...args.principal }, { serve, gate, admittedAt, accessExpiresAt, expiresAt } = args;
668
- const now = Math.floor(Date.now() / 1000);
669
- if (![admittedAt, accessExpiresAt, expiresAt].every((v) => Number.isSafeInteger(v) && v > 0)
670
- || admittedAt > now || expiresAt <= now || expiresAt > accessExpiresAt || expiresAt > admittedAt + SERVICE_ACCESS_TTL_SECONDS)
671
- throw new Error("service callout mint requires the original admission-bounded expiry");
672
- const identity = principalKey(principal.owner, principal.actor);
673
- const snapshot = assertServeGrantMintable(serve, { space: auth.space, holderOwner: principal.owner });
674
- if (snapshot.journalClass || snapshot.pools.length || snapshot.commands.some((command) => serve.surface[command].class !== "ephemeral"))
675
- throw new Error("service callout mint supports only standalone ephemeral serving grants");
676
- const permissions = endpointServePermissions(auth.space, { ...principal, connId: inboxNonce }, { endpointServe: serve, serveIssuance: gate });
677
- 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 });
678
- if (Buffer.byteLength(jwt, "utf8") > MAX_MINTED_JWT_BYTES)
679
- throw new Error("service callout mint exceeds the native JWT byte limit");
680
- const credentialId = credentialIdOf(jwt);
681
- await finalizeServeIssuance(gate, serve, { credentialId, credentialKey: connection.userNkey,
682
- serviceConnection: connection, holderActor: principal.actor, sourceChain: ["root"], exp: expiresAt });
683
- if (expiresAt <= Math.floor(Date.now() / 1000))
684
- throw new Error("service callout mint expired before release; its fixed expiry is not extended");
685
- return { jwt, credentialId, iat: decode(jwt).iat, exp: expiresAt };
686
- }
687
- /** The profiles whose credential carries caller rails, and can therefore be minted as an
688
- * issuance (SPEC 13.15). Everything else is infrastructure or a one-shot with no rail to bind. */
689
- const ISSUABLE_PROFILES = new Set(["agent", "control-caller-privileged", "control-caller-admin", "deployer", "manager-caller"]);
690
- /** The operator instruments: the only profiles issued with no source and no presence key of their own. */
691
- const INSTRUMENT_PROFILES = new Set(["control-caller-privileged", "control-caller-admin", "deployer"]);
692
- /** Build the NATS user permission object for a profile: a default-deny allow-list scoped to
693
- * exactly what each profile does. Every profile is now enumerated least-privilege — the former
694
- * allow-all `manager` is gone (its roles split across supervisor/provisioner/operator/purger and the
695
- * CLI-surface profiles). Subject/stream/durable names come from the shared builders so the ACLs
696
- * can't drift from the wire layout.
697
- *
698
- * PRINCIPAL-PARAMETERIZED + MODE-AGNOSTIC (owner+actor grammar): `pr` carries the owner+actor wire
699
- * principal (chat/inst/svc/ctl subjects, per-agent durables, the presence key all scope to it) PLUS the
700
- * connection nkey (`pr.connId`, which scopes the private reply inbox `_INBOX_<connId>`). Core does NOT
701
- * fork on dev-vs-user — the composition root supplies the principal: the auth callout passes the derived
702
- * owner + ledger actor + the per-connection ephemeral nkey; the static/dev mint passes
703
- * `{owner:"local", actor:<id>, connId:<id>}` via {@link principalOf}. EXPORTED so the callout's injected
704
- * `permissionsFor` hook can feed a validated principal straight into the same builder. */
705
- export function permissionsFor(profile, space, pr, opts) {
706
- // Guard the connId BEFORE any profile builds `_INBOX_<connId>.>`: in user mode connId is a client-
707
- // chosen nonce (untrusted), so a metacharacter here would escalate the inbox grant to every inbox.
708
- // Assert once, for all profiles (each early-returning profile builds its own inbox from pr.connId).
709
- assertInboxConnId(pr.connId);
710
- // Extraneous serve-artifact refusal, hoisted ABOVE the profile dispatch: every early-return
711
- // profile (delivery/supervisor/observer/...) must refuse it too, not just the agent tail, or a
712
- // misconfigured sensitive mint is silently masked (MintOpts: every other profile refuses it).
713
- // The "endpoint-serve" profile is excluded so its own arm below keeps the call-mintCreds redirect.
714
- if (opts.endpointServe && profile !== "endpoint-serve")
715
- throw new Error(`permissionsFor: endpointServe rides the dedicated "endpoint-serve" profile - a serve credential is per-instance authority (SPEC 13.9), never folded into a "${profile}" cred`);
716
- // An issuance binds CALLER rails (SPEC 13.15). A profile with no caller rail has nothing to bind
717
- // the generation to, so `issued` on it is a misconfiguration refused here, never dropped.
718
- if (opts.issued && !ISSUABLE_PROFILES.has(profile))
719
- throw new Error(`permissionsFor: opts.issued binds caller rails and "${profile}" holds none; only ${[...ISSUABLE_PROFILES].join(", ")} mint issued authority (SPEC 13.15)`);
720
- if (opts.listing && profile !== "agent" && profile !== "manager-caller")
721
- throw new Error(`permissionsFor: a listing generation rides the agent and manager-caller views only, not "${profile}" (SPEC 13.15)`);
722
- if (opts.listing && opts.issued)
723
- throw new Error("permissionsFor: an issued credential lists under its own generation; a listing generation beside it is refused (SPEC 13.15)");
724
- if (isEnvironmentManagerProfile(profile))
725
- return environmentManagerPermissions(profile, space, pr, opts.environmentManager);
726
- if (opts.environmentManager)
727
- throw new Error(`permissionsFor: environmentManager pins cannot ride ${profile}`);
728
- if (profile === "delivery")
729
- return deliveryPermissions(space, pr); // scoped server-side Plane-3 infra
730
- if (profile === "manager-caller")
731
- return managerCallerPermissions(space, pr, opts);
732
- if (profile === "membership-rw")
733
- return membershipRwPermissions(space, pr); // scoped graph-feed reader/writer
734
- if (profile === "supervisor")
735
- return supervisorPermissions(space, pr); // always-on daemon
736
- if (profile === "provisioner")
737
- return provisionerPermissions(space, pr); // ephemeral onboarding authority
738
- if (profile === "deprovisioner") {
739
- // Ephemeral, TARGET-PINNED teardown — the counterpart to `provisioner`. The target is a
740
- // full principal dot-form for user-mode agents, or a bare static/dev actor id (keyed under
741
- // DEV_OWNER) — see {@link deprovisionTargetPrincipal}.
742
- if (!opts.deprovisionTarget)
743
- throw new Error("permissionsFor: deprovisioner requires opts.deprovisionTarget ({principal, lifecycleUid} of the departed incarnation)");
744
- return deprovisionerPermissions(space, pr, opts.deprovisionTarget);
745
- }
746
- if (profile === "retirement-requester") {
747
- // Ephemeral request+reply on the AUTH ENDPOINT rail:
748
- // publish EXACTLY this caller triple's own request subject for the ONE target it names +
749
- // subscribe its own reply-plane filter and inbox. No store reads, no barrier/scanner/plane
750
- // authority - the requester only asks; the auth plane holds every executing right and
751
- // re-checks the serve registration at serve time.
752
- // Validate the WHOLE shape, not just its presence. Each of these is a subject token: a missing
753
- // one would otherwise surface as a raw "cannot read properties of undefined" from deep inside
754
- // the subject builder, which tells the operator nothing about WHICH field it owes. The `target`
755
- // arrived with #350 (the handle triple moved into the subject), so a caller written against the
756
- // pre-#350 `{owner, actor}` shape lands here — and must be told exactly that.
757
- const rr = opts.retirementRequester;
758
- if (!rr)
759
- throw new Error("permissionsFor: retirement-requester requires opts.retirementRequester ({owner, actor, uid, target} of the requesting manager)");
760
- for (const [k, v] of [["owner", rr.owner], ["actor", rr.actor], ["uid", rr.uid]])
761
- if (typeof v !== "string" || v.length === 0)
762
- throw new Error(`permissionsFor: retirement-requester requires opts.retirementRequester.${k} (the caller triple is <owner>.<actor>.<uid>; since #350 the rail carries the CALLER's uid, not a two-token alias)`);
763
- if (!rr.target || typeof rr.target.owner !== "string" || typeof rr.target.actor !== "string" || typeof rr.target.lifecycleUid !== "string")
764
- throw new Error("permissionsFor: retirement-requester requires opts.retirementRequester.target ({owner, actor, lifecycleUid} of the ONE incarnation this credential may retire) - since #350 the handle target rides the SUBJECT and is grant-pinned, so it can no longer be supplied in the request body");
765
- const { owner, actor, uid, target } = rr;
766
- const caller = { owner, actor, uid };
767
- // The row is minted in `exact` mode: a privileged, non-redemption mode where this profile
768
- // pins the arity-3 target triple directly from the manager's own coordinates under root
769
- // authority, rather than through `handle`'s issuer-signed redemption provenance. The target is
770
- // still confinement-pinned, so this credential can ask to retire the ONE incarnation it was
771
- // minted for and nothing else - the same confinement the pre-#350 grant got from naming an
772
- // exact `ctl` subject, now covering the TARGET as well as the caller. The nonce is the only
773
- // wildcard token (§13.9): a bounded per-request suffix, not an addressing widening.
774
- const rows = epRequestGrantRows(space, {
775
- endpoint: AUTH_ENDPOINT,
776
- command: EP_CMD_RETIRE_LIFECYCLE,
777
- target: { mode: "exact", tOwner: target.owner, tActor: target.actor, tUid: target.lifecycleUid },
778
- }, caller);
779
- return {
780
- pub: {
781
- allow: [
782
- ...rows,
783
- epDescribeAllGrantRow(space, caller),
784
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
785
- ],
786
- },
787
- sub: { allow: [epCallerReplyFilter(space, caller), `_INBOX_${pr.connId}.>`] },
788
- };
789
- }
790
- if (profile === "manager-service")
791
- throw new Error('permissionsFor: "manager-service" is not a generic profile; use the typed remote manager authority protocol');
792
- if (profile === "remote-manager") {
793
- if (!opts.remoteManager)
794
- throw new Error('permissionsFor: "remote-manager" requires opts.remoteManager ({instanceId, owner} of the authorized manager lifecycle)');
795
- return remoteManagerPermissions(space, pr, opts.remoteManager);
796
- }
797
- if (profile === "issuer")
798
- return issuerPermissions(space, pr);
799
- if (profile === "registry-reader")
800
- return registryReaderPermissions(space, pr);
801
- if (profile === "run-admitter") {
802
- if (!opts.runAdmitter)
803
- throw new Error("permissionsFor: run-admitter requires opts.runAdmitter ({endpoint, runId} of the ONE run it admits)");
804
- return runAdmitterPermissions(space, pr, opts.runAdmitter);
805
- }
806
- if (profile === "transfer-writer") {
807
- if (!opts.transferWriter)
808
- throw new Error("permissionsFor: transfer-writer requires opts.transferWriter ({instanceId, hex} of the ONE object it writes)");
809
- const g = transferWriterGrants(space, opts.transferWriter.instanceId, opts.transferWriter.hex, pr.connId);
810
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
811
- }
812
- if (profile === "transfer-reader") {
813
- if (!opts.transferReader)
814
- throw new Error("permissionsFor: transfer-reader requires opts.transferReader ({instanceId} whose own bucket it reads)");
815
- const g = transferReaderGrants(space, opts.transferReader.instanceId, pr.connId);
816
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
817
- }
818
- if (profile === "endpoint-evictor") {
819
- // A SCOPED delivery-admin caller for ONE re-registration's verify-evict.
820
- // Publish EXACTLY this credential's OWN delivery-admin control subject + $JS.API.INFO; subscribe
821
- // its own reply subtree + inbox. NO lease, presence, store read, consumer, KV, or executing
822
- // right — the daemon does the $SYS scan/KICK (subject-gated authority, like the supervisor evictor
823
- // it narrows) and the manager passes only the predecessor's principal. Narrower than the
824
- // `supervisor` profile the auth barrier-evict reuses (its #30 residual, done here for the manager).
825
- const req = controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor);
826
- return { pub: { allow: [req, "$JS.API.INFO"] }, sub: { allow: [`${req}.reply.>`, `_INBOX_${pr.connId}.>`] } };
827
- }
828
- if (profile === "lifecycle-executor") {
829
- if (!opts.lifecycleExecutor)
830
- throw new Error("permissionsFor: lifecycle-executor requires opts.lifecycleExecutor ({owner, actor, lifecycleUid, alias} of the ONE incarnation it may move)");
831
- return lifecycleExecutorPermissions(space, pr, opts.lifecycleExecutor);
832
- }
833
- if (profile === "endpoint-serve-executor") {
834
- if (!opts.endpointServeExecutor)
835
- throw new Error("permissionsFor: endpoint-serve-executor requires opts.endpointServeExecutor ({endpoint, instanceId} of the ONE endpoint instance it may register/serve-mint)");
836
- return endpointServeExecutorPermissions(space, pr, opts.endpointServeExecutor);
837
- }
838
- if (profile === "goal-writer") {
839
- if (!opts.goalWriter)
840
- throw new Error("permissionsFor: goal-writer requires opts.goalWriter ({endpoint} whose action goals this connection binds + commits)");
841
- return goalWriterPermissions(space, pr, opts.goalWriter);
842
- }
843
- if (profile === "purger")
844
- return purgerPermissions(space, pr); // ephemeral history-purge
845
- if (profile === "backup") {
846
- if (!opts.backup)
847
- throw new Error("permissionsFor: backup requires opts.backup");
848
- return backupProfilePermissions(space, pr.connId, opts.backup);
849
- }
850
- if (profile === "restore") {
851
- if (!opts.restore)
852
- throw new Error("permissionsFor: restore requires opts.restore");
853
- return restoreProfilePermissions(space, pr.connId, opts.restore);
854
- }
855
- if (profile === "operator")
856
- return operatorPermissions(space, pr); // human-CLI client (send/dm/ask)
857
- if (profile === "probe")
858
- return probePermissions(pr); // connect-only liveness/auth preflight
859
- if (profile === "channel-writer")
860
- return channelWriterPermissions(space, pr); // channel-registry writes
861
- if (profile === "channel-purger")
862
- return channelPurgerPermissions(space, pr); // channel-writer + CHAT purge
863
- if (profile === "teardown")
864
- return teardownPermissions(space, pr, opts.transferStreams ?? []); // space-wide STREAM.DELETE holder
865
- if (profile === "membership-store-recreate")
866
- return membershipStoreRecreatePermissions(space, pr);
867
- if (profile === "issued-store-recreate")
868
- return issuedStoreRecreatePermissions(space, pr); // the two issued-authority stores only
869
- if (profile === "control-caller-privileged")
870
- return controlCallerPermissions(space, pr, "privileged", opts); // ps/start reads
871
- if (profile === "control-caller-admin")
872
- return controlCallerPermissions(space, pr, "admin", opts); // any-mode stop/attach
873
- if (profile === "deployer")
874
- return deployerPermissions(space, pr, opts.controlTier ?? "admin", opts); // spawn -f deploy authority (user-mode view rides privileged)
875
- if (profile === "session-caller")
876
- return sessionCallerPermissions(space, pr, opts.sessionCaller); // one §13.6 session's caller rails
877
- if (profile === "dm-reader")
878
- return dmReaderPermissions(space, pr); // one own dm_ durable, bind-only
879
- if (profile === "session-serving")
880
- return sessionServingPermissions(space, pr, opts.sessionServing); // one §13.6 session's SERVING rails
881
- if (profile === "session-ledger")
882
- return sessionLedgerPermissions(space, pr); // the dedicated session ledger, no rails
883
- if (profile === "run-driver") {
884
- if (!opts.runDriver)
885
- throw new Error("permissionsFor: run-driver requires opts.runDriver ({endpoint, runId, takeoverId, instanceId, epoch} of the ONE run and attempt it drives)");
886
- const g = runDriverGrants(space, opts.runDriver, pr.connId);
887
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
888
- }
889
- if (profile === "run-mediator") {
890
- if (!opts.runMediator)
891
- throw new Error("permissionsFor: run-mediator requires opts.runMediator for one run and attempt");
892
- const g = runMediatorGrants(space, opts.runMediator, pr.connId);
893
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
894
- }
895
- if (profile === "run-operator") {
896
- if (!opts.runOperator)
897
- throw new Error("permissionsFor: run-operator requires opts.runOperator ({endpoint, takeoverId} of the ONE endpoint whose runs it reads and answers)");
898
- const g = runOperatorGrants(space, opts.runOperator, pr.connId);
899
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
900
- }
901
- if (profile === "endpoint-serve")
902
- // Serve rows are emitted ONLY by mintCreds behind the §13.1 issuance fence — never via this
903
- // exported builder, so a direct signer/callout can't obtain unfenced serve rows (SPEC 13.1/13.9).
904
- throw new Error("permissionsFor: endpoint-serve rows are emitted only by mintCreds behind the §13.1 issuance fence; call mintCreds");
905
- const CHAT = chatStream(space), DM = dmStream(space), TASK = taskStream(space);
906
- const PAYLOAD = eventPayloadStream(space);
907
- const KV = `KV_${presenceBucket(space)}`;
908
- const CHKV = `KV_${channelBucket(space)}`; // channel registry (read-only for everyone)
909
- const MEMKV = `KV_${membershipBucket(space)}`; // derived graph membership feed (read-only — dashboard)
910
- const DLVKV = `KV_${deliveryBucket(space)}`; // delivery lease/readiness (read-only — Component 6 health)
911
- // Validate both principal tokens; the reply inbox keys on the connection nkey (see MintPrincipal).
912
- principalKey(pr.owner, pr.actor);
913
- const inbox = `_INBOX_${pr.connId}.>`;
914
- if (profile === "observer" || profile === "admin") {
915
- // Read-only: live feed via tap, history + presence via ephemeral/ordered consumers it
916
- // creates on CHAT + the presence KV. No chat/inst/svc/ctl publish → can't post.
917
- // observer — sub chat.> only; DM_<space>/svc never named → DMs + anycast structurally
918
- // invisible (step-6 inbox scoping means it can't sniff deliveries either).
919
- // admin — sub widened to the MESSAGING plane, enumerated (SPEC 13.9/13.11): the
920
- // dashboard's tap also sees DMs (inst.>) and anycast (svc.>) live, PLUS DM-stream read
921
- // verbs so it can backfill DM history. A deliberate god-view over messaging only: a
922
- // space-wide `>` would additionally plain-subscribe every v0.4 endpoint request rail
923
- // (collecting the reply nonces the queue-qualified-only rule protects) and every
924
- // core-only session frame, so the ep/epe/epf/epj/ept/epr/epw/eps/epc planes are
925
- // deliberately excluded. DMs are plaintext + ACL-gated, so mint this only for a
926
- // trusted audit dashboard. CONSUMER.CREATE on DM_<space> is the DM-confidentiality
927
- // surface — granted here ONLY for this elevated read-only profile, never to agents.
928
- const sub = [
929
- ...eventPayloadReadSubjects(space, pr.owner, [], profile === "admin"),
930
- ...(profile === "admin"
931
- ? [`${spacePrefix(space)}.chat.>`, `${spacePrefix(space)}.inst.>`, `${spacePrefix(space)}.svc.>`, inbox]
932
- : [`${spacePrefix(space)}.chat.>`, inbox]),
933
- ];
934
- // History readers (channelHistory, multiChannelHistory, dmHistory) are named consumers keyed on
935
- // this connection's reader id (see MintPrincipal.readerId). The profile may delete exactly those
936
- // names and no other consumer (#4123): each read deletes its readers when it ends, so polling no
937
- // longer fills the stream's consumer limit.
938
- const readerId = pr.readerId ?? pr.connId;
939
- const readerDeletes = (stream) => Array.from({ length: HISTORY_READERS }, (_, i) => `$JS.API.CONSUMER.DELETE.${stream}.${historyReaderConsumer(readerId, i)}`);
940
- const allow = [
941
- `$JS.API.STREAM.INFO.${PAYLOAD}`,
942
- ...eventPayloadReadSubjects(space, pr.owner, [], profile === "admin").flatMap(subject => Array.from({ length: HISTORY_READERS }, (_, i) => `$JS.API.CONSUMER.CREATE.${PAYLOAD}.${historyReaderConsumer(readerId, i)}.${subject}`)),
943
- ...Array.from({ length: HISTORY_READERS }, (_, i) => [
944
- `$JS.API.CONSUMER.INFO.${PAYLOAD}.${historyReaderConsumer(readerId, i)}`,
945
- `$JS.API.CONSUMER.MSG.NEXT.${PAYLOAD}.${historyReaderConsumer(readerId, i)}`,
946
- ]).flat(),
947
- ...readerDeletes(PAYLOAD),
948
- "$JS.API.INFO",
949
- `$JS.API.STREAM.INFO.${CHAT}`,
950
- `$JS.API.STREAM.INFO.${KV}`,
951
- // NO stream-wide CONSUMER.DELETE on any stream this profile reads (#691). Its watch consumers
952
- // are client-named ordered consumers (`oc_<nuid>_<serial>`, the serial bumped on every
953
- // rebuild), so the only expressible grant for them is stream-wide, and stream-wide let one
954
- // observer delete another principal's live watch cursors and the delivery daemon's fan-out
955
- // durable. The broker reaps those consumers at their inactive threshold instead, and the
956
- // client treats a refused delete of its own watch consumer as that designed outcome.
957
- //
958
- // history reader consumer: a multi-filter create can't encode its filter in the subject → bare
959
- // form; the .> form covers the single-filter named create.
960
- `$JS.API.CONSUMER.CREATE.${CHAT}`,
961
- `$JS.API.CONSUMER.CREATE.${CHAT}.>`,
962
- `$JS.API.CONSUMER.INFO.${CHAT}.>`,
963
- `$JS.API.CONSUMER.MSG.NEXT.${CHAT}.>`,
964
- ...readerDeletes(CHAT),
965
- `$JS.ACK.${CHAT}.>`,
966
- `$JS.API.CONSUMER.CREATE.${KV}.>`, // kv.watch ordered consumer (roster is public)
967
- `$JS.API.CONSUMER.INFO.${KV}.>`,
968
- // Channel registry read (watch + direct kv.get + enriched listChannels) — config is
969
- // world-readable. STREAM.MSG.GET is the verb kv.get() rides (the bucket has no allow_direct).
970
- `$JS.API.STREAM.INFO.${CHKV}`,
971
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
972
- `$JS.API.CONSUMER.CREATE.${CHKV}.>`,
973
- `$JS.API.CONSUMER.INFO.${CHKV}.>`,
974
- // Derived graph-membership feed (broker-sourced who-is-subscribed) — watch + direct kv.get. The
975
- // silent-reader set is sensitive, so read is admin/observer-only (this elevated profile), never an
976
- // agent. Read-only: no `$KV.${membershipBucket}` publish — only the `membership-rw` cred writes it.
977
- `$JS.API.STREAM.INFO.${MEMKV}`,
978
- `$JS.API.STREAM.MSG.GET.${MEMKV}`,
979
- // The snapshot read (`readMembership`) is paged batched Direct Gets whose request subject is the
980
- // bare stream, binding no consumer (#4123): this profile may not delete a scan's consumer, so a
981
- // consumer per read stayed to the inactive threshold and each refused delete was a broker log
982
- // line. The reply subject is caller-chosen, the same vector the consumer create below already
983
- // grants on this bucket, so the read reaches no byte the watch could not.
984
- `$JS.API.DIRECT.GET.${MEMKV}`,
985
- `$JS.API.CONSUMER.CREATE.${MEMKV}.>`,
986
- `$JS.API.CONSUMER.INFO.${MEMKV}.>`,
987
- // Delivery lease/readiness: READ-ONLY (STREAM.INFO + kv.get), the same pair the `agent` arm
988
- // below already carries for its non-gating `cotal_channels` health surface. A read-only
989
- // DIAGNOSTIC profile needs this axis for the same reason an agent does, and more: without it
990
- // an operator-facing surface can only report the daemon's PROCESS, which is green while the
991
- // responder is unbound (#1576). No `$KV.${deliveryBucket(space)}` publish — the lease has
992
- // exactly one writer, the `delivery` cred, and that is unchanged here.
993
- `$JS.API.STREAM.INFO.${DLVKV}`,
994
- `$JS.API.STREAM.MSG.GET.${DLVKV}`,
995
- "$JS.FC.>", // ordered-consumer flow control
996
- ];
997
- if (profile === "admin") {
998
- // DM history backfill (dmHistory): same bare-form gotcha as CHAT — filter_subjects is
999
- // plural so the create lands on the bare subject; the .> form covers named consumers.
1000
- allow.push(`$JS.API.STREAM.INFO.${DM}`, `$JS.API.CONSUMER.CREATE.${DM}`, `$JS.API.CONSUMER.CREATE.${DM}.>`, `$JS.API.CONSUMER.INFO.${DM}.>`, `$JS.API.CONSUMER.MSG.NEXT.${DM}.>`, ...readerDeletes(DM), `$JS.ACK.${DM}.>`);
1001
- }
1002
- return { sub: { allow: sub }, pub: { allow } };
1003
- }
1004
- // ---- agent ----
1005
- // No silent fallthrough: every non-agent profile is handled above, so anything else reaching here is a
1006
- // stale/unwired profile string (e.g. a JS caller bypassing the closed `Profile` union). Fail loud rather
1007
- // than mint it agent perms by accident (the no-fallbacks rule; matches the deleted `manager`'s intent).
1008
- if (profile !== "agent")
1009
- throw new Error(`permissionsFor: unhandled profile "${profile}" - add an explicit arm, do not fall through to agent`);
1010
- const allowPublish = opts.allowPublish ?? []; // post ACL — DEFAULT-DENY (publish must be declared)
1011
- // Read ACL — DEFAULT-DENY for channels, exactly like allowPublish above. Omitted or empty mints
1012
- // NO channel row: no per-channel history-consumer create grant and no `chat.*.<ch>` sub.allow.
1013
- // The DM/presence/anycast/control rows below are unconditional, so a channel-less agent is still
1014
- // a full mesh participant, reachable by DM and visible on the roster.
1015
- const allowSubscribe = opts.allowSubscribe ?? [];
1016
- // Re-assert at the mint chokepoint (covers mint/spawn paths that bypass the file loader): a policy
1017
- // channel must equal its wire token, or the minted grant would alias the logical ACL.
1018
- for (const ch of [...allowSubscribe, ...allowPublish])
1019
- assertValidChannel(ch);
1020
- if (!pr.lifecycleUid)
1021
- throw new Error("permissionsFor(agent): a lifecycleUid is required - the agent's dm/dlv/chathist grants are lifecycle-keyed exact names (SPEC 13.1)");
1022
- const uid = assertLifecycleToken(pr.lifecycleUid);
1023
- const chatHistD = chatHistDurable(pr.owner, pr.actor, uid), dmD = dmDurable(pr.owner, pr.actor, uid);
1024
- const DLV = dlvStream(space), dlvD = dlvDurable(pr.owner, pr.actor, uid); // Plane-3 per-member delivery (bind-only when channel-readable)
1025
- const roles = taskRoles(opts.role, opts.capabilities);
1026
- const pubAllow = [
1027
- // peer publish — owner+actor identity + channel scope, built from the real builders. Default-deny:
1028
- // ONLY the declared allowPublish channels (none by default) get a chat-publish grant.
1029
- ...allowPublish.map((ch) => chatSubject(space, pr.owner, pr.actor, ch)),
1030
- unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a> — DM any instance, as me
1031
- anycastSubject(space, "*", pr.owner, pr.actor), // svc.*.<o>.<a> — anycast any role, as me
1032
- // Self stop/despawn rides the v0.4 ep baseline (`stop` self-mode) — the manager `ctl` rail is
1033
- // deleted. The delivery-daemon rail below is a separate service (Plane-3), kept.
1034
- // ctl.delivery.<o>.<a> — request a durable backstop join/leave/list from the SERVER-SIDE delivery
1035
- // daemon (NOT the manager). The reply rides this same subtree (`ctl.delivery.<o>.<a>.reply.<n>`, in
1036
- // sub.allow below) so the daemon can answer without broad inbox-publish — see CONTROL_DELIVERY.
1037
- controlServiceSubject(space, CONTROL_DELIVERY, pr.owner, pr.actor),
1038
- // THE PEER-READABLE LIVENESS PROBE (#1577) — one publish row per plane, each pinned to THIS
1039
- // agent's own principal slots, so a peer asks as itself and can never forge a probe from
1040
- // another. This is the row that makes liveness askable by a NON-OWNER: without it, the only
1041
- // hypothesis a peer could form for any failure was "my credentials are wrong", because the
1042
- // subjects that answer "is the manager alive" were owner-only.
1043
- //
1044
- // WHAT THIS DOES NOT GRANT, which is the half that keeps it from being a back door. It is
1045
- // PUBLISH ON A REQUEST SUBJECT, not a read of anything. The agent gains NO grant on the manager
1046
- // bucket (still absent by deliberate omission, below) and NO new read of the delivery bucket.
1047
- // The answer it can obtain is one enum per plane, because the responder reduces the lease row
1048
- // before replying and the row never crosses the wire. It cannot subscribe the SERVE filter
1049
- // either: `live.<plane>.*.*` is not in `sub.allow`, so an agent cannot impersonate a responder
1050
- // and answer a peer's probe with a comforting lie.
1051
- ...LIVENESS_PLANES.map((plane) => livenessSubject(space, plane, pr.owner, pr.actor)),
1052
- // JetStream control plane — scoped to this agent's own streams/durables.
1053
- "$JS.API.INFO",
1054
- // STREAM.INFO: CHAT (join watermark, recall drop-marker, channel-list counts — a documented
1055
- // metadata surface, see SPEC §9) + the world-readable presence/registry KVs. NOT DM/DLV/EPC:
1056
- // an agent reaches each of those by name — its own pre-created dm_<id>/dlv_<id> durable, or a
1057
- // subject-scoped DIRECT.GET on EPC — so it never needs a stream-level read, and `subjects_filter`
1058
- // is a REQUEST-BODY field no ACL can narrow, so INFO there would enumerate DM and delivery
1059
- // subject metadata across peers (who DMed whom) for no functional gain. TASK's INFO row is
1060
- // role-gated with the rest of its TASK grants, below.
1061
- `$JS.API.STREAM.INFO.${CHAT}`, `$JS.API.STREAM.INFO.${KV}`, `$JS.API.STREAM.INFO.${CHKV}`,
1062
- // Live channel delivery is the agent's own native core subscription (sub.allow over chat.*.<ch>,
1063
- // below) — there is NO per-instance chat live-tail durable to bind. The durable backstop is
1064
- // Plane-3 (the bind-only dlv_<id> durable below). So no CHAT consumer bind/ack grants here.
1065
- // CHAT history reads (join-backfill, focus-recall, drop-marker) — single-filter EPHEMERAL
1066
- // consumers named chathist_<id>. The create rides the extended subject
1067
- // CONSUMER.CREATE.<CHAT>.<chathist_id>.<filter>, whose trailing filter token nats-server pins to
1068
- // the request body (JSConsumerCreateFilterSubjectMismatchErr, code 10131) — so one create grant
1069
- // per allowSubscribe channel makes history reads broker-bounded to the read ACL. Replaces the
1070
- // old unfiltered DIRECT.GET.<CHAT> (which could fetch ANY message regardless of channel). The
1071
- // name is the agent's own, so info/fetch/delete can't reach a peer's consumer. NO broad
1072
- // CONSUMER.CREATE.<CHAT> / .> deny here: NATS deny beats allow, which would also kill these.
1073
- ...allowSubscribe.map((ch) => `$JS.API.CONSUMER.CREATE.${CHAT}.${chatHistD}.${chatSubject(space, "*", "*", ch)}`),
1074
- `$JS.API.CONSUMER.INFO.${CHAT}.${chatHistD}`,
1075
- `$JS.API.CONSUMER.MSG.NEXT.${CHAT}.${chatHistD}`,
1076
- `$JS.API.CONSUMER.DELETE.${CHAT}.${chatHistD}`,
1077
- // DM consumer: BIND ONLY — info/fetch/ack its own pre-created durable, never create.
1078
- `$JS.API.CONSUMER.INFO.${DM}.${dmD}`,
1079
- `$JS.API.CONSUMER.MSG.NEXT.${DM}.${dmD}`,
1080
- `$JS.ACK.${DM}.${dmD}.>`,
1081
- // Plane-3 DELIVER consumer (SPEC §8): when this credential can read at least one channel, BIND
1082
- // ONLY its own pre-created dlv_<id> — info/fetch/ack, never create. A channel-less credential has
1083
- // no DLV durable and no fetch or ack row. It can still ask CONSUMER.INFO for its own durable
1084
- // name. A client older than 0.163.0 does that during start, and a permitted read answers that
1085
- // the consumer is absent, which that client treats as nothing to bind. A refused publish fails
1086
- // the start. It gets NO grant on the INBOX (mixed pre-auth) stream either.
1087
- ...(allowSubscribe.length > 0 ? [
1088
- `$JS.API.CONSUMER.INFO.${DLV}.${dlvD}`,
1089
- `$JS.API.CONSUMER.MSG.NEXT.${DLV}.${dlvD}`,
1090
- `$JS.ACK.${DLV}.${dlvD}.>`,
1091
- ] : [`$JS.API.CONSUMER.INFO.${DLV}.${dlvD}`]),
1092
- // Presence: on-demand read + watch (read, public roster) + flow control + PUT OWN KEY ONLY.
1093
- // The read is a batched Direct Get of the bucket (SPEC §6): a seat reads the roster when it acts
1094
- // instead of receiving every member's heartbeat. Its reply subject is caller-chosen, the same
1095
- // vector the consumer create below already grants on the same world-readable bucket, so it
1096
- // reaches no byte the watch could not. The watch rows stay for seats built before the read.
1097
- `$JS.API.DIRECT.GET.${KV}`,
1098
- `$JS.API.CONSUMER.CREATE.${KV}.>`,
1099
- `$JS.API.CONSUMER.INFO.${KV}.>`,
1100
- // No CONSUMER.DELETE here or on the registry below: the watch's `oc_<nuid>_<serial>` name
1101
- // cannot be pinned, and a stream-wide delete reaches every peer's watch cursor (#691). A
1102
- // rebuild's predecessor delete is not published under these claims (#4123), and the consumer
1103
- // stays until the broker's inactive threshold.
1104
- "$JS.FC.>",
1105
- presenceKeySubject(space, pr.owner, pr.actor), // own presence key (owner+actor) only — can't spoof peers
1106
- // Channel registry: read-only (watch + direct kv.get for the join-time replay decision).
1107
- // No `$KV.${channelBucket(space)}.*` publish — privileged-write, default-deny gives that free.
1108
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
1109
- // A seat reads the registry on demand, and the one-shot CLI reads it once, each with a batched
1110
- // Direct Get whose request subject is the bare stream (SPEC §7, #4091). On a user-auth mesh the
1111
- // CLI connects on the user's bearer, which the auth service mints with these rows, so the row is
1112
- // what lets it leave no watch consumer behind. The same reply-subject reasoning as the presence
1113
- // read above: the consumer create below already grants that vector on this world-readable bucket.
1114
- `$JS.API.DIRECT.GET.${CHKV}`,
1115
- `$JS.API.CONSUMER.CREATE.${CHKV}.>`,
1116
- `$JS.API.CONSUMER.INFO.${CHKV}.>`,
1117
- // Delivery lease/readiness: READ-ONLY (kv.get) for the non-gating `cotal_channels` delivery-health
1118
- // surface (Component 6). The lease key is daemon-availability info, like the world-readable roster;
1119
- // NO write grant — only the `delivery` cred writes it.
1120
- `$JS.API.STREAM.INFO.${DLVKV}`,
1121
- `$JS.API.STREAM.MSG.GET.${DLVKV}`,
1122
- // Manager lease bucket (`cotal_manager_<space>`): NO grant at all. An agent must never read,
1123
- // write, or delete it. The bucket holds one `lease.<instanceId>` key per manager instance and
1124
- // the per-space `renewal` key. The `supervisor` credential writes `lease.*` and `renewal`; a
1125
- // `remote-manager` credential writes only its own `lease.<instanceId>`. An agent that could
1126
- // mutate a lease key could DoS that holder (evict it, or pre-create the key to block a fresh
1127
- // one). Safety is by OMISSION (default-deny on the un-granted `KV_cotal_manager_*` stream and
1128
- // `$KV.cotal_manager_*.>`), so do NOT add a broad `KV_*` or `$KV.<space>.>` grant that would
1129
- // silently re-open it.
1130
- ];
1131
- if (roles.length > 0) {
1132
- // TASK consumer: BIND ONLY the pre-created durable (svc_<role>) of its own role and of each
1133
- // `role:<r>` token it holds. Like DM, the create-time filter_subject isn't reliably
1134
- // ACL-constrainable, so no create path is allowed — the privileged provisioner pre-creates
1135
- // svc_<role> filtered to svc.<role>.>. STREAM.INFO rides the SAME role gate as the bind rows: a
1136
- // role-less agent holds no TASK grant at all, so it can neither read the task stream's state
1137
- // nor enumerate its subjects.
1138
- pubAllow.push(`$JS.API.STREAM.INFO.${TASK}`);
1139
- for (const role of roles) {
1140
- const svcD = taskDurable(role);
1141
- pubAllow.push(`$JS.API.CONSUMER.INFO.${TASK}.${svcD}`, `$JS.API.CONSUMER.MSG.NEXT.${TASK}.${svcD}`, `$JS.ACK.${TASK}.${svcD}.>`,
1142
- // The take of one delivered request (SPEC §8.1), pinned to this role and this principal, so a
1143
- // credential takes only for a role whose queue it binds. Its reply rides the sub row below.
1144
- takeSubject(space, role, pr.owner, pr.actor));
1145
- }
1146
- }
1147
- // Spawn / admin capability control reach rides the v0.4 ep rows below (the manager `ctl` rail is
1148
- // deleted) — the spawn set (owner-mode manager lifecycle) and the admin instrument set
1149
- // (any-mode + manager.admin family) are added to the ep caller rows, not a ctl subject.
1150
- // v0.4 endpoint rails (SPEC §13.9 caller rows). EVERY agent gets the Appendix-B BASELINE set
1151
- // (wildcard describe + delivery join/leave/list + self-mode lifecycle + the reply rail), keyed
1152
- // on the SAME lifecycle uid as the agent's durables; the spawn capability adds the owner-mode
1153
- // manager lifecycle set. Beyond the baseline stays default-deny: only minted capabilities
1154
- // produce rows, each pinning the full caller triple (§13.1 lifecycle UID included; the nonce
1155
- // is the only wildcard token).
1156
- // ONE lifecycle uid keys the whole caller rail (§13.1/§13.2 forge-lock: one credential names one
1157
- // incarnation). `uid` is the already-asserted pr.lifecycleUid; the baseline, the spawn set, AND
1158
- // the explicit capabilities ALL build their caller triple from it. opts.lifecycleUid is a public
1159
- // seam (the IdP-adapter path) that must AGREE, never a second source of truth for the triple: a
1160
- // divergent value would mint two reply rails on one credential, so it fails loud here.
1161
- const epCaller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid }, opts);
1162
- const baseline = epBaselineGrantRows(space, epCaller);
1163
- pubAllow.push(...baseline.pub);
1164
- if (opts.issued)
1165
- pubAllow.push(acceptedReadGrant(space, opts.issued.acceptedToken));
1166
- const epSub = [...baseline.sub];
1167
- // The registry's listing question rides the issued rail (SPEC 13.20): under the credential's own
1168
- // generation when its issuance carries it, else under a listing generation.
1169
- if (opts.issued?.listing)
1170
- pubAllow.push(...epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, epCaller));
1171
- if (opts.listing) {
1172
- const rows = listingGrantRows(space, epCaller, opts.listing);
1173
- pubAllow.push(...rows.pub);
1174
- epSub.push(...rows.sub);
1175
- }
1176
- // BOTH HALVES OF THE ROLLUP, NOT JUST `pub`. `epCallerGrantRows` returns `{pub, sub}` and its
1177
- // `sub` is the per-goal progress row its own docblock promises: "a goal-bearing capability
1178
- // (spawn/launch) adds ONE per-endpoint epGoalProgressGrantRow - the caller may follow its OWN
1179
- // goal to terminal". Taking `.pub` alone minted a credential that may SUBMIT a goal and may not
1180
- // HEAR it, so the broker refused the follow and the caller reported a timeout about a goal whose
1181
- // terminal had already been committed (#610). `spawn` is goal-bearing, so this `sub` is never
1182
- // empty here - the row was computed correctly and discarded one property access short of the
1183
- // credential.
1184
- if (opts.capabilities?.includes("spawn")) {
1185
- const rows = epCallerGrantRows(space, spawnCallerCapabilities(pr.owner), epCaller);
1186
- pubAllow.push(...rows.pub);
1187
- for (const s of rows.sub)
1188
- if (!epSub.includes(s))
1189
- epSub.push(s);
1190
- }
1191
- // The `run` capability (SPEC 14.3): the manager-hosted workflow-run rows PLUS the spawn set a
1192
- // program's own spawns need. Rows already minted by `spawn` above are exact duplicates and the
1193
- // dedupe below folds them; the `sub` half carries the same goal-follow row for the same reason
1194
- // the spawn branch keeps it.
1195
- if (opts.capabilities?.includes("run")) {
1196
- const rows = epCallerGrantRows(space, runCallerCapabilities(pr.owner), epCaller);
1197
- for (const p of rows.pub)
1198
- if (!pubAllow.includes(p))
1199
- pubAllow.push(p);
1200
- for (const s of rows.sub)
1201
- if (!epSub.includes(s))
1202
- epSub.push(s);
1203
- }
1204
- if (opts.capabilities?.includes("admin"))
1205
- // The admin capability grants the admin instrument set on the ep rails, the set a
1206
- // `control-caller-admin` holds — the any-mode rows + the `manager.admin` family + the reads. In
1207
- // user mode this is the ledger `admin` scope arriving via the callout, the broker-enforced
1208
- // half of the tier; the manager's ledger-derived per-op admin flag stays on top of it.
1209
- {
1210
- // Same `{pub, sub}` contract as the spawn branch above: an admin instrument's set carries the
1211
- // goal-bearing lifecycle commands, so it earns the same follow row.
1212
- const rows = epCallerGrantRows(space, operatorInstrumentCapabilities("admin", pr.owner), epCaller);
1213
- pubAllow.push(...rows.pub);
1214
- for (const s of rows.sub)
1215
- if (!epSub.includes(s))
1216
- epSub.push(s);
1217
- }
1218
- if (opts.endpointCapabilities?.length) {
1219
- if (opts.lifecycleUid !== undefined && assertLifecycleToken(opts.lifecycleUid) !== uid)
1220
- throw new Error(`permissionsFor: opts.lifecycleUid "${opts.lifecycleUid}" disagrees with the principal's lifecycleUid "${uid}" - one credential names ONE incarnation on the caller rail (SPEC 13.1/13.2)`);
1221
- const rows = epCallerGrantRows(space, opts.endpointCapabilities, epCaller);
1222
- pubAllow.push(...rows.pub);
1223
- for (const s of rows.sub)
1224
- if (!epSub.includes(s))
1225
- epSub.push(s);
1226
- }
1227
- // Explicit create-deny (defense-in-depth over default-deny) on the two streams whose
1228
- // create-time filter_subject is the attack surface — DM (private content) and TASK
1229
- // (cross-role work-stealing). Covers the bare ephemeral form (no trailing token), the
1230
- // named/new-API form, and the old durable form. No create path on either stream.
1231
- const pubDeny = [
1232
- `$JS.API.CONSUMER.CREATE.${DM}`,
1233
- `$JS.API.CONSUMER.CREATE.${DM}.>`,
1234
- `$JS.API.CONSUMER.DURABLE.CREATE.${DM}.>`,
1235
- `$JS.API.CONSUMER.CREATE.${TASK}`,
1236
- `$JS.API.CONSUMER.CREATE.${TASK}.>`,
1237
- `$JS.API.CONSUMER.DURABLE.CREATE.${TASK}.>`,
1238
- // Plane-3 DELIVER: bind-only, like DM — the create-time filter_subject is the attack surface, so
1239
- // no create path (the provisioner pre-creates dlv_<id> filtered to dlv.<id>).
1240
- `$JS.API.CONSUMER.CREATE.${DLV}`,
1241
- `$JS.API.CONSUMER.CREATE.${DLV}.>`,
1242
- `$JS.API.CONSUMER.DURABLE.CREATE.${DLV}.>`,
1243
- ];
1244
- // CHAT live read boundary (SPEC v0.3 §9 / Appendix B): mint the read ACL as a native `sub.allow`
1245
- // over cotal.<space>.chat.*.<channel> — one per allowSubscribe channel, wildcards passed through
1246
- // (e.g. chat.*.review.>, chat.*.>). This is what lets an agent self-serve a live channel subscribe
1247
- // with NO manager: join = nc.subscribe, broker-enforced per-subscribe, no consumer name to confine,
1248
- // so an open ACL needs no enumeration. This sub.allow grant IS the live read path — there is no
1249
- // per-instance chat durable; the durable backstop is Plane-3 (delivery-daemon fan-out → per-member DELIVER).
1250
- const subChat = allowSubscribe.map((ch) => chatSubject(space, "*", "*", ch));
1251
- const payloadReads = eventPayloadReadSubjects(space, pr.owner, allowSubscribe);
1252
- if (opts.eventPayloads !== false)
1253
- pubAllow.push(eventPayloadSubject(space, pr.owner, pr.actor));
1254
- pubAllow.push(`$JS.API.STREAM.INFO.${PAYLOAD}`, ...payloadReads.map(subject => `$JS.API.CONSUMER.CREATE.${PAYLOAD}.${chatHistD}.${subject}`), `$JS.API.CONSUMER.INFO.${PAYLOAD}.${chatHistD}`, `$JS.API.CONSUMER.MSG.NEXT.${PAYLOAD}.${chatHistD}`, `$JS.API.CONSUMER.DELETE.${PAYLOAD}.${chatHistD}`);
1255
- // Replies to this agent's durable join/leave/list requests ride `ctl.delivery.<o>.<a>.>` (NOT the
1256
- // per-id _INBOX), so the scoped delivery daemon can answer without broad inbox-publish.
1257
- const deliveryReplies = `${controlServiceSubject(space, CONTROL_DELIVERY, pr.owner, pr.actor)}.>`;
1258
- // Liveness answers (#1577) ride the probe's OWN request subtree, exactly like the delivery
1259
- // control replies above and for the same reason: the responder answers without needing broad
1260
- // inbox-publish. One row per plane, pinned to this agent's principal, so it can hear answers to
1261
- // ITS OWN probes and nothing else — it cannot subscribe a peer's reply lane and harvest answers
1262
- // addressed elsewhere.
1263
- const livenessReplies = LIVENESS_PLANES.map((plane) => `${livenessSubject(space, plane, pr.owner, pr.actor)}.>`);
1264
- // Manager control replies ride the v0.4 ep reply rail (in `epSub`, keyed on the caller triple) —
1265
- // the `ctl.<tier>.<id>.reply.>` subtrees are gone with the ctl rail.
1266
- // A take's reply rides the take's own request subtree, like the delivery control replies.
1267
- const takeReplies = roles.map((role) => `${takeSubject(space, role, pr.owner, pr.actor)}.>`);
1268
- return { pub: { allow: pubAllow, deny: pubDeny }, sub: { allow: [inbox, deliveryReplies, ...takeReplies, ...livenessReplies, ...subChat, ...payloadReads, ...epSub] } };
1269
- }
1270
- /** The reads a spawn-scoped manager-caller view carries on its one pinned instance. A launch uses
1271
- * `status` (execution mode and connectors), `models` (their catalogs), `resolve-cwd` (canonical
1272
- * directory) and `list-dir` (directory navigation). The remaining read, `ps`,
1273
- * lists the caller's own agents: the Manager bounds it to the caller's owner unless the caller
1274
- * holds admin. The standing spawn set carries none of them, because it reaches every manager in
1275
- * the space through the class rail. */
1276
- const SPAWN_VIEW_READS = Object.freeze(["status", "models", "resolve-cwd", "list-dir", "ps"]);
1277
- /** One seat's manager control view. It carries no agent messaging or delivery surface, and every
1278
- * manager request, including describe, is pinned to one exact registered instance. */
1279
- function managerCallerPermissions(space, pr, opts) {
1280
- if (!pr.lifecycleUid)
1281
- throw new Error("permissionsFor(manager-caller): a lifecycleUid is required");
1282
- const instanceId = opts.managerInstanceId === undefined
1283
- ? (() => { throw new Error("permissionsFor(manager-caller): managerInstanceId is required"); })()
1284
- : assertLifecycleToken(opts.managerInstanceId, "managerInstanceId");
1285
- const caps = opts.capabilities ?? [];
1286
- const ordinary = [
1287
- { endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: "describe" },
1288
- ...baselineCallerCapabilities().filter((cap) => cap.endpoint === BASELINE_LIFECYCLE_ENDPOINT),
1289
- ...(caps.includes("spawn") ? spawnCallerCapabilities(pr.owner) : []),
1290
- ...(caps.includes("spawn") ? SPAWN_VIEW_READS.map((command) => ({ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command })) : []),
1291
- ...(caps.includes(MANAGER_VITALS_SCOPE) ? [{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: MANAGER_VITALS_COMMAND }] : []),
1292
- ...(caps.includes("run") ? runCallerCapabilities(pr.owner) : []),
1293
- ...(caps.includes("admin") ? operatorInstrumentCapabilities("admin", pr.owner) : []),
1294
- ];
1295
- const caller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid: assertLifecycleToken(pr.lifecycleUid) }, opts);
1296
- const rows = epCallerGrantRows(space, instanceOnlyManagerCapabilities(ordinary, instanceId), caller);
1297
- const listing = opts.listing ? listingGrantRows(space, caller, opts.listing) : { pub: [], sub: [] };
1298
- return {
1299
- pub: {
1300
- allow: [
1301
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
1302
- ...(opts.issued ? [acceptedReadGrant(space, opts.issued.acceptedToken)] : []),
1303
- ...rows.pub,
1304
- ...(opts.issued?.listing ? epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, caller) : []),
1305
- ...listing.pub,
1306
- ],
1307
- },
1308
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...rows.sub, ...listing.sub] },
1309
- };
1310
- }
1311
- /** The long-lived SUPERVISOR permission set — the always-on manager daemon
1312
- * (`manager.ts` `this.ep`), carved down from the former allow-all `manager`. Its breadth is
1313
- * STANDING, so tightening it removes the always-on DM/DLV body-read AND the stream-admin tamper
1314
- * from the one connection that never goes away. It holds the manager bucket's `lease.*` instance keys
1315
- * and the per-space renewal lease key, its own presence key + the roster watch, the ONE delivery-admin
1316
- * call (request + bounded reply subtree), the manager-plane liveness serve + reply rows, and a
1317
- * read-only point read of the delivery lease row — and nothing else. It serves no manager control:
1318
- * that is the v0.4 `service` endpoint, served on a SEPARATE connection under its own
1319
- * `endpoint-serve` credential. Provisioning (DM/DLV/TASK consumer-create + ACL
1320
- * writes) moves to the EPHEMERAL `provisioner` (opened per-spawn); destructive history-purge moves to the
1321
- * EPHEMERAL `purger`. So the supervisor holds NO chat/inst/svc publish (it never posts — only
1322
- * `setActivity`, a presence write), NO DM/DLV read of any kind (no consumer-create, no native sub), NO
1323
- * stream CREATE/DELETE/PURGE/UPDATE, NO channel-registry access (the daemon sets `watchChannels:false`).
1324
- * `$JS` is an ENUMERATED allow-list — exactly the presence-watch + lease-KV verbs — never `$JS.>`. A
1325
- * leaked supervisor cred can hold the lease and read the public roster; it cannot read a DM, forge an
1326
- * actor, provision, purge, or tamper with a stream. */
1327
- function supervisorPermissions(space, pr) {
1328
- const PKV = `KV_${presenceBucket(space)}`, MKV = `KV_${managerBucket(space)}`;
1329
- const SUP_DLVKV = `KV_${deliveryBucket(space)}`;
1330
- return {
1331
- pub: {
1332
- allow: [
1333
- "$JS.API.INFO",
1334
- // Transcript startup checks read retained subject counts, never message bodies.
1335
- `$JS.API.STREAM.INFO.${chatStream(space)}`,
1336
- // Per-instance manager liveness lease (managerBucket, pre-created at `cotal up`): OPEN-ONLY bind +
1337
- // CAS this instance's own `lease.<instanceId>` key (acquire/renew/release) + read the subtree. The
1338
- // lease is per instance, so the write grant spans `lease.*` (every instance of this space
1339
- // shares this one supervisor principal — the isolation between instances is the logical-id/CAS
1340
- // boundary, not a cred boundary). NO STREAM.CREATE (pre-created), DELETE, or PURGE.
1341
- `$JS.API.STREAM.INFO.${MKV}`,
1342
- `$JS.API.STREAM.MSG.GET.${MKV}`, // readManagerLease (last_by_subj lease.*) + CAS-conflict kv.get
1343
- `$KV.${managerBucket(space)}.${MANAGER_LEASE_KEY}.*`, // this instance's lease.<id> key (create/update/delete = $KV publishes)
1344
- // #1634: the per-space daemon-credential renewal lease, the CAS that picks ONE renewal owner
1345
- // when several managers share the daemon's store. Same bucket, its own key outside `lease.*`.
1346
- `$KV.${managerBucket(space)}.${MANAGER_RENEWAL_LEASE_KEY}`,
1347
- // Presence: publish OWN key + watch the roster. Own key only (no peer-key forge); no
1348
- // presence-stream purge/delete (no force-offline tamper). No presence kv.get (roster is the in-memory
1349
- // watch cache + sweep), so no STREAM.MSG.GET on presence.
1350
- `$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`,
1351
- `$JS.API.STREAM.INFO.${PKV}`,
1352
- `$JS.API.CONSUMER.CREATE.${PKV}.>`, // kv.watch ordered consumer (roster)
1353
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
1354
- "$JS.FC.>", // ordered-consumer flow control
1355
- // The ONE control service the supervisor CALLS: the delivery daemon's privileged
1356
- // admin rail — the manager is the daemon's renewal owner, and after re-signing the daemon creds
1357
- // files it requests `reloadCreds` here so adoption is an explicit, auditable event. Self-scoped
1358
- // request subject (its own owner+actor slots), bounded reply subtree in sub.allow below.
1359
- controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor),
1360
- // LIVENESS REPLIES for the MANAGER plane (#1577), bounded to the `.reply.` leaf under a
1361
- // caller's own request subject. The supervisor is the natural responder for this plane: it
1362
- // is the process that HOLDS the manager lease, so it is the one that can answer the
1363
- // question honestly without anyone else being granted a read of the lease row.
1364
- //
1365
- // REPLIES ONLY, exactly like the delivery daemon's `ctl.delivery.*.*.reply.>`. The row stops
1366
- // at the leaf, so the supervisor cannot publish to the liveness REQUEST subjects themselves
1367
- // and therefore cannot forge a probe from a peer.
1368
- livenessReplyGrant(space, "manager"),
1369
- // #1694: a POINT READ of the delivery lease row, so the store-identity challenge can verify
1370
- // that the process which answered the queue-grouped admin rail is the holder that actually
1371
- // reloads the standing credentials. Without it the challenge can only report what some
1372
- // responder sent, and a non-holder's store stands in for the reloading process's.
1373
- //
1374
- // READ ONLY, and that is the half that matters: a credential able to WRITE this row could
1375
- // manufacture the very fact the challenge reads, which would put the determination back in
1376
- // the hands of a participant. No `$KV.${deliveryBucket(space)}` publish, no watch consumer,
1377
- // no STREAM.DELETE or PURGE.
1378
- `$JS.API.STREAM.INFO.${SUP_DLVKV}`,
1379
- `$JS.API.STREAM.MSG.GET.${SUP_DLVKV}`,
1380
- `$JS.API.DIRECT.GET.${SUP_DLVKV}.>`,
1381
- ],
1382
- },
1383
- sub: {
1384
- // Own reply inbox + the delivery-admin reply subtree for its OWN requests. NO chat/inst/dlv
1385
- // native sub (the supervisor reads no feed), NO manager control-tier serve (that is
1386
- // the endpoint-serve credential's), NO broad `$JS.>`/`$KV.>`.
1387
- //
1388
- // PLUS the manager-plane liveness SERVE filter (#1577): `live.manager.*.*`, queue-grouped, so
1389
- // any credentialed peer's presence probe reaches the lease holder. This is a serve
1390
- // subscription on a presence-only rail, not a widening of what the supervisor may read: the
1391
- // request body is empty and the subject carries only the caller's own principal.
1392
- allow: [
1393
- `_INBOX_${pr.connId}.>`,
1394
- `${controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor)}.>`,
1395
- livenessServeFilter(space, "manager"),
1396
- ],
1397
- },
1398
- };
1399
- }
1400
- /** The long-lived REMOTE MANAGER base credential. This is intentionally smaller than the local
1401
- * supervisor+provisioner union: it registers only its own manager presence, holds only its own
1402
- * manager-instance lease key, and may provision only lifecycle-keyed resources under its derived
1403
- * owner. Endpoint registration, contract publication and serving use separate instance-pinned
1404
- * credentials returned by the same typed host protocol. Per-agent provisioning deliberately does
1405
- * NOT ride this credential: NATS consumer names are single tokens, so a broker grant cannot safely
1406
- * express a prefix wildcard inside `dm_<owner>-<actor>-<uid>`. That operation stays on the host's
1407
- * authenticated provisioning protocol, where the requested descendant is fresh-validated before
1408
- * an exact one-shot grant is used. */
1409
- function remoteManagerPermissions(space, pr, pin) {
1410
- if (pin.owner !== pr.owner)
1411
- throw new Error(`permissionsFor: remote-manager owner ${JSON.stringify(pin.owner)} does not match the authenticated principal owner ${JSON.stringify(pr.owner)}`);
1412
- const iid = assertLifecycleToken(pin.instanceId, "remote manager instanceId");
1413
- const allowedActors = new Set([`manager_${iid}`, `manager_exec_${iid}`]);
1414
- if (!allowedActors.has(pin.actor) || pr.actor !== pin.actor)
1415
- throw new Error(`permissionsFor: remote-manager actor must be the server-selected manager_${iid} or manager_exec_${iid} for instance ${iid}`);
1416
- const PKV = `KV_${presenceBucket(space)}`;
1417
- const MKV = `KV_${managerBucket(space)}`;
1418
- const AUTH = epAuthBucket(space);
1419
- const REC = recordsBucket(space);
1420
- const gateKey = epgateKey("manager", iid);
1421
- const credPrefix = epcredFamilyPrefix("manager", iid);
1422
- const repairKey = eprepairKey("manager", iid);
1423
- // The SUPERVISOR actor of the pair, which is the one that runs `Manager.start()` and therefore
1424
- // the only one that binds the manager plane's liveness responder (`service.ts` hands
1425
- // `credentials.supervisor` to the manager; the executor gets the instance-scoped registration
1426
- // surface). The liveness rows below are pinned to it so the executor does not carry authority to
1427
- // answer a probe it never serves.
1428
- const isSupervisorActor = pin.actor === `manager_${iid}`;
1429
- const recordKeys = [
1430
- recordSpecKey(RECORD_KINDS.svc, ["manager", iid]),
1431
- recordStatusKey(RECORD_KINDS.svc, ["manager", iid]),
1432
- recordAtomicKey(GOVERN_HEAD, ["manager"]),
1433
- ];
1434
- return {
1435
- pub: {
1436
- allow: [
1437
- "$JS.API.INFO",
1438
- // Only the supervisor allocates names against retained transcript counts. This metadata
1439
- // grant carries no consumer or message-body read, just like the agent CHAT info grant.
1440
- ...(isSupervisorActor ? [`$JS.API.STREAM.INFO.${chatStream(space)}`] : []),
1441
- // Own manager-instance lease only. The local supervisor profile spans lease.* because one
1442
- // host manages every local instance; a remote user grant must not.
1443
- `$JS.API.STREAM.INFO.${MKV}`,
1444
- `$JS.API.STREAM.MSG.GET.${MKV}`,
1445
- `$KV.${managerBucket(space)}.${MANAGER_LEASE_KEY}.${iid}`,
1446
- // Own presence key + roster watch.
1447
- `$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`,
1448
- `$JS.API.STREAM.INFO.${PKV}`,
1449
- `$JS.API.CONSUMER.CREATE.${PKV}.>`,
1450
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
1451
- "$JS.FC.>",
1452
- // This instance's manager service registration + credential family only.
1453
- `$KV.${AUTH}.${gateKey}`,
1454
- `$KV.${AUTH}.${repairKey}`,
1455
- `$KV.${AUTH}.${credPrefix}.>`,
1456
- ...recordKeys.map((key) => `$KV.${REC}.${key}`),
1457
- `${spacePrefix(space)}.epc.*`,
1458
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
1459
- `$JS.API.DIRECT.GET.${epcStreamName(space)}`,
1460
- `$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
1461
- `$JS.API.CONSUMER.CREATE.KV_${AUTH}.>`,
1462
- `$JS.API.CONSUMER.INFO.KV_${AUTH}.>`,
1463
- `$JS.API.CONSUMER.DELETE.KV_${AUTH}.>`,
1464
- ...recordKeys.map((key) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${key}`),
1465
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
1466
- // LIVENESS REPLIES for the MANAGER plane (#1577), bounded to the `.reply.` leaf under a
1467
- // caller's own request subject — the same row and the same bound as the local supervisor
1468
- // profile holds.
1469
- //
1470
- // WHY THIS PROFILE NEEDS IT AT ALL. `Manager.start()` binds the manager plane's liveness
1471
- // responder unconditionally, and a remote manager runs the same `start()` under this
1472
- // credential. Without the serve subscription below the bind is denied, and a peer probing
1473
- // the manager plane then gets the broker's own no-responders answer, which this surface
1474
- // grades `unbound` — a definite verdict about the plane, produced by a gap in a credential,
1475
- // while the remote manager is bound and serving. A surface that exists to stop a failure to
1476
- // find out being rendered as a finding must not render its own missing grant as one.
1477
- //
1478
- // REPLIES ONLY. The row stops at the leaf, so a remote manager cannot publish to the
1479
- // liveness REQUEST subjects and therefore cannot forge a probe that appears to come from a
1480
- // peer, exactly as the supervisor row cannot.
1481
- ...(isSupervisorActor ? [livenessReplyGrant(space, "manager")] : []),
1482
- ],
1483
- },
1484
- sub: {
1485
- allow: [
1486
- `_INBOX_${pr.connId}.>`,
1487
- // The manager-plane liveness SERVE filter (#1577): `live.manager.*.*`, queue-grouped, so a
1488
- // credentialed peer's presence probe reaches this instance. A serve subscription on a
1489
- // presence-only rail and not a widening of what a remote manager may read: the request body
1490
- // is empty and the subject carries only the caller's own principal. The MANAGER plane only —
1491
- // this credential cannot serve `delivery`, so each plane still answers for itself.
1492
- ...(isSupervisorActor ? [livenessServeFilter(space, "manager")] : []),
1493
- ],
1494
- },
1495
- };
1496
- }
1497
- /** The human-CLI OPERATOR permission set — the ephemeral key the headless
1498
- * client commands mint (`cotal send dm|msg|ask`, `cotal dm`, `personas list --running`, via
1499
- * `openTransient`). It does exactly what those do: POST as itself (chat/DM/anycast — self-scoped, can
1500
- * never forge another actor), and READ the public roster (presence) + the channel registry to resolve a
1501
- * name→id and a channel's delivery class. Much narrower than the old broad `manager`: NO serve-control,
1502
- * NO DM/DLV body read, NO chat-history read, NO stream CREATE/DELETE/PURGE, NO ACL write, NO lease, NO
1503
- * provisioning. A leaked operator cred can post as itself and read the roster — the same surface as the
1504
- * human who ran the command. (The interactive `cotal join` console — chat read + own-DM receive — is a
1505
- * separate, fuller surface, deferred: it needs the unprovisioned-console DM self-create fixed first.) */
1506
- function operatorPermissions(space, pr) {
1507
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
1508
- return {
1509
- pub: {
1510
- allow: [
1511
- // Post AS itself only — self-scoped (owner+actor), so a leaked operator cred can never forge a
1512
- // message attributable to another principal.
1513
- chatSubject(space, pr.owner, pr.actor, ">"), // chat.<o>.<a>.> — multicast any channel as me
1514
- unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a> — DM any peer as me
1515
- anycastSubject(space, "*", pr.owner, pr.actor), // svc.*.<o>.<a> — anycast any role as me
1516
- `$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`, // own presence key only
1517
- "$JS.API.INFO",
1518
- // Presence read (name→id resolution + the roster). The transient endpoint reads the bucket once
1519
- // with a batched Direct Get, whose request subject is the bare stream (#4091); the consumer rows
1520
- // serve a watch. No STREAM.MSG.GET.
1521
- `$JS.API.STREAM.INFO.${PKV}`,
1522
- `$JS.API.DIRECT.GET.${PKV}`,
1523
- `$JS.API.CONSUMER.CREATE.${PKV}.>`,
1524
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
1525
- // Channel registry read — the transient endpoint reads it once (batched Direct Get), multicast
1526
- // reads a channel's delivery class, and `channels list` scans it. Read-only (no `$KV.<channel>`
1527
- // write — that's the provisioner).
1528
- `$JS.API.STREAM.INFO.${CHKV}`,
1529
- `$JS.API.DIRECT.GET.${CHKV}`,
1530
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
1531
- // Keyed KV get rides `DIRECT.GET.<stream>.$KV.<bucket>.<key>` — the key is in the SUBJECT, so
1532
- // the grant needs the trailing `.>` (unlike STREAM.MSG.GET, which carries it in the payload).
1533
- `$JS.API.DIRECT.GET.${CHKV}.>`,
1534
- `$JS.API.CONSUMER.CREATE.${CHKV}.>`,
1535
- `$JS.API.CONSUMER.INFO.${CHKV}.>`,
1536
- "$JS.FC.>", // ordered-consumer flow control
1537
- ],
1538
- },
1539
- // Own reply inbox only (presence/channel watch ordered-consumer delivery + any request replies land
1540
- // here). NO chat/inst/dlv native sub — the operator posts and reads the roster, it receives no feed.
1541
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1542
- };
1543
- }
1544
- /** Connect-only PROBE — the liveness/auth preflight (`preflight.ts preflightTarget`, minted on
1545
- * ~every CLI command that resolves a mesh). `probeConnect` opens a connection to prove the broker is up
1546
- * and the creds are accepted, then closes it — it performs NO pub/sub. So the tightest possible grant:
1547
- * deny ALL publish, subscribe only to the own reply inbox. A leaked probe cred can open a socket and do
1548
- * nothing else. (Was the broad `manager` cred — minted on nearly every command, the worst over-grant.) */
1549
- function probePermissions(pr) {
1550
- return { pub: { deny: [">"] }, sub: { allow: [`_INBOX_${pr.connId}.>`] } };
1551
- }
1552
- /** CHANNEL-WRITER — edits the channel registry ONLY: `cotal channels set/default` and the
1553
- * `spawn -f` new-channel seed (`seedChannelRegistry`). It VALUE-writes `$KV.<channelBucket>` (a channel's
1554
- * config key) and read-before-writes it. NO stream data, NO other bucket, NO chat/DM — a leaked
1555
- * channel-writer can only rewrite channel config, never post, read a body, or tear a stream down. */
1556
- function channelWriterPermissions(space, pr) {
1557
- const CHKV = `KV_${channelBucket(space)}`;
1558
- return {
1559
- pub: {
1560
- allow: [
1561
- "$JS.API.INFO",
1562
- `$KV.${channelBucket(space)}.>`, // create/update/delete a channel config key
1563
- `$JS.API.STREAM.INFO.${CHKV}`, // kvm.open/create existence check
1564
- `$JS.API.STREAM.CREATE.${CHKV}`, // kvm.create is create-if-matching (bucket already exists post-up)
1565
- // read-before-write: kvm.open rides STREAM.MSG.GET; kvm.create (direct=true) rides keyed DIRECT.GET.
1566
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
1567
- `$JS.API.DIRECT.GET.${CHKV}.>`,
1568
- ],
1569
- },
1570
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1571
- };
1572
- }
1573
- /** CHANNEL-PURGER — the `cotal web` dashboard's ONLY write path: delete a channel
1574
- * (`clearChannel` = filtered `STREAM.PURGE.CHAT` to drop the channel's messages + a `$KV.<channelBucket>`
1575
- * key delete). Pre-minted once by `web` so the account signing seed falls out of scope; the dashboard's
1576
- * READ side runs on the separate read-only `admin` cred. = channel-writer + the scoped CHAT purge. */
1577
- function channelPurgerPermissions(space, pr) {
1578
- const CHKV = `KV_${channelBucket(space)}`;
1579
- // `clearChannel` only kvm.OPENs the (already-created) bucket, key-deletes, and purges — it never
1580
- // kvm.creates, so — unlike channel-writer's set/default back-compat path — this cred gets NO
1581
- // `STREAM.CREATE`. Compose the shared channel-KV read + delete verbs + the scoped CHAT purge explicitly.
1582
- return {
1583
- pub: {
1584
- allow: [
1585
- "$JS.API.INFO",
1586
- `$KV.${channelBucket(space)}.>`, // delete the channel's registry key
1587
- `$JS.API.STREAM.INFO.${CHKV}`, // kvm.open existence check
1588
- `$JS.API.STREAM.MSG.GET.${CHKV}`, // read-before-delete
1589
- `$JS.API.DIRECT.GET.${CHKV}.>`,
1590
- `$JS.API.STREAM.PURGE.${chatStream(space)}`, // drop the channel's chat messages
1591
- ],
1592
- },
1593
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1594
- };
1595
- }
1596
- /** TEARDOWN — `cotal down -f` space teardown. The space-wide cred that keeps `STREAM.DELETE` (the
1597
- * tamper verb). `down -f` is multi-step: `connectProbe` (presence-watch + channel-registry read)
1598
- * → invoke the manager's `ps` + any-mode `despawn` over the ep rails to politely stop the managed
1599
- * agents → `readMembership` (the membership-feed read that keeps an owned channel another member
1600
- * still uses) → `deleteChannels`
1601
- * (channel-registry key delete + CHAT purge) → `deleteSpace` (STREAM.DELETE every owned stream/bucket).
1602
- * So it reads state, CALLS admin control, deletes channels, and deletes streams — but NEVER reads a
1603
- * DM/DLV body, posts chat, or forges. Isolated here so no standing operator/provisioner/supervisor cred
1604
- * can delete a stream; a leaked teardown can wipe a space you own + stop its agents (that IS its job),
1605
- * nothing else. Minted ephemerally per teardown from the local trust material (same-checkout `down -f`). */
1606
- function teardownPermissions(space, pr, transferStreams) {
1607
- // The ep-rail mirror of the admin deploy tier: teardown reads `ps` and stops owned agents
1608
- // it did not spawn (any-mode despawn) - the admin instrument set. Lifecycle-keyed, so a uid is
1609
- // required at mint (fail-loud).
1610
- const ep = instrumentEpRows(space, pr, "admin");
1611
- const CHAT = chatStream(space);
1612
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
1613
- const MSHIP = `KV_${membershipBucket(space)}`;
1614
- const RECORDS = `KV_${recordsBucket(space)}`;
1615
- // The deletion path and the exact per-stream grants use one target list. Reject any caller-
1616
- // supplied transfer name that is not this space's transfer bucket before minting the grant.
1617
- for (const name of transferStreams)
1618
- if (!isTransferStream(space, name))
1619
- throw new Error(`permissionsFor: teardown transferStreams names ${JSON.stringify(name)}, not one of ${space}'s transfer streams`);
1620
- const del = spaceDeletionStreams(space, transferStreams)
1621
- .flatMap((s) => [`$JS.API.STREAM.INFO.${s}`, `$JS.API.STREAM.DELETE.${s}`]);
1622
- return {
1623
- pub: {
1624
- allow: [
1625
- "$JS.API.INFO",
1626
- BROKER_USER_INFO_SUBJECT, // confirm the current teardown connection's account before native impact reads
1627
- // deleteSpace() enumerates the transfer streams (one per manager instance that received a
1628
- // carried resume) by name shape; their names are not derivable from the space alone.
1629
- "$JS.API.STREAM.NAMES",
1630
- // connectProbe read: presence watch (name→id + roster) + channel registry read.
1631
- `$JS.API.CONSUMER.CREATE.${PKV}.>`,
1632
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
1633
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
1634
- `$JS.API.DIRECT.GET.${CHKV}.>`,
1635
- `$JS.API.CONSUMER.CREATE.${CHKV}.>`,
1636
- `$JS.API.CONSUMER.INFO.${CHKV}.>`,
1637
- // readMembership's one-pass scan of the feed (its STREAM.INFO is in `del`). No `$KV` publish:
1638
- // only `membership-rw` writes the feed.
1639
- // Batched snapshots read the same feed as the watch below, without a consumer.
1640
- `$JS.API.DIRECT.GET.${MSHIP}`,
1641
- `$JS.API.CONSUMER.CREATE.${MSHIP}.>`,
1642
- `$JS.API.CONSUMER.INFO.${MSHIP}.>`,
1643
- // Space deletion names the workflow runs it removes by their status records: a non-fencing
1644
- // direct get confined to run status keys (§13.9), on a stream this grant may already delete.
1645
- `$JS.API.DIRECT.GET.${RECORDS}.$KV.${recordsBucket(space)}.run.*.*.status`,
1646
- "$JS.FC.>", // ordered-consumer flow control
1647
- // Stop the managed agents over the v0.4 ep rails only (ps + any-mode despawn) — the admin
1648
- // instrument set. The manager `ctl` rail is deleted.
1649
- ...ep.pub,
1650
- ...del,
1651
- // deleteChannels/clearChannel: purge the channel's chat messages + delete its registry key.
1652
- `$JS.API.STREAM.PURGE.${CHAT}`,
1653
- `$KV.${channelBucket(space)}.>`,
1654
- ],
1655
- },
1656
- // Own inbox (connectProbe presence-watch delivery + JS API responses) + the ep reply rail (the
1657
- // ps + any-mode despawn calls reply there). The `ctl.admin.<id>.reply.>` subtree is gone.
1658
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
1659
- };
1660
- }
1661
- /** MEMBERSHIP-STORE-RECREATE — explicit conversion of the derived membership feed from File to
1662
- * Memory. The credential can inspect and delete exactly that one stream. It cannot create the
1663
- * replacement, read membership values, or touch another stream; the ordinary short-lived
1664
- * provisioner creates and verifies the empty Memory replacement after deletion. */
1665
- function membershipStoreRecreatePermissions(space, pr) {
1666
- const stream = `KV_${membershipBucket(space)}`;
1667
- return {
1668
- pub: {
1669
- allow: [
1670
- "$JS.API.INFO",
1671
- `$JS.API.STREAM.INFO.${stream}`,
1672
- `$JS.API.STREAM.DELETE.${stream}`,
1673
- ],
1674
- },
1675
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1676
- };
1677
- }
1678
- /** ISSUED-STORE-RECREATE — `cotal up --recreate-issued-stores`, and an embedder's call of
1679
- * `removeIssuedStoresBeforeRetention`: back up, then delete, the two issued-authority stores of ONE
1680
- * space that predate bounded retention. Exactly `STREAM.INFO`, `STREAM.SNAPSHOT` and
1681
- * `STREAM.DELETE` on those two streams, the snapshot's delivery inside its own inbox, and the
1682
- * snapshot ACK subjects of those two streams ({@link snapshotAckGrant}). Nothing reads a row,
1683
- * writes a store or reaches another stream. */
1684
- function issuedStoreRecreatePermissions(space, pr) {
1685
- return {
1686
- pub: {
1687
- allow: [
1688
- "$JS.API.INFO",
1689
- ...issuedStoreStreamNames(space).flatMap((s) => [`$JS.API.STREAM.INFO.${s}`, `$JS.API.STREAM.SNAPSHOT.${s}`, `$JS.API.STREAM.DELETE.${s}`, snapshotAckGrant(s)]),
1690
- ],
1691
- },
1692
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1693
- };
1694
- }
1695
- /** CONTROL-CALLER (ep rails only) — the operator's lifecycle commands
1696
- * (`cotal ps/start/stop/attach`, `manager/commands.ts`). It invokes the manager's v0.4 service
1697
- * endpoint and reads the bounded reply on the ep reply rail. That is ALL — no `$JS`, no `$KV`,
1698
- * no chat/DM: it forges nothing, reads no body.
1699
- *
1700
- * The tiers stay SPLIT because the BROKER grant is load-bearing: an any-mode
1701
- * despawn/attach row *is* cross-agent reach — the manager maps mode `any` to its admin
1702
- * authorization path, so which ROWS an instrument holds is the tier boundary. Therefore:
1703
- * • `control-caller-privileged` (ps/start) holds the manager reads + untargeted `spawn` +
1704
- * `define-persona` — structurally barred from cross-agent ops (no any-mode row). This is the
1705
- * high-frequency path; it never needs admin reach.
1706
- * • `control-caller-admin` (stop/attach) adds the any-mode despawn/attach rows + the
1707
- * `manager.admin` family — it genuinely needs cross-agent reach. Its containment is the
1708
- * broker gating the any-mode rows + the cred being ephemeral (mint → one request →
1709
- * disconnect, from the local signing seed); on a user mesh the manager's serve-time ledger
1710
- * re-check sits on top. */
1711
- function controlCallerPermissions(space, pr, epTier, opts = {}) {
1712
- // The manager `ctl` rail is gone — an operator instrument holds ONLY its v0.4 ep rows (the
1713
- // tier-matched request set, the reply rail, describe, the one epc fetch). The `epTier` selects
1714
- // privileged (ps/start reads) vs admin (any-mode stop/attach) exactly as the ctl tier did.
1715
- //
1716
- // `--on <instanceId>`: these instruments are ONE-SHOT, minted per control call, and the
1717
- // resolve that pins the instance happens BEFORE the mint. So the caller can hand the exact
1718
- // instance id down and get the exact `ep.inst.<endpoint>.<iid>.<command>` row for THIS invocation
1719
- // and nothing else — the least-privilege issuance, with no standing wildcard anywhere. The
1720
- // `extra` seam is the same one the deployer's owner-equality `launch` row already rides, and the
1721
- // emitter's `if (cap.instanceId)` branch validates the token, so a malformed id fails loud at
1722
- // mint rather than widening a subject.
1723
- const ep = instrumentEpRows(space, pr, epTier, opts.endpointCapabilities ?? [], opts);
1724
- return {
1725
- // The PRIVILEGED tier (the `cotal ps` instrument) also carries the SCOPED §13.9 records read the
1726
- // class scatter's freeze rides: `freezeExpectedSet` enumerates `svc.<endpoint>.*.spec`
1727
- // and LEADER-reads each frozen slot's svc spec/status before it scatters `ps` on the `all` rail.
1728
- // The admin tier (stop/attach) never scatters, so it gets no records read.
1729
- pub: { allow: epTier === "privileged" ? [...ep.pub, ...scatterFreezeReadRows(space)] : ep.pub },
1730
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
1731
- };
1732
- }
1733
- /** The SCOPED §13.9 records-read rows the class-scatter freeze rides (`cotal ps`): the
1734
- * `svc.*` enumeration consumer + the leader-served per-slot spec/status read of the endpoint's
1735
- * `svc` registry — a READ of exactly the service-registration keys, no write, no other bucket.
1736
- * The keyed Direct Get is subject-PINNED to `svc.>`; the enumeration consumer
1737
- * and the leader `STREAM.MSG.GET` are STREAM-scoped because the requested key rides the PAYLOAD
1738
- * (which a subject grant cannot narrow) — the SAME NAMED RESIDUAL every records reader already
1739
- * accepts (the provisioner, the lifecycle/serve executors): for this EPHEMERAL one-shot instrument's
1740
- * lifetime it can READ (never write) any records-store row — registration metadata, no secrets. */
1741
- function scatterFreezeReadRows(space) {
1742
- const REC = recordsBucket(space);
1743
- return [
1744
- // The `svc.<e>.*.spec` enumeration is a `STREAM.INFO` carrying a `subjects_filter` — ONE
1745
- // read-only metadata verb. It replaced a `kv.keys()` that rode an ordered ephemeral consumer and
1746
- // therefore needed CONSUMER.CREATE/INFO/DELETE on this bucket: three consumer-lifecycle verbs to
1747
- // list keys, on a credential that only ever wanted to read them.
1748
- //
1749
- // MEASURED, not assumed: with the enumeration converted and this row absent, the static/operator
1750
- // `cotal ps` is refused on `$JS.API.STREAM.INFO.KV_<records>` — a path that works today. The
1751
- // conversion and this row land TOGETHER or the operator path regresses.
1752
- `$JS.API.STREAM.INFO.KV_${REC}`,
1753
- // The per-slot spec/status reads (`freezeExpectedSet` + the registration reconcile) are
1754
- // leader-served `STREAM.MSG.GET` — stream-scoped (NAMED RESIDUAL above), plus the subject-pinned
1755
- // keyed Direct Get form for any direct-aware read path (scoped to the `svc.` registry prefix).
1756
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
1757
- `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.>`,
1758
- ];
1759
- }
1760
- /** The v0.4 ep-rail rows of an operator INSTRUMENT credential: the tier-matched
1761
- * {@link operatorInstrumentCapabilities} request rows + the caller's reply rail, the wildcard
1762
- * `describe` form, and the ONE subject-scoped §13.7 contract-store fetch row (the same shape the
1763
- * agent baseline holds). No ctl row exists, so these ARE the instrument. The caller triple pins the instrument's own mint-time lifecycle uid
1764
- * ({@link MintPrincipal.lifecycleUid}) — REQUIRED here: without it the reply rail cannot be pinned
1765
- * and the mint fails loud rather than emit a triple-less (unfenced) caller surface. `extra` lets a
1766
- * profile append its tier-refined additions (the user-mode deployer's owner-equality `launch`). */
1767
- function instrumentEpRows(space, pr, tier, extra = [], opts = {}) {
1768
- if (!pr.lifecycleUid)
1769
- throw new Error(`permissionsFor: an operator instrument's ep caller rows are lifecycle-keyed (SPEC 13.1/13.2) - mint with opts.lifecycleUid (mintLifecycleUid()) so the reply rail pins the instrument's own incarnation`);
1770
- const epCaller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid: pr.lifecycleUid }, opts);
1771
- const rows = epCallerGrantRows(space, [...operatorInstrumentCapabilities(tier, pr.owner), ...extra], epCaller);
1772
- return {
1773
- pub: [
1774
- epDescribeAllGrantRow(space, epCaller),
1775
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
1776
- ...(opts.issued ? [acceptedReadGrant(space, opts.issued.acceptedToken)] : []),
1777
- ...rows.pub,
1778
- ],
1779
- sub: rows.sub,
1780
- };
1781
- }
1782
- /** The ep caller a mint pins: the triple, plus the issued generation when the mint is an
1783
- * issuance (SPEC 13.15). One place decides the rail so a credential's request rows, its reply
1784
- * read, and its describe row all land on the same one. */
1785
- function issuedCallerFor(triple, opts) {
1786
- if (!opts.issued)
1787
- return triple;
1788
- assertGeneration(opts.issued.acceptedToken, "acceptedToken");
1789
- return { ...triple, generation: assertGeneration(opts.issued.generation) };
1790
- }
1791
- /** The rows a listing generation adds to a legacy-rail credential (SPEC 13.15, "Listing
1792
- * issuance"): the registry's `endpoints` request publish and its reply subscribe on `ep.v1`, and
1793
- * the per-key read of the generation's accepted row. Exactly these: one caller value emits one
1794
- * rail, so these are the only `ep.v1` rows such a credential holds. */
1795
- export function listingGrantRows(space, caller, listing) {
1796
- if (isIssuedCaller(caller))
1797
- throw new Error("listingGrantRows: an issued caller lists under its own generation");
1798
- assertGeneration(listing.acceptedToken, "acceptedToken");
1799
- const issued = { owner: caller.owner, actor: caller.actor, uid: caller.uid, generation: assertGeneration(listing.generation) };
1800
- return {
1801
- pub: [...epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, issued), acceptedReadGrant(space, listing.acceptedToken)],
1802
- sub: [epCallerReplyFilter(space, issued)],
1803
- };
1804
- }
1805
- /** ENDPOINT-SERVE (v0.4, SPEC §13.9 "Serve grants") — the per-instance serve credential:
1806
- * EXACTLY the instance's registered rails and nothing else. Subscribe: the queue-qualified
1807
- * class rail, the plain scatter rail, and the own-instance rail for the FULL registered
1808
- * command set plus the derived `describe`, and the own epoch-pinned timer-fire subjects;
1809
- * publish: the epoch-pinned egress (reply / `epe` events / `ept` schedule requests / `epr`
1810
- * record-write ingress) plus, from the branded snapshot only, the §13.9 bind rows: the shared
1811
- * `eff_<e>` effects bind iff the surface is journal-class and each owned `pool_<e>_<pool>`
1812
- * bind (bind-only + `$JS.API.INFO`; an ephemeral-only poolless endpoint emits none). No agent
1813
- * baseline of any kind — no chat/DM/anycast/presence/ctl, no broad `$JS.>`. The value MUST be the
1814
- * branded ARTIFACT `authorizeServeGrant` returned, and its mint context binds: same space, and
1815
- * the minted principal is the registered owner. This builds the ROWS; the RELEASE fence is the
1816
- * durable issuance-gate CAS `mintCreds` runs (SPEC §13.1) — a raw/copied/diverging value or a
1817
- * foreign space/principal refuses here, and a stale incarnation loses the gate CAS. */
1818
- function endpointServePermissions(space, pr, opts) {
1819
- if (!opts.endpointServe)
1820
- throw new Error("permissionsFor: endpoint-serve requires opts.endpointServe (the authorized serve artifact)");
1821
- // The fence is INSEPARABLE from serve-row emission: a serve credential's rows are only ever
1822
- // valid when released behind the §13.1 issuance CAS, so this builder refuses to emit them
1823
- // without the gate seam — closing the exported-permissionsFor bypass where a direct signer
1824
- // could obtain unfenced serve rows past the brand/space/owner check. `mintCreds` runs the CAS.
1825
- if (!opts.serveIssuance)
1826
- throw new Error("permissionsFor: endpoint-serve requires opts.serveIssuance (serve rows are emitted only behind the §13.1 issuance fence; mintCreds runs its CAS before release)");
1827
- const snap = assertServeGrantMintable(opts.endpointServe, { space, holderOwner: pr.owner });
1828
- // Rail subscribe rows cover the EPHEMERAL commands only (journal commands ride epj, never the
1829
- // request rails) + the derived describe; the descriptor surface stays full. The class comes
1830
- // from the brand-verified artifact surface, not the caller.
1831
- const ephemeralCommands = snap.commands.filter((cmd) => opts.endpointServe.surface[cmd].class === "ephemeral");
1832
- const rows = epServeGrantRows(space, {
1833
- endpoint: snap.endpoint, instanceId: snap.instanceId, epoch: snap.epoch, ephemeralCommands,
1834
- });
1835
- // §13.9 bind rows, from the BRANDED snapshot only (journal class is registered truth,
1836
- // pools are the authorizing provisioner's pre-created durables): a journal-class instance
1837
- // binds the shared `eff_<e>` effects durable, a pool-owning one binds each owned
1838
- // `pool_<e>_<pool>` — all bind-only (INFO/MSG.NEXT/ACK, never create/delete), plus the one
1839
- // `$JS.API.INFO` a pull consumer needs. An ephemeral-only poolless endpoint emits NONE of
1840
- // these rows (default-deny both directions).
1841
- const bindRows = [];
1842
- if (snap.journalClass)
1843
- bindRows.push(...effectsBindGrants(space, snap.endpoint));
1844
- for (const pool of snap.pools)
1845
- bindRows.push(...poolOwnerBindGrants(space, snap.endpoint, pool));
1846
- if (bindRows.length > 0)
1847
- bindRows.push("$JS.API.INFO");
1848
- return {
1849
- pub: { allow: [...rows.pub, ...bindRows] },
1850
- sub: { allow: [...rows.sub, `_INBOX_${pr.connId}.>`] },
1851
- };
1852
- }
1853
- /** DEPLOYER — the `cotal spawn -f` manifest-deploy authority. `spawn -f` drives ONE
1854
- * `connectProbe` endpoint that both READS live state (roster/presence watch, channel registry,
1855
- * membership feed, manager-singleton lease) AND invokes the running manager's `launch` + `ps`
1856
- * readiness over the v0.4 ep rails. Those interleave on one connection, so a strict 3-connection
1857
- * split would only refactor `live.ts` for marginal gain; `deployer` is that one coherent,
1858
- * ephemeral deploy cred. It is the SOLE profile that combines reads + admin-control — NOT a template a
1859
- * 4th command should reach for (revisit the connection split before adding a second such caller).
1860
- *
1861
- * Boundaries (all enforced by omission / default-deny): NO self-post (`chat`/`inst`/`svc`), NO `$JS.>`,
1862
- * NO `STREAM.DELETE`/`PURGE`/`UPDATE`, NO DM/DLV/TASK `CONSUMER.CREATE` (no body-read surface), NO `$KV`
1863
- * writes (channel seeding rides a SEPARATE `channel-writer` cred). It holds the admin INSTRUMENT ep
1864
- * set (any-mode despawn/attach + the manager.admin family + reads) because manifest launch/ps
1865
- * genuinely need cross-agent reach — and that IS real power: the manager's any-mode authz is
1866
- * subject-gated (the any-mode ep row is mintable only under operator policy), so holding it lets it
1867
- * stop/attach/launch ANY agent. The BROKER gating that row is the boundary. Containment is therefore
1868
- * the LIFETIME, not a manager re-check: minted from LOCAL same-checkout auth for one `spawn -f`,
1869
- * memory-only, dropped after deploy. If it is ever persisted, handed to user-supplied `--creds`, or
1870
- * reused as a general "read + admin" cred, revisit. */
1871
- function deployerPermissions(space, pr, epTier = "admin", opts = {}) {
1872
- // The v0.4 ep rows of the deploy authority: static (admin) deploys carry the admin instrument
1873
- // set; the user-mode deployer VIEW (privileged) carries the privileged set PLUS an untargeted
1874
- // `launch` row — its launch stays owner-equality-authorized (the manager's ledger-derived admin
1875
- // flag is false for a spawn-scoped deployer), exactly the v0.3 user-mode privileged-tier launch.
1876
- // `--on`: the per-invocation pin APPENDS to this profile's standing set, never replaces it -
1877
- // the privileged deployer view keeps its owner-equality `launch` row and additionally gets the one
1878
- // exact `ep.inst.<endpoint>.<iid>.<command>` row for the instance this deploy resolved.
1879
- const pinned = opts.endpointCapabilities ?? [];
1880
- const ep = epTier === "admin"
1881
- ? instrumentEpRows(space, pr, "admin", pinned, opts)
1882
- : instrumentEpRows(space, pr, "privileged", [{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: "launch" }, ...pinned], opts);
1883
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
1884
- const MSHIP = `KV_${membershipBucket(space)}`, MGRKV = `KV_${managerBucket(space)}`;
1885
- const DLVKV = `KV_${deliveryBucket(space)}`;
1886
- // Read verbs for a KV bucket SCANNED/WATCHED via an ordered consumer (presence, channel registry, and
1887
- // the membership feed — `readMembership` enumerates keys via `kv.keys()`): existence + kv.get (both
1888
- // STREAM.MSG.GET and keyed DIRECT.GET forms) + the ordered consumer. NO `$KV.<bucket>` publish → no write.
1889
- const kvScan = (bucket) => [
1890
- `$JS.API.STREAM.INFO.${bucket}`,
1891
- `$JS.API.STREAM.MSG.GET.${bucket}`,
1892
- `$JS.API.DIRECT.GET.${bucket}.>`,
1893
- `$JS.API.CONSUMER.CREATE.${bucket}.>`,
1894
- `$JS.API.CONSUMER.INFO.${bucket}.>`,
1895
- ];
1896
- // A KV bucket read by a KEYED point-get only (`readManagerLease` = kvm.open + `kv.get(LEASE_KEY)`, no
1897
- // scan/watch): existence + kv.get, but NO ordered-consumer verbs (nothing enumerates or watches it).
1898
- const kvPointRead = (bucket) => [
1899
- `$JS.API.STREAM.INFO.${bucket}`,
1900
- `$JS.API.STREAM.MSG.GET.${bucket}`,
1901
- `$JS.API.DIRECT.GET.${bucket}.>`,
1902
- ];
1903
- return {
1904
- pub: {
1905
- allow: [
1906
- "$JS.API.INFO",
1907
- ...kvScan(PKV), // presence watch — roster + name→id
1908
- ...kvScan(CHKV), // channel registry read (readChannelRegistry + classifyChannels)
1909
- ...kvScan(MSHIP), // membership FEED read (readMembership → detectUnmanagedActors) — the membership_ bucket
1910
- ...kvPointRead(MGRKV), // manager-singleton lease keyed read (waitManagerReady) — point-get, NO write, NO watch
1911
- ...kvPointRead(DLVKV), // delivery-lease keyed read (preserve-state quiescence proof) — point-get, NO write, NO watch
1912
- "$JS.FC.>", // ordered-consumer flow control
1913
- // Launch + ps readiness ride the v0.4 ep rows only (the manager `ctl` rail is gone).
1914
- // Static deploys carry the admin instrument set; the user-mode deployer VIEW carries the
1915
- // privileged set + an owner-equality `launch` row (the manager's ledger-derived admin flag
1916
- // is false for a spawn-scoped deployer, so its launch stays owner-equality-authorized).
1917
- ...ep.pub,
1918
- ],
1919
- },
1920
- // Own inbox (presence/registry watch delivery + JS API responses) + the ep reply rail.
1921
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
1922
- };
1923
- }
1924
- /** The ephemeral PURGER permission set — minted per-purge inside the daemon's
1925
- * `opPurge` and `cotal history clear`. Isolates the DESTRUCTIVE history-purge grant
1926
- * (`STREAM.PURGE.CHAT` + `STREAM.PURGE.DM`) off the always-on supervisor: `--dms` purges the DM stream,
1927
- * exactly the grant the supervisor must not hold. It PURGES but never READS — no DM/chat consumer, no
1928
- * `MSG.GET` — so a leaked purger can drop history but cannot read a body. Short-lived (one purge call). */
1929
- function purgerPermissions(space, pr) {
1930
- const CHAT = chatStream(space), DM = dmStream(space);
1931
- return {
1932
- pub: {
1933
- allow: [
1934
- "$JS.API.INFO", // jetstreamManager bootstrap; STREAM.PURGE needs no prior STREAM.INFO
1935
- `$JS.API.STREAM.PURGE.${CHAT}`, // clearSpaceHistory chat purge
1936
- `$JS.API.STREAM.PURGE.${DM}`, // clearSpaceHistory includeDms — the isolated DM-purge grant
1937
- ],
1938
- // NOTE: this profile does NOT cover `clearChannel` (web/`down -f` channel-delete) — that also does a
1939
- // `$KV.<channelBucket>.<ch>` registry delete this cred lacks, which `channel-purger` and `teardown` hold.
1940
- },
1941
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1942
- };
1943
- }
1944
- /** The ephemeral PROVISIONER permission set — the onboarding authority,
1945
- * carved off the long-lived manager. Minted short-lived for per-spawn provisioning (pre-create each
1946
- * agent's bind-only DM/DLV/TASK durables + record its read ACL via `commitAcl`) — the daemon opens it per
1947
- * spawn (`manager.ts withProvisioner`). It is ALSO the cred that creates the space's streams + KV buckets
1948
- * and seeds the channel registry via `setupSpaceStreams` (exercised by the manager-split smoke) — and
1949
- * `cotal up`'s ephemeral setup cred (`up.ts authSetup`) now mints THIS profile, not the broad `manager`.
1950
- * NEVER minted for an agent — `cotal mint` whitelists
1951
- * agent/observer/admin only, like `manager`/`delivery`.
1952
- *
1953
- * This profile HOLDS the DM/DLV `CONSUMER.CREATE` push-consumer surface — the irreducible onboarding
1954
- * power (the create-time `deliver_subject` of a push consumer is not ACL-constrained, so whoever can
1955
- * create a DM/DLV consumer can stream the bodies). That is exactly why it is split OFF the always-on
1956
- * supervisor and made EPHEMERAL: the daemon opens a provisioner connection per spawn and drains it
1957
- * immediately, so the surface exists only for the provisioning window, not as a standing target. The
1958
- * cred is MEMORY-ONLY (never written to `.cotal`) and carries a short profile-default `exp`.
1959
- *
1960
- * `$JS` is an ENUMERATED allow-list, never `$JS.>`: STREAM.CREATE + INFO for the space streams/buckets,
1961
- * DM/DLV/TASK consumer CREATE/DURABLE.CREATE/INFO — and deliberately NO `MSG.NEXT`/`MSG.GET`/`ACK` on
1962
- * DM/DLV (it creates the bind-only mailbox but never reads it), and NO STREAM.DELETE/PURGE/MSG.DELETE
1963
- * (it provisions, it does not tear down). STREAM.UPDATE is held on EXACTLY thirteen streams and no others:
1964
- * the three TTL'd KV buckets (presence + the two leases, #286: an existing bucket's `max_age` cannot be
1965
- * fixed by `kvm.create`, so reconciling a pre-TTL deployment requires updating it), the four hardened
1966
- * authority stores (records, issued, accepted, admission), each updated once at creation, and the
1967
- * membership KV and artifact Object Store, whose legacy `max_bytes` values setup reconciles to -1 (the
1968
- * reservation a positive cap holds against the broker's `max_file_store` is what stopped a tenth space
1969
- * from being provisioned; `Objm.create` cannot fix an existing bucket's cap either), and the CHAT,
1970
- * INBOX, DLV and DM streams, whose history limits `cotal history limit` writes (`setHistoryLimit`).
1971
- * Stated positively on purpose: this docblock previously read "NO …/UPDATE", which was already untrue of
1972
- * the records stream and became untrue of the buckets, and a comment that denies a credential's real
1973
- * power is worse than none — it is the document a reader trusts instead of checking. KV value-writes are
1974
- * scoped to exactly the two
1975
- * registries provisioning touches: the read-ACL bucket (`commitAcl`) and the channel registry (seed). */
1976
- function provisionerPermissions(space, pr) {
1977
- const CHAT = chatStream(space), DM = dmStream(space), TASK = taskStream(space);
1978
- const INBOX = inboxStream(space), DLV = dlvStream(space);
1979
- // Every non-endpoint KV backing stream the provisioner pre-creates. Endpoint control streams and
1980
- // their records/auth/session buckets come from endpointPlaneStreamNames below, the same downstream
1981
- // ownership list consumed by inventory and teardown. The provisioner holds create-or-verify only on
1982
- // those authority stores; lifecycle/session writes ride their narrower executor credentials.
1983
- const buckets = [
1984
- presenceBucket, channelBucket, membersBucket, aclBucket, membershipBucket, anycastBucket, deliveryBucket, managerBucket,
1985
- ].map((b) => `KV_${b(space)}`);
1986
- // STREAM.CREATE + INFO for each (idempotent setup at `cotal up`; CREATE is create-if-matching, INFO covers
1987
- // the client's existence checks). NO DELETE/PURGE — provisioning never tears a stream down.
1988
- // The §13.7 CONTRACT store (EPC) joins the list for the static manager's start-time
1989
- // `ensureContractStore`: create-or-verify only — the provisioner holds no
1990
- // artifact-publish grant on it (publication rides the scoped endpoint-serve executor).
1991
- // The seven §13.12 ENDPOINT streams join the list: spawn-as-action makes the manager
1992
- // the first EPF (goal facts) + EPE (progress) writer, and nothing provisioned the endpoint streams
1993
- // before (no manager code wrote to them), so `createEndpointStreams` now runs at the manager's
1994
- // start-time ensure over this provisioner. Create-or-verify only (idempotent, fail-loud on drift);
1995
- // the provisioner holds no value-write on any of them (goal facts ride the scoped goal-writer cred).
1996
- // WFJ and the EPC/records/auth/session stores join them through endpointPlaneStreamNames because
1997
- // createEndpointStreams owns all twelve resources. Create-or-verify only; the provisioner appends
1998
- // nothing (writes ride the narrower runtime and authority credentials).
1999
- // The artifact Object Store joins the list: `setupSpaceStreams` creates it, and under auth mode the
2000
- // provisioner is the cred doing that creating. Its backing stream is `OBJ_<bucket>` - named
2001
- // explicitly, because `$O.<bucket>.>` is outside the `cotal.<space>.>` grammar and no space-prefix
2002
- // grant reaches it. CREATE + INFO here, plus the ONE STREAM.UPDATE below (the legacy-cap reconcile):
2003
- // the provisioner never publishes an object, never creates a consumer on it, and never deletes it.
2004
- // That confinement is load-bearing rather than tidy - the
2005
- // object-store client reads by creating an ephemeral PUSH consumer with a caller-chosen
2006
- // `deliver_subject`, so a CONSUMER.CREATE here would be an exporter of every artifact in the space.
2007
- const OBJ = objectStoreStream(artifactBucket(space));
2008
- const streamSetup = [CHAT, DM, TASK, INBOX, DLV, eventPayloadStream(space), OBJ, ...endpointPlaneStreamNames(space), ...buckets].flatMap((s) => [
2009
- `$JS.API.STREAM.CREATE.${s}`,
2010
- `$JS.API.STREAM.INFO.${s}`,
2011
- ]);
2012
- // #286: STREAM.UPDATE on EXACTLY the three TTL'd KV streams (presence + the two leases). `kvm.create`
2013
- // never updates an existing bucket's config, so a bucket created by a cotal that predates the `max_age`
2014
- // TTL keeps NO expiry forever — dead presence records (and stale leases) never age out. `setupSpaceStreams`
2015
- // reconciles their `max_age` via STREAM.UPDATE at every `cotal up`, which needs this grant. Scoped to these
2016
- // three streams here. The durable task stream and the channel/members/acl registries are never
2017
- // updated (the history limits of the four message streams are the exception, below), and there is
2018
- // still NO DELETE/PURGE. The supervisor profile keeps its full UPDATE
2019
- // denial; this widening is provisioning-only.
2020
- // Derived from the SAME inventory that creates and reconciles them, not a third hand-kept copy.
2021
- // Review found this list was the last independent one: a fourth TTL'd bucket added to `ttlBuckets`
2022
- // would be created and reconciled correctly and then die on a permissions violation here, because
2023
- // the grant never learned about it. Same defect one seam out — a bucket the code knows to maintain
2024
- // and the credential is not allowed to.
2025
- const ttlStreams = ttlBuckets(space).map(([bucket]) => `KV_${bucket}`);
2026
- // ...plus the membership KV and artifact Object Store. Both create at `max_bytes: -1` so they
2027
- // reserve nothing against the broker's `max_file_store`, and both reconcile only their own stock
2028
- // legacy caps so an EXISTING mesh releases those reservations too. The create clients never update
2029
- // an existing bucket's config, so each reconcile is a STREAM.UPDATE and needs this grant — without
2030
- // it the provisioner dies on a permissions violation on the first `cotal up` after the upgrade.
2031
- // Still CREATE/INFO/UPDATE only:
2032
- // no publish, no CONSUMER.CREATE (a push consumer's caller-chosen `deliver_subject` would export
2033
- // every artifact in the space), no DELETE/PURGE.
2034
- // ...plus the CHAT, INBOX, DLV and DM streams: `cotal history limit` sets their history limits
2035
- // (SPEC §8). STREAM.UPDATE is a whole-config write, so the grant reaches every setting of them;
2036
- // `setHistoryLimit` changes only `max_age` and `max_msgs_per_subject` and refuses a read back that is
2037
- // not canonical apart from those two. TASK stays create-only.
2038
- const streamReconcile = [...ttlStreams, `KV_${membershipBucket(space)}`, OBJ, CHAT, INBOX, DLV, DM]
2039
- .map((s) => `$JS.API.STREAM.UPDATE.${s}`);
2040
- // #404: one EXACT reserved key on each TTL bucket is the post-update enforcement canary. The
2041
- // provisioner still cannot write presence identities or lease keys; it can only write this fixed
2042
- // maintenance key, which expires through the policy the reconcile is proving.
2043
- const ttlCanaries = ttlBuckets(space).map(([bucket]) => `$KV.${bucket}.${TTL_RECONCILE_CANARY_KEY}`);
2044
- // DM/DLV/TASK durable pre-create (bind-only mailboxes): both the new-API CREATE and legacy DURABLE.CREATE
2045
- // forms (the client's consumer-add path varies by version), plus INFO (the add returns ConsumerInfo).
2046
- // NO MSG.NEXT/MSG.GET/ACK — the provisioner creates the consumer but MUST NOT read its body.
2047
- const consumerCreate = [DM, DLV, TASK].flatMap((s) => [
2048
- `$JS.API.CONSUMER.CREATE.${s}.>`,
2049
- `$JS.API.CONSUMER.DURABLE.CREATE.${s}.>`,
2050
- `$JS.API.CONSUMER.INFO.${s}.>`,
2051
- ]);
2052
- return {
2053
- pub: {
2054
- allow: [
2055
- "$JS.API.INFO",
2056
- // Current-connection identity only; the broker maps the account and requesting user.
2057
- // No subject containing another account/user and no system credential is granted.
2058
- BROKER_USER_INFO_SUBJECT,
2059
- ...streamSetup,
2060
- ...streamReconcile,
2061
- ...ttlCanaries,
2062
- ...consumerCreate,
2063
- // KV value-writes — exactly the two registries provisioning writes: the agent read-ACL registry
2064
- // (`commitAcl` at provision) and the channel registry (seed defaults at `cotal up`, channel admin).
2065
- // NO presence/members/membership/delivery writes (the agent's own key, the delivery cred, and the
2066
- // membership-rw cred own those).
2067
- `$KV.${aclBucket(space)}.>`,
2068
- `$KV.${channelBucket(space)}.>`,
2069
- // ...and READ both: commitAcl read-before-writes the ACL (`kvm.open`, direct=false ⇒ STREAM.MSG.GET);
2070
- // the channel seed read-before-writes defaults (`kvm.create`, direct=true ⇒ DIRECT.GET). Grant both
2071
- // read verbs on both buckets to cover the open/create-path variance — reads of registries it already
2072
- // writes, no escalation. Without these the read-before-write rejects and provisioning/seed throws.
2073
- `$JS.API.STREAM.MSG.GET.KV_${aclBucket(space)}`,
2074
- `$JS.API.DIRECT.GET.KV_${aclBucket(space)}.>`, // keyed get: `.>` (the key rides the subject)
2075
- `$JS.API.STREAM.MSG.GET.KV_${channelBucket(space)}`,
2076
- `$JS.API.DIRECT.GET.KV_${channelBucket(space)}.>`, // keyed get: `.>` (the key rides the subject)
2077
- // The static-manager start path: `ensureAuthorityStores` UPDATEs the records store's
2078
- // deny-flags exactly once at fresh creation (create → update → verify), and the boot
2079
- // reconciliation sweep enumerates the manager's slot rows (`keys()` → an ordered consumer)
2080
- // then reads each slot BODY (phase/uid/actor) to plan resume — the reads ride the
2081
- // stream-scoped MSG.GET residual named below (records lifecycle metadata, no secrets).
2082
- // The issued, accepted and admission stores (SPEC 13.15, 14.8) take the same one-time
2083
- // hardening UPDATE at fresh creation as the records store: their rows are create-only and
2084
- // their markers permanent, and a holder's own key row would otherwise replace them as a
2085
- // value write. One list in core names the hardened stores for every seam that creates them.
2086
- ...hardenedAuthorityStreamNames(space).map((s) => `$JS.API.STREAM.UPDATE.${s}`),
2087
- `$JS.API.CONSUMER.CREATE.KV_${recordsBucket(space)}.>`,
2088
- `$JS.API.CONSUMER.INFO.KV_${recordsBucket(space)}.>`,
2089
- `$JS.API.CONSUMER.DELETE.KV_${recordsBucket(space)}.>`,
2090
- // ...and reads the slot-mapping rows so the sweep can plan resume actions. The KV client
2091
- // reads a lazily-bound bucket via leader-served `STREAM.MSG.GET` — stream-scoped, NOT
2092
- // key-scoped (the requested key rides the PAYLOAD). NAMED RESIDUAL: for its one-shot
2093
- // lifetime the provisioner can READ (never write) any records-store row — lifecycle
2094
- // metadata, no secrets. The keyed Direct Get grant stays for direct-aware read paths.
2095
- `$JS.API.STREAM.MSG.GET.KV_${recordsBucket(space)}`,
2096
- `$JS.API.DIRECT.GET.KV_${recordsBucket(space)}.$KV.${recordsBucket(space)}.${STATIC_SLOT_PREFIX}.>`,
2097
- ],
2098
- },
2099
- // Replies only: every stream/consumer/KV-create PubAck and JS API response lands on the per-id inbox.
2100
- // NO chat/inst/dlv/ctl subscription — the provisioner never serves control nor reads any feed.
2101
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2102
- };
2103
- }
2104
- /** The ISSUER permission set (SPEC 13.15): value-writes on the evidence store (evidence, attempt,
2105
- * source index: create-only and CAS rows, keyed by generation) and on the accepted-row store
2106
- * (create-only, keyed by the client's token); `STREAM.INFO` on both, the bind-time shape check;
2107
- * the leader-served point read on the evidence store; and the ordered `keys()` walk a source
2108
- * retirement enumerates the reverse index with.
2109
- * NAMED RESIDUAL (the contract's section 8): this profile holds a write and a raw read on ONE
2110
- * stream, the pairing no peer-held profile may hold, so it is never issuable to a peer. */
2111
- function issuerPermissions(space, pr) {
2112
- const ISSUED = `KV_${issuedBucket(space)}`;
2113
- return {
2114
- pub: {
2115
- allow: [
2116
- "$JS.API.INFO",
2117
- `$KV.${issuedBucket(space)}.>`,
2118
- `$KV.${acceptedBucket(space)}.>`,
2119
- // A user-auth connection's renewal finds the accepted row its nonce names (SPEC 13.15).
2120
- `$JS.API.DIRECT.GET.KV_${acceptedBucket(space)}.$KV.${acceptedBucket(space)}.>`,
2121
- `$JS.API.STREAM.INFO.${ISSUED}`,
2122
- `$JS.API.STREAM.INFO.KV_${acceptedBucket(space)}`,
2123
- `$JS.API.STREAM.MSG.GET.${ISSUED}`,
2124
- // Source liveness: the leader-served point read of a static incarnation's issuance gate on
2125
- // the auth store (body-selected, stream-wide: the same named residual every records
2126
- // reader accepts). No auth-store WRITE of any shape.
2127
- `$JS.API.STREAM.MSG.GET.KV_${epAuthBucket(space)}`,
2128
- `$JS.API.CONSUMER.CREATE.${ISSUED}.>`,
2129
- `$JS.API.CONSUMER.INFO.${ISSUED}.>`,
2130
- `$JS.API.CONSUMER.DELETE.${ISSUED}.>`,
2131
- "$JS.FC.>",
2132
- ],
2133
- },
2134
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2135
- };
2136
- }
2137
- /** The REGISTRY READER permission set (SPEC 13.20). The evidence store's `STREAM.MSG.GET` is
2138
- * stream-scoped because the key rides the request body: NAMED RESIDUAL, the holder can read every
2139
- * recorded ceiling in the space, so this credential is never a peer's. The records reads are the
2140
- * key list and the per-key `svc` spec/status Direct Get, no stream-wide read; contract artifacts
2141
- * ride the agent's subject-scoped fetch row. No write of any shape. */
2142
- function registryReaderPermissions(space, pr) {
2143
- const ISSUED = `KV_${issuedBucket(space)}`;
2144
- const REC = recordsBucket(space);
2145
- return {
2146
- pub: {
2147
- allow: [
2148
- `$JS.API.STREAM.INFO.${ISSUED}`,
2149
- `$JS.API.STREAM.MSG.GET.${ISSUED}`,
2150
- `$JS.API.STREAM.INFO.KV_${REC}`,
2151
- `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.*.*.spec`,
2152
- `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.*.*.status`,
2153
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
2154
- ],
2155
- },
2156
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2157
- };
2158
- }
2159
- /** The RUN ADMITTER permission set (SPEC 14.8): exactly ONE run's admission record and
2160
- * revocation marker on the admission store (both create-only), plus the leader-served read the
2161
- * create-before-read and the marker's own re-read ride. No other run's keys, no other store. */
2162
- function runAdmitterPermissions(space, pr, pin) {
2163
- const bucket = admissionBucket(space);
2164
- return {
2165
- pub: {
2166
- allow: [
2167
- "$JS.API.INFO",
2168
- `$KV.${bucket}.${admissionKey(pin.endpoint, pin.runId)}`,
2169
- `$KV.${bucket}.${revocationKey(pin.endpoint, pin.runId)}`,
2170
- ...(pin.submission ? [`$KV.${bucket}.${runSubmissionKey(pin.endpoint, pin.submission.caller, pin.submission.id)}`] : []),
2171
- `$JS.API.STREAM.MSG.GET.KV_${bucket}`,
2172
- ],
2173
- },
2174
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2175
- };
2176
- }
2177
- /** The ephemeral, LIFECYCLE-PINNED §13.1 state-write permission set for the STATIC manager's
2178
- * lifecycle executor. One credential per lifecycle OPERATION (activation, terminal,
2179
- * renewal ledger append): every grant names exactly ONE incarnation's keys — the alias head,
2180
- * the uid reservation, the manager slot row, the issuance gate, and the `cred.<uid>.>` ledger
2181
- * family — so a leaked executor cred can move one incarnation's state machine and nothing else.
2182
- *
2183
- * Reads: records reads ride the keyed Direct Get form (the key is ON the subject, so the read
2184
- * grant stays key-pinned); the auth store is leader-served (`allow_direct=false`), so its reads
2185
- * are body-selected `STREAM.MSG.GET` — stream-scoped, NOT key-scoped (the requested key rides
2186
- * the PAYLOAD, which a subject grant cannot see). NAMED RESIDUAL: for its one-shot lifetime the
2187
- * executor can READ (never write) other rows in the auth store. */
2188
- function lifecycleExecutorPermissions(space, pr, pin) {
2189
- const REC = recordsBucket(space), AUTH = epAuthBucket(space);
2190
- // ALL keys DERIVED here from the pin coordinates — the slot key is `staticSlotKey(owner, alias)`,
2191
- // NOT a caller-supplied literal, so a mis-constructed pin can only ever name ONE coherent
2192
- // incarnation's rows (guard the core: the profile enforces the "one incarnation" promise, it
2193
- // does not merely assert it). The builders throw on any non-KV-safe segment.
2194
- const recordKeys = [
2195
- lifecycleHeadKey(pin.owner, pin.actor), uidReservationKey(pin.lifecycleUid), staticSlotKey(pin.owner, pin.alias),
2196
- recordSpecKey(RECORD_KINDS.lifecycle, [pin.owner, pin.actor, pin.lifecycleUid]),
2197
- ];
2198
- return {
2199
- pub: {
2200
- allow: [
2201
- "$JS.API.INFO",
2202
- // Records-store CAS writes — the value-publish carries the key on the subject, so each
2203
- // grant names exactly one of this incarnation's keys.
2204
- ...recordKeys.map((k) => `$KV.${REC}.${k}`),
2205
- // Auth-store CAS writes — this incarnation's gate + its cred-ledger family (renewals
2206
- // append rows here; the terminal's revoke CASes them).
2207
- `$KV.${AUTH}.${issuanceGateKey(pin.lifecycleUid)}`,
2208
- `$KV.${AUTH}.cred.${pin.lifecycleUid}.>`,
2209
- // Keyed Direct Get reads of the same records keys (key-pinned) for direct-aware read
2210
- // paths, PLUS the leader-served `STREAM.MSG.GET` the lazily-bound KV client actually
2211
- // uses — stream-scoped, NOT key-scoped (the requested key rides the PAYLOAD, which a
2212
- // subject grant cannot see). NAMED RESIDUAL: for its one-shot lifetime the executor can
2213
- // READ (never write) other rows in BOTH authority stores — lifecycle metadata, no
2214
- // secrets; every WRITE stays key-pinned above.
2215
- ...recordKeys.map((k) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${k}`),
2216
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
2217
- `$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
2218
- ],
2219
- },
2220
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2221
- };
2222
- }
2223
- /** The SELF-MEDIATED goal-writer profile (spawn-as-action): exactly
2224
- * {@link goalWriterGrants} for ITS endpoint — the goal bind + terminal facts, the goal-record KV
2225
- * writes, and the leader-served fencing reads — plus the connection-scoped reply inbox. Disjoint
2226
- * from the endpoint's serve credential: a serve connection carries none of these rows, so it
2227
- * is broker-denied every goal write. */
2228
- function goalWriterPermissions(space, pr, pin) {
2229
- const g = goalWriterGrants(space, pin.endpoint, pr.connId);
2230
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
2231
- }
2232
- /** The console/CLI per-session CALLER rows: RAILS-ONLY for ONE §13.6 session — pub the
2233
- * session's epoch-pinned `in` rail, sub its `out` rail plus the caller's own reply inbox, and
2234
- * NOTHING else. Deliberately NO KV, NO JetStream API, NO store: the caller drives the terminal over
2235
- * the two core-only eps subjects and never reads the session ledger, so there is no subject-blind
2236
- * store read to widen (SPEC §13.9). The endpoint+sessionId+epoch pin the EXACT pair, so a cred for
2237
- * session A authorizes nothing of session B (no wildcard). `epsSubject` validates every token, so a
2238
- * malformed coordinate refuses at the mint rather than emitting a broadened subject. */
2239
- function sessionCallerPermissions(space, pr, pin) {
2240
- if (!pin)
2241
- throw new Error('permissionsFor: "session-caller" requires opts.sessionCaller ({endpoint, sessionId, epoch}) - the ONE session\'s rails this cred may use');
2242
- return {
2243
- pub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "in")] },
2244
- sub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "out"), `_INBOX_${pr.connId}.>`] },
2245
- };
2246
- }
2247
- /** The own-DM reader rows (#4189): CONSUMER.INFO and MSG.NEXT on the principal's own
2248
- * lifecycle-keyed `dm_` durable, its `$JS.ACK` subtree, and the connection inbox. Nothing else:
2249
- * no publish of any message, no CONSUMER.CREATE (the durable is provisioned, never created), no
2250
- * `$JS.API.INFO`, no STREAM.INFO, no presence, channel, CHAT or `dlv_` row. It is exactly what
2251
- * `EndpointOptions.dmOnly` sends. */
2252
- function dmReaderPermissions(space, pr) {
2253
- if (!pr.lifecycleUid)
2254
- throw new Error('permissionsFor(dm-reader): a lifecycleUid is required - the dm_ durable name is lifecycle-keyed (SPEC 13.1)');
2255
- const DM = dmStream(space), dmD = dmDurable(pr.owner, pr.actor, assertLifecycleToken(pr.lifecycleUid));
2256
- return {
2257
- pub: { allow: [`$JS.API.CONSUMER.INFO.${DM}.${dmD}`, `$JS.API.CONSUMER.MSG.NEXT.${DM}.${dmD}`, `$JS.ACK.${DM}.${dmD}.>`] },
2258
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2259
- };
2260
- }
2261
- /** The manager's per-session SERVING rows: the EXACT mirror of
2262
- * {@link sessionCallerPermissions} with the directions swapped — sub the ONE session's epoch-pinned
2263
- * `in` rail (caller→serving), pub its `out` rail (serving→caller), plus the connection-scoped reply
2264
- * inbox, and NOTHING else. Same asymmetry §13.6 states: "the caller publishes `in` and subscribes
2265
- * `out`; the serving instance the reverse".
2266
- *
2267
- * Deliberately NO KV and NO JetStream API — not even the session ledger. The serving side drives
2268
- * bytes; the ledger is the standing `session-ledger` credential's, on a different connection. That
2269
- * separation is what lets this credential be one-shot and die with its session while the durable
2270
- * revocation authority outlives it (§13.6).
2271
- *
2272
- * This REPLACES a standing writer that held `eps.<endpoint>.*.<epoch>.{in,out}` and so could read
2273
- * and write every live session's bytes at its epoch. The pin makes a credential for session A
2274
- * authorize nothing of session B, and `epsSubject` validates every token, so a malformed
2275
- * coordinate refuses at the mint rather than emitting a broadened subject. */
2276
- function sessionServingPermissions(space, pr, pin) {
2277
- if (!pin)
2278
- throw new Error('permissionsFor: "session-serving" requires opts.sessionServing ({endpoint, sessionId, epoch}) - the ONE session\'s rails this cred may serve');
2279
- return {
2280
- pub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "out")] },
2281
- sub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "in"), `_INBOX_${pr.connId}.>`] },
2282
- };
2283
- }
2284
- /** The manager's SESSION-LEDGER rows: the DEDICATED sessions-bucket rows and nothing
2285
- * else — no session rail of any shape. Needs no pin: the grant carries no endpoint, epoch, or
2286
- * session component, because §13.6's durable revocation authority is per-space, not per-session
2287
- * (it must still be able to resolve and revoke a row after the endpoint that served it is gone).
2288
- * {@link sessionLedgerGrants} carries the row rationale, the §13.9 subject-blindness confinement,
2289
- * and the named `session.*` breadth residual. */
2290
- function sessionLedgerPermissions(space, pr) {
2291
- const g = sessionLedgerGrants(space, pr.connId);
2292
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
2293
- }
2294
- /** The ephemeral, ENDPOINT-INSTANCE-PINNED endpoint-serve executor permission set:
2295
- * the manager mints this per registration/serve-mint op and drives the endpoint
2296
- * registration barrier's `epgate` CAS + the mint fence's `epcred` stage/revoke THROUGH it — never
2297
- * its standing seed/supervisor connection. Every
2298
- * WRITE is key-pinned to exactly ONE (endpoint, instanceId): the gate `epgate.<ep>.<iid>`, its
2299
- * serving ledger family `epcred.<ep>.<iid>.>`, and the registration's two records keys (the
2300
- * instance's `svc` spec + the endpoint's governance head — `registerServiceInstance` drives the
2301
- * slot-take/promote over this same connection). A leaked/mis-constructed executor can move exactly
2302
- * one endpoint instance's serve state and nothing else. The auth store is `allow_direct=false`, so
2303
- * reads are leader-served `STREAM.MSG.GET` (stream-scoped, NOT key-scoped — the key rides the
2304
- * payload); enumeration of the epcred family rides an ordered `keys()` consumer. NAMED RESIDUAL:
2305
- * for its one-shot lifetime the executor can READ (never write) other auth rows — endpoint/
2306
- * credential metadata, no bearer bytes; every WRITE stays key-pinned. */
2307
- function endpointServeExecutorPermissions(space, pr, pin) {
2308
- const AUTH = epAuthBucket(space), REC = recordsBucket(space);
2309
- // DERIVED from (endpoint, instanceId) via the core builders — never a caller literal.
2310
- const gateKey = epgateKey(pin.endpoint, pin.instanceId);
2311
- const credPrefix = epcredFamilyPrefix(pin.endpoint, pin.instanceId);
2312
- const repairKey = eprepairKey(pin.endpoint, pin.instanceId);
2313
- // The registration writes this ONE instance's spec key plus the endpoint's governance head
2314
- // (`registerServiceInstance` PHASE 1/3b: the slot-take + promote ride the SAME executor), and this
2315
- // instance's own svc STATUS key (the manager writes its CONVERGED `ready` status so it
2316
- // is a §13.5 scatter member — `freezeExpectedSet` requires a status caught up to the current
2317
- // registration; the write is epoch-fenced by `writeServiceStatus`).
2318
- const recordKeys = [
2319
- recordSpecKey(RECORD_KINDS.svc, [pin.endpoint, assertLifecycleToken(pin.instanceId, "instanceId")]),
2320
- recordStatusKey(RECORD_KINDS.svc, [pin.endpoint, assertLifecycleToken(pin.instanceId, "instanceId")]),
2321
- recordAtomicKey(GOVERN_HEAD, [pin.endpoint]),
2322
- ];
2323
- return {
2324
- pub: {
2325
- allow: [
2326
- "$JS.API.INFO",
2327
- // The key-pinned WRITE grants: the gate (provision create + barrier freeze/reopen CAS),
2328
- // the serving ledger family (mint-fence stage + barrier revoke), and the registration's
2329
- // two records-store keys (spec CAS + governance slot/promote). The value-publish carries
2330
- // the key on the subject, so each grant names exactly this instance's keys.
2331
- `$KV.${AUTH}.${gateKey}`,
2332
- `$KV.${AUTH}.${repairKey}`,
2333
- `$KV.${AUTH}.${credPrefix}.>`,
2334
- ...recordKeys.map((k) => `$KV.${REC}.${k}`),
2335
- // §13.7 contract-artifact publication: the registration publishes the
2336
- // endpoint's cluster document, closure manifests, and schema roots to the EPC store so
2337
- // callers can fetch-verify-compile the registered digests. A digest subject is a SINGLE
2338
- // hex token (`epc.<64hex>`), so the grant is the single-token `epc.*` form (matching
2339
- // `contractPublisherGrants`), never the multi-token `epc.>`. Digest subjects cannot be
2340
- // key-pinned pre-mint; the store's SHAPE is the defense (ensureContractStore): a digest
2341
- // subject holds exactly one broker-immutable message (max_msgs_per_subject:1 +
2342
- // discard-new-per-subject REJECTS a second publish regardless of the create-only header, so
2343
- // a grant-holder CANNOT append a shadow over a published artifact), deny_delete/deny_purge
2344
- // keep that message, and content addressing (verify-on-read, create-only-winner fallback)
2345
- // makes a wrong-subject write unservable. NAMED RESIDUAL: for its one-shot lifetime the
2346
- // executor can publish NEW digest-addressed artifacts at previously-unused subjects (a
2347
- // bounded storage flood; unreferenced artifacts carry no authority) — it can NOT overwrite,
2348
- // shadow, or replace an existing one.
2349
- `${spacePrefix(space)}.epc.*`,
2350
- // The lost-CAS verify-read `publishContractArtifact` runs when a re-publish (every re-up /
2351
- // restart against an existing store) loses the create-only CAS: it fetches the recorded
2352
- // artifact to confirm the idempotent no-op. BOTH Direct Get forms — the subject-scoped
2353
- // `last_by_subj` (the fast path) and the bare stream form (the create-only-winner
2354
- // `next_by_subj` fallback) — so the publish path never dies on a broker denial regardless
2355
- // of stream config. Without this the manager exits on its SECOND boot (the tester's
2356
- // upgrade-path regression). Reads public content-addressed artifacts only.
2357
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
2358
- `$JS.API.DIRECT.GET.${epcStreamName(space)}`,
2359
- // Leader-served reads (the auth store is allow_direct=false): stream-scoped MSG.GET (the
2360
- // barrier/fence read the gate + each epcred row), plus the ordered consumer the epcred
2361
- // `keys()` enumeration binds. The records store IS direct-servable, so its reads add the
2362
- // key-pinned DIRECT.GET forms beside the leader-served fallback. NAMED RESIDUAL: reads
2363
- // any row in both stores for its one-shot lifetime (metadata, no bearer bytes).
2364
- `$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
2365
- `$JS.API.CONSUMER.CREATE.KV_${AUTH}.>`,
2366
- `$JS.API.CONSUMER.INFO.KV_${AUTH}.>`,
2367
- `$JS.API.CONSUMER.DELETE.KV_${AUTH}.>`,
2368
- // Ordered value scans acknowledge flow control only for this authorized auth stream.
2369
- `$JS.FC.KV_${AUTH}.>`,
2370
- ...recordKeys.map((k) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${k}`),
2371
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
2372
- ],
2373
- },
2374
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2375
- };
2376
- }
2377
- /** The ephemeral, TARGET-PINNED DEPROVISIONER permission set — the teardown counterpart
2378
- * to {@link provisionerPermissions}, minted per departed agent inside the manager's `deprovision` tail
2379
- * (`withProvisioner`-style: a fresh scoped cred per teardown is cheap). It deletes exactly the
2380
- * dev/static principal footprint the provisioner created for ONE agent: that agent's two bind-only
2381
- * durables (`dm_local-<actor>`, `dlv_local-<actor>`) and its read-ACL row — pinned BY NAME to the target
2382
- * actor under {@link DEV_OWNER}, so a leaked deprovisioner cred can tear down that one already-dead
2383
- * agent and NOTHING else.
2384
- *
2385
- * Deliberately NOT granted (least-privilege / correctness): the role-SHARED `svc_<role>` TASK durable
2386
- * (one consumer for ALL agents of a role — deleting it on one agent's exit would break its siblings; it
2387
- * lives until space teardown), any peer's `dm_`/`dlv_`/ACL (the grants are target-name-pinned, never
2388
- * `.>`), any MSG.NEXT/MSG.GET/ACK (it deletes mailboxes, never reads a body), and any STREAM
2389
- * DELETE/PURGE (it removes per-agent consumers, never a stream). The `chathist_<id>` history consumers
2390
- * need no grant here — they are ephemeral (`mem_storage`, 30s inactive threshold) and agent-deleted
2391
- * after each read, so they self-clean on the agent's disconnect.
2392
- *
2393
- * Blast radius of a leaked cred (minted for target T): it can delete T's `dm_local-<T>`/`dlv_local-<T>`
2394
- * durables + purge T's ACL row — a denial-of-DELIVERY for T (broken DM/DLV bind + the reader DEFERs on
2395
- * the absent ACL) if fired while T is still alive. It CANNOT read T's bodies, impersonate T, reach any peer, or
2396
- * delete a stream — and it is ephemeral (one per-exit teardown, minted then dropped). Contained and
2397
- * recoverable (re-provision T). */
2398
- function deprovisionerPermissions(space, pr, deprovisionTarget) {
2399
- const DM = dmStream(space), DLV = dlvStream(space);
2400
- const t = deprovisionTargetPrincipal(deprovisionTarget);
2401
- const target = principalKey(t.owner, t.actor);
2402
- return {
2403
- pub: {
2404
- allow: [
2405
- "$JS.API.INFO", // jetstreamManager bootstrap
2406
- // Delete the target LIFECYCLE's two bind-only durables BY EXACT NAME — no `.>`, no cross-agent
2407
- // reach, and no reach into a same-alias successor: its names carry a different uid, so a
2408
- // replayed teardown is broker-DENIED there (SPEC 13.1 / Appendix "deprovisioner").
2409
- `$JS.API.CONSUMER.DELETE.${DM}.${dmDurable(t.owner, t.actor, t.lifecycleUid)}`,
2410
- `$JS.API.CONSUMER.DELETE.${DLV}.${dlvDurable(t.owner, t.actor, t.lifecycleUid)}`,
2411
- `$JS.API.CONSUMER.INFO.${DM}.${dmDurable(t.owner, t.actor, t.lifecycleUid)}`,
2412
- `$JS.API.CONSUMER.INFO.${DLV}.${dlvDurable(t.owner, t.actor, t.lifecycleUid)}`,
2413
- // Purge the target lifecycle's read-ACL row (own-target exact key only — the reader then treats
2414
- // it as an unknown owner). `kvm.open` binds the pre-created bucket; the purge rides
2415
- // `$KV.<aclBucket>.<key>`.
2416
- `$JS.API.STREAM.INFO.KV_${aclBucket(space)}`,
2417
- `$JS.API.DIRECT.GET.KV_${aclBucket(space)}.$KV.${aclBucket(space)}.${aclKey(target.key, t.lifecycleUid)}`,
2418
- `$KV.${aclBucket(space)}.${aclKey(target.key, t.lifecycleUid)}`,
2419
- // Purge the target lifecycle's durable membership rows, one exact key per named concrete
2420
- // channel or family (a family's `>` is `=` in the key, so no grant here is a wildcard). The key
2421
- // embeds the uid, so a successor's row is unreachable by name.
2422
- ...(t.memberChannels.length > 0 ? [`$JS.API.STREAM.INFO.KV_${membersBucket(space)}`] : []),
2423
- ...t.memberChannels.map((ch) => `$JS.API.DIRECT.GET.KV_${membersBucket(space)}.$KV.${membersBucket(space)}.${memberKey(ch, target.key, t.lifecycleUid)}`),
2424
- ...t.memberChannels.map((ch) => `$KV.${membersBucket(space)}.${memberKey(ch, target.key, t.lifecycleUid)}`),
2425
- ],
2426
- },
2427
- // Replies only: the CONSUMER.DELETE PubAcks + KV purge ack land on the per-connection inbox. NO chat/DM/ctl
2428
- // subscription — the deprovisioner serves nothing and reads no feed.
2429
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
2430
- };
2431
- }
2432
- /** The scoped `delivery` daemon permission set (server-side Plane-3 infra; NEVER allow-all, never
2433
- * minted for an agent — `cotal mint` excludes it, like `manager`). Least-privilege: exactly what the
2434
- * fan-out writer + trusted reader + activation catch-up + membership/ACL reads + members-KV writes +
2435
- * the lease + the `ctl.delivery` control service touch. `sub.allow` is the per-identity inbox (all JS
2436
- * pull delivery / KV-watch / request replies land there) PLUS the `ctl.delivery` control subtree it
2437
- * serves; ALL stream/KV reads ride the JS API (publishes), so there is NO native `chat`/`dinbox`/`dlv`
2438
- * subscription — a leaked cred can't natively sniff the mixed pre-auth store. Honest blast radius
2439
- * (delivery-daemon.mdx): it can write any owner's `dlv` (the post-auth store agents trust); the future
2440
- * fan-out/reader cred split bounds that. */
2441
- function deliveryPermissions(space, pr) {
2442
- const p = spacePrefix(space);
2443
- const CHAT = chatStream(space), INBOX = inboxStream(space), DLV = dlvStream(space);
2444
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
2445
- const MKV = `KV_${membersBucket(space)}`, AKV = `KV_${aclBucket(space)}`, DKV = `KV_${deliveryBucket(space)}`;
2446
- const TASK = taskStream(space), AKVR = `KV_${anycastBucket(space)}`;
2447
- const kvRead = (bucket) => [
2448
- `$JS.API.STREAM.INFO.${bucket}`,
2449
- `$JS.API.STREAM.MSG.GET.${bucket}`, // kv.get
2450
- `$JS.API.CONSUMER.CREATE.${bucket}.>`, // kv.watch ordered consumer
2451
- `$JS.API.CONSUMER.INFO.${bucket}.>`,
2452
- `$JS.API.CONSUMER.DELETE.${bucket}.>`,
2453
- ];
2454
- const pub = [
2455
- "$JS.API.INFO",
2456
- `$JS.API.STREAM.INFO.${CHAT}`, `$JS.API.STREAM.INFO.${INBOX}`, `$JS.API.STREAM.INFO.${DLV}`,
2457
- // Fan-out durable + activation-catch-up ephemerals live on CHAT — the daemon legitimately reads ALL
2458
- // chat (the fan-out consumes the whole stream), so a stream-wide CHAT consumer grant is no
2459
- // escalation. The catch-up ephemeral names (`cu_<owner>_<gen>`) are dynamic, so they can't be
2460
- // name-pinned; CHAT-wide is correct here.
2461
- //
2462
- // BOTH forms, and the bare one is not redundant: a create carrying `filter_subjects` cannot encode
2463
- // its filter in the subject, so the client publishes to the BARE `…CREATE.<CHAT>` while a named
2464
- // consumer goes to the `.>` form. The mediated history read (`readHistory`) builds exactly that
2465
- // multi-filter ephemeral, and with only the `.>` grant it fails with a Permissions Violation on the
2466
- // bare subject — measured, not predicted. The observer profile already carries both for the same
2467
- // reason. Grants the daemon nothing new in substance: it may already create any named consumer on
2468
- // this stream and already reads all of it.
2469
- `$JS.API.CONSUMER.CREATE.${CHAT}`,
2470
- `$JS.API.CONSUMER.CREATE.${CHAT}.>`,
2471
- `$JS.API.CONSUMER.DURABLE.CREATE.${CHAT}.>`,
2472
- `$JS.API.CONSUMER.INFO.${CHAT}.>`,
2473
- `$JS.API.CONSUMER.MSG.NEXT.${CHAT}.>`,
2474
- `$JS.API.CONSUMER.DELETE.${CHAT}.>`,
2475
- `$JS.ACK.${CHAT}.>`,
2476
- // Trusted reader on INBOX — NAME-PINNED to the single `reader` durable (the meaningful confinement:
2477
- // no arbitrary INBOX consumer create against the mixed pre-auth store).
2478
- `$JS.API.CONSUMER.CREATE.${INBOX}.${INBOX_READER_DURABLE}.>`,
2479
- `$JS.API.CONSUMER.DURABLE.CREATE.${INBOX}.${INBOX_READER_DURABLE}`,
2480
- `$JS.API.CONSUMER.INFO.${INBOX}.${INBOX_READER_DURABLE}`,
2481
- `$JS.API.CONSUMER.MSG.NEXT.${INBOX}.${INBOX_READER_DURABLE}`,
2482
- `$JS.API.CONSUMER.DELETE.${INBOX}.${INBOX_READER_DURABLE}`,
2483
- `$JS.ACK.${INBOX}.${INBOX_READER_DURABLE}.>`,
2484
- // The reader removes an entry addressed to a retired lifecycle (its ACL row is tombstoned), so the
2485
- // store does not keep what no reader can ever deliver. Nothing new in substance: the reader can
2486
- // already ack any INBOX entry away.
2487
- `$JS.API.STREAM.MSG.DELETE.${INBOX}`,
2488
- "$JS.FC.>", // ordered-consumer flow control
2489
- // Reads: presence (@mention resolve) + channel registry (delivery class) + members + ACL (re-auth).
2490
- ...kvRead(PKV), ...kvRead(CHKV), ...kvRead(MKV), ...kvRead(AKV),
2491
- // Members-KV WRITE — the daemon is the durable-membership authority (join/leave/activate/catch-up).
2492
- `$KV.${membersBucket(space)}.>`,
2493
- // Delivery lease/readiness KV: read the bucket (renew CAS) + write ONLY lease keys. The
2494
- // CONSUMER.* rows are kv.watch's ordered consumer for the lease-loss watch (#1596) — the same
2495
- // read axis the other kvRead buckets carry, on the bucket this cred already reads point-wise:
2496
- // a watch is a READ of the row's changes, never a write. CONSUMER.DELETE rides with it for the
2497
- // same reason it does on every watched bucket: an ordered consumer rebuilds by deleting its
2498
- // predecessor, and a refused delete strands consumers on every rebuild (measured on the
2499
- // presence bucket; the comment there carries the full story).
2500
- `$JS.API.STREAM.INFO.${DKV}`, `$JS.API.STREAM.MSG.GET.${DKV}`,
2501
- `$JS.API.CONSUMER.CREATE.${DKV}.>`,
2502
- `$JS.API.CONSUMER.INFO.${DKV}.>`,
2503
- `$JS.API.CONSUMER.DELETE.${DKV}.>`,
2504
- `$KV.${deliveryBucket(space)}.lease.*`,
2505
- // The timer writer (SPEC 13.2): the daemon hosts the pump that turns `.schedule` requests into
2506
- // the authoritative `.armed` publishes — without it no workflow pause on the space ever
2507
- // expires. Its consumer rows are the shared timer-writer grant set; both create forms for the
2508
- // same reason CHAT carries both (the client picks by whether the create embeds a filter). The
2509
- // arm itself needs the fence's two leader reads — the `.armed` head on EPT and the checkpoint
2510
- // status on the records KV — and exactly ONE publish: the `.armed` subject. Never `.fire`
2511
- // (the broker's own schedule delivery) and never `.schedule` (it consumes those).
2512
- ...timerWriterGrants(space),
2513
- `$JS.API.CONSUMER.DURABLE.CREATE.${eptReqStreamName(space)}.${timerWriterDurable(space)}`,
2514
- `$JS.API.STREAM.INFO.${eptReqStreamName(space)}`,
2515
- `$JS.API.STREAM.INFO.${eptStreamName(space)}`,
2516
- `$JS.API.STREAM.MSG.GET.${eptStreamName(space)}`,
2517
- `$JS.API.STREAM.INFO.KV_${recordsBucket(space)}`,
2518
- `$JS.API.STREAM.MSG.GET.KV_${recordsBucket(space)}`,
2519
- `${p}.ept.*.*.*.*.armed`,
2520
- // Plane-3 data writes: dinbox (fan-out target) + dlv (post-auth handoff) for ANY lifecycle — the
2521
- // identity slots widen to `.*.*.*` (owner+actor+lifecycleUid: dinbox/dlv are per-LIFECYCLE now,
2522
- // SPEC 13.1; NATS subject arity is exact, so the old two-token form is broker-denied on every
2523
- // three-token write).
2524
- `${p}.dinbox.*.*.*`, `${p}.dlv.*.*.*`,
2525
- // ctl.delivery control REPLIES ONLY (requests arrive on the sub below; the daemon only ever
2526
- // m.respond()s to a requester's reply subject `ctl.delivery.<owner>.<actor>.reply.<n>`). Scoped to
2527
- // the `.reply.>` leaf so the daemon can't publish to the request subjects themselves — tighter than a
2528
- // blanket `ctl.delivery.>` (fact-check precision, review panel). The caller slots widened to `.*.*`.
2529
- `${p}.ctl.delivery.*.*.reply.>`,
2530
- // The privileged delivery-admin rail: same replies-only shape. Requests reach the
2531
- // daemon on the sub below; only the supervisor cred can PUBLISH them (nats-server is the boundary).
2532
- `${p}.ctl.delivery-admin.*.*.reply.>`,
2533
- // LIVENESS REPLIES for the DELIVERY plane (#1577) — same replies-only shape as the two control
2534
- // rails above. The daemon is the only process that can grade its own responder honestly: it
2535
- // knows its own incarnation, so a predecessor's `ready:true` corpse in the lease classifies as
2536
- // stale rather than as its own health. Bounded to the `.reply.` leaf, so it cannot publish to
2537
- // the request subjects and forge a probe from a peer.
2538
- livenessReplyGrant(space, "delivery"),
2539
- // Anycast request status (SPEC §8.1). The daemon reads a request at the seq a take, status or
2540
- // cancel names, and deletes one its sender cancelled while it waited: a read of every request
2541
- // body in the space and a delete of any of them, both bounded by the take record. It owns the
2542
- // records bucket, creating it on a mesh that predates it, and lists it for the maintenance pass.
2543
- // It DMs a request's sender from its own principal only, and answers takes on their bounded
2544
- // reply leaf.
2545
- `$JS.API.STREAM.INFO.${TASK}`,
2546
- `$JS.API.STREAM.MSG.GET.${TASK}`,
2547
- `$JS.API.STREAM.MSG.DELETE.${TASK}`,
2548
- `$JS.API.STREAM.CREATE.${AKVR}`,
2549
- ...kvRead(AKVR),
2550
- `$JS.API.DIRECT.GET.${AKVR}.>`,
2551
- `$KV.${anycastBucket(space)}.>`,
2552
- unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a>: a notice to a sender, as itself
2553
- takeReplyGrant(space),
2554
- ];
2555
- const sub = [
2556
- `_INBOX_${pr.connId}.>`,
2557
- takeServeFilter(space), // serve anycast takes (queue-grouped; role + owner+actor caller slots)
2558
- `${p}.ctl.delivery.*.*`, // serve the delivery control service (queue-grouped; owner+actor caller slots)
2559
- `${p}.ctl.delivery-admin.*.*`, // serve the privileged admin rail (reloadCreds; eviction executor next)
2560
- // Serve the delivery plane's liveness probe (#1577), queue-grouped. Presence-only: the handler
2561
- // reduces the lease row to one enum before replying, so this subscription lets the daemon ANSWER
2562
- // a peer without any peer gaining a read of the lease.
2563
- livenessServeFilter(space, "delivery"),
2564
- ];
2565
- return { pub: { allow: pub }, sub: { allow: sub } };
2566
- }
2567
- /** The scoped DATA-account `membership-rw` permission set (the graph feed's conn B; NEVER allow-all,
2568
- * never minted for an agent — `cotal mint` excludes it, like `manager`/`delivery`). Least-privilege:
2569
- * READ the members registry (the durable arm of the merge) + READ/WRITE the one derived membership
2570
- * bucket, and nothing else. It holds NO chat/DM/anycast/ctl grant and never touches `$SYS` (account
2571
- * isolation keeps the system-account CONNZ read on the SEPARATE conn-A cred). A leaked conn-B cred can
2572
- * read durable-membership records and forge the feed — bounded to "dashboard integrity" by the
2573
- * display-only invariant; it reads no message bodies and admins nothing. */
2574
- function membershipRwPermissions(space, pr) {
2575
- const MKV = `KV_${membersBucket(space)}`; // durable arm — read
2576
- const MEMKV = `KV_${membershipBucket(space)}`; // derived feed — read (diff/prune) + write
2577
- const kvRead = (bucket) => [
2578
- `$JS.API.STREAM.INFO.${bucket}`,
2579
- `$JS.API.STREAM.MSG.GET.${bucket}`, // kv.get
2580
- `$JS.API.CONSUMER.CREATE.${bucket}.>`, // kv.keys()/kv.watch ordered consumer
2581
- `$JS.API.CONSUMER.INFO.${bucket}.>`,
2582
- `$JS.API.CONSUMER.DELETE.${bucket}.>`,
2583
- ];
2584
- const pub = [
2585
- "$JS.API.INFO",
2586
- ...kvRead(MKV),
2587
- ...kvRead(MEMKV),
2588
- `$KV.${membershipBucket(space)}.>`, // write derived feed (kv.put + kv.delete)
2589
- "$JS.FC.>", // ordered-consumer flow control
2590
- ];
2591
- return { pub: { allow: pub }, sub: { allow: [`_INBOX_${pr.connId}.>`] } };
2592
- }
2593
- /** The scoped SYSTEM-account `membership-observer` permission set (the graph feed's conn A). An EXPLICIT
2594
- * block is MANDATORY: a system-account user with NO permissions block defaults to ALLOW-ALL = full
2595
- * `$SYS` = broker admin (verified — pre-flight spike + docs). Least-privilege allowlist:
2596
- * - **pub:** the account-scoped CONNZ request subject ONLY (not server-wide `PING.CONNZ`, not
2597
- * `REQ.SERVER.*`/`REQ.CLAIMS.*`).
2598
- * - **sub:** the scoped reply inbox (`<MEMBERSHIP_INBOX_PREFIX>.>`) + this ONE account's
2599
- * CONNECT/DISCONNECT events (re-poll triggers) — never `$SYS.ACCOUNT.*.…` (cross-tenant) nor
2600
- * `$SYS.ACCOUNT.<id>.>` (pulls in SUBSZ/JSZ/purge).
2601
- * No `$SYS.>` deny that would shadow the allows (deny-beats-allow). A leaked conn-A cred enumerates THIS
2602
- * account's connections (silent readers + nkeys) and can forge the feed; it reads no bodies, touches no
2603
- * other account, and admins no server. */
2604
- function membershipObserverPermissions(accountId) {
2605
- return {
2606
- pub: { allow: [connzRequestSubject(accountId)] },
2607
- sub: {
2608
- allow: [
2609
- `${MEMBERSHIP_INBOX_PREFIX}.>`,
2610
- accountConnectSubject(accountId),
2611
- accountDisconnectSubject(accountId),
2612
- ],
2613
- },
2614
- };
2615
- }
2616
- /** Mint the scoped `membership-observer` creds — a SYSTEM-account user (conn A of the graph feed),
2617
- * signed with the in-memory `auth.sys.signingSeed` from a fresh {@link createSpaceAuth}. THROWS if that
2618
- * seed is absent (a re-`up` of an already-provisioned space, whose `$SYS` seed was discarded at its
2619
- * original `up`): the observer can only be minted at the (re-)provision that creates the account — a
2620
- * documented migration property, not a silent no-op. The CONNZ/event subjects pin the DATA account id
2621
- * (`auth.account.pub`). Mirrors {@link mintCreds} but issues into the system account. */
2622
- export async function mintMembershipObserverCreds(auth, identity, opts = {}) {
2623
- if (!auth.sys.signingSeed)
2624
- 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.");
2625
- const signer = nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed));
2626
- const perms = membershipObserverPermissions(auth.account.pub);
2627
- // Bounded exp: the observer is `rotation-renewed` — it carries the matrix's default
2628
- // lifetime so a copied cred becomes broker-dead, but there is NO online renewal (the $SYS seed is
2629
- // gone after `up`); renewal is a coordinated system-account rotation + restart.
2630
- const validDates = userValidDates("membership-observer", opts);
2631
- const userJwt = await encodeUser("membership-observer", fromPublic(identity.id), fromPublic(auth.sys.pub), perms, { signer, ...validDates });
2632
- const creds = fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed)));
2633
- return new TextDecoder().decode(creds);
2634
- }
2635
- /** Host-only read-only census credential. A registered system signer is required; no fallback
2636
- * to a broader observer or eviction credential. Reissuing with a retained registered signer
2637
- * needs no broker restart. The helper does not discover or persist that signer.
2638
- */
2639
- export async function mintAccountCensusCreds(auth, identity, opts = {}) {
2640
- const prefix = accountCensusInboxPrefix(auth.account.pub);
2641
- if (!auth.sys.signingSeed)
2642
- throw new Error("account census requires the registered system-account signer");
2643
- const { exp } = userValidDates("account-census", opts), now = Math.floor(Date.now() / 1000);
2644
- if (exp === undefined || !Number.isSafeInteger(exp) || exp <= now || exp > now + FIVE_MINUTES)
2645
- throw new Error("account census requires a bounded future credential expiry");
2646
- const user = fromSeed(new TextEncoder().encode(identity.seed));
2647
- if (!isUserNkey(identity.id) || user.getPublicKey() !== identity.id)
2648
- throw new Error("account census identity does not match its user key");
2649
- const jwt = await encodeUser("account-census", fromPublic(identity.id), fromPublic(auth.sys.pub), {
2650
- pub: { allow: [connzRequestSubject(auth.account.pub)] }, sub: { allow: [`${prefix}.>`] },
2651
- }, { signer: nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed)), exp });
2652
- if (exp <= Math.floor(Date.now() / 1000))
2653
- throw new Error("account census credential expired before release");
2654
- return new TextDecoder().decode(fmtCreds(jwt, user));
2655
- }
2656
- /** The KICK-ONLY connection-evictor permission set — a SYSTEM-account user that can do
2657
- * exactly ONE thing: `$SYS.REQ.SERVER.*.KICK` (disconnect a live client by cid). It CANNOT read
2658
- * CONNZ (discovery stays on the separate observer cred — never one broad sys user that both
2659
- * enumerates and kills), touch any other `$SYS` verb, or reach another account's data. A leaked
2660
- * evictor cred can DoS live connections on this broker (KICK is not account-scoped — the honest
2661
- * blast radius), which is why it is a HIGH-POWER standing credential: minted only at `up`,
2662
- * rate-limited + audited by its one caller (the delivery daemon), and its cid/server-id inputs come
2663
- * only from the observer's own CONNZ scan, never a user-facing API. Wildcard `*` over server id
2664
- * because a cluster's server ids aren't known at mint time; the scan pins the exact id per KICK. */
2665
- function connectionEvictorPermissions() {
2666
- return {
2667
- pub: { allow: ["$SYS.REQ.SERVER.*.KICK"] },
2668
- // Request/reply KICK replies land on the client's default inbox; no other subscription — it
2669
- // serves nothing and reads no feed.
2670
- sub: { allow: ["_INBOX.>"] },
2671
- };
2672
- }
2673
- /** Mint the scoped `connection-evictor` creds — the kick-only SYSTEM-account user for live
2674
- * eviction. Same mint-only-at-provision property as the observer (the $SYS seed is in-memory
2675
- * only), same fail-loud when it's absent. Paired with the observer at `up`. */
2676
- export async function mintConnectionEvictorCreds(auth, identity, opts = {}) {
2677
- if (!auth.sys.signingSeed)
2678
- 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.");
2679
- const signer = nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed));
2680
- // Bounded exp: `rotation-renewed`, same posture as the observer above.
2681
- const validDates = userValidDates("connection-evictor", opts);
2682
- const userJwt = await encodeUser("connection-evictor", fromPublic(identity.id), fromPublic(auth.sys.pub), connectionEvictorPermissions(), { signer, ...validDates });
2683
- const creds = fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed)));
2684
- return new TextDecoder().decode(creds);
2685
- }
2686
- /**
2687
- * Render the config for an OPEN (no-auth) broker.
2688
- *
2689
- * This exists so that no path reaches a listener without naming its transport. Open mode used to
2690
- * start nats-server from bare CLI flags (`-js -sd … -p … -a …`) and never called `serverConfig` at
2691
- * all, which meant the required `transport` union protected the auth path and was silent on the
2692
- * open one: an operator could pass a cert and key, watch `up` print its normal banner, and get a
2693
- * cleartext listener. That is the silent downgrade this feature exists to prevent, reachable by
2694
- * someone who did everything right — so open mode renders a config too.
2695
- *
2696
- * It deliberately does NOT reuse `serverConfig`: that renders the operator, system account and
2697
- * MEMORY resolver, none of which a no-auth broker should carry. What the two share is the thing
2698
- * that matters — a REQUIRED transport, so the choice cannot be omitted on either path.
2699
- *
2700
- * IMPORTANT, and it must be said wherever open-mode TLS is surfaced to an operator: TLS ON AN
2701
- * OPEN MESH GIVES CONFIDENTIALITY, NOT AUTHENTICATION. It hides traffic from a passive observer.
2702
- * It does not verify who is connecting, because an open broker has no credentials to check — so
2703
- * anyone who can reach the port still gets in, encrypted. It is a legitimate configuration for a
2704
- * mesh crossing a network nobody controls, and it is NOT "secure" in the sense a reader will
2705
- * assume from seeing `cotals://`. Describe it as the caveat it is rather than as a feature.
2706
- */
2707
- export function openServerConfig(opts) {
2708
- const port = opts.port ?? 4222;
2709
- const host = opts.host ?? "127.0.0.1";
2710
- const logBlock = renderLogBlock("openServerConfig", opts);
2711
- if (opts.maxPayload !== undefined && (!Number.isSafeInteger(opts.maxPayload) || opts.maxPayload <= 0))
2712
- throw new Error("openServerConfig: maxPayload must be a positive safe integer of bytes");
2713
- return `# Generated by \`cotal up\` - do not edit by hand.
2714
- host: ${host}
2715
- port: ${port}
2716
- max_control_line: ${MAX_CONTROL_LINE_BYTES}
2717
- ${opts.maxPayload !== undefined ? `max_payload: ${opts.maxPayload}\n` : ""}${logBlock}${renderTlsBlock(opts.transport)}${renderJetStreamBlock("openServerConfig", opts.storeDir, opts.maxFileStore, opts.brokerVersion)}
2718
- `;
2719
- }
2720
- /** Render native nats-server file logging and rotation directives when requested. */
2721
- function renderLogBlock(renderer, opts) {
2722
- if (opts.logFile === undefined && (opts.logfileSizeLimit !== undefined || opts.logfileMaxNum !== undefined))
2723
- throw new Error(`${renderer}: logfileSizeLimit and logfileMaxNum require logFile`);
2724
- const lines = [];
2725
- if (opts.logFile !== undefined) {
2726
- if (!opts.logFile.trim() || /[\u0000-\u001f\u007f]/u.test(opts.logFile))
2727
- throw new Error(`${renderer}: logFile must be a non-empty path without control characters`);
2728
- lines.push(`log_file: ${JSON.stringify(opts.logFile)}`);
2729
- }
2730
- if (opts.logfileSizeLimit !== undefined) {
2731
- if (!Number.isSafeInteger(opts.logfileSizeLimit) || opts.logfileSizeLimit <= 0)
2732
- throw new Error(`${renderer}: logfileSizeLimit must be a positive integer number of bytes`);
2733
- lines.push(`logfile_size_limit: ${opts.logfileSizeLimit}`);
2734
- }
2735
- if (opts.logfileMaxNum !== undefined) {
2736
- if (!Number.isSafeInteger(opts.logfileMaxNum) || opts.logfileMaxNum <= 0)
2737
- throw new Error(`${renderer}: logfileMaxNum must be a positive integer file count`);
2738
- lines.push(`logfile_max_num: ${opts.logfileMaxNum}`);
2739
- }
2740
- return lines.length ? `${lines.join("\n")}\n` : "";
2741
- }
2742
- /** The exact `jetstream{}` block both broker renderers write for this store and cap, for a caller
2743
- * that must find or replace it in a rendered configuration. */
2744
- export function brokerJetStreamBlock(storeDir, maxFileStore, brokerVersion) {
2745
- return renderJetStreamBlock("brokerJetStreamBlock", storeDir, maxFileStore, brokerVersion);
2746
- }
2747
- /** The shared JetStream block. A set file cap must be positive; brokers 2.15 and later
2748
- * also need an explicit unlimited default consumer count. */
2749
- function renderJetStreamBlock(renderer, storeDir, maxFileStore, brokerVersion) {
2750
- const version = brokerVersion === undefined ? undefined : /^(\d+)\.(\d+)\.\d+/.exec(brokerVersion);
2751
- if (brokerVersion !== undefined && !version)
2752
- throw new Error(`${renderer}: invalid brokerVersion ${JSON.stringify(brokerVersion)}`);
2753
- const limits = version && (Number(version[1]) > 2 || Number(version[1]) === 2 && Number(version[2]) >= 15)
2754
- ? ", limits { default_max_consumers: -1 }" : "";
2755
- if (maxFileStore === undefined)
2756
- return `jetstream { store_dir: ${JSON.stringify(storeDir)}${limits} }`;
2757
- if (!Number.isSafeInteger(maxFileStore) || maxFileStore <= 0)
2758
- throw new Error(`${renderer}: maxFileStore must be a positive integer number of bytes (got ${String(maxFileStore)})`);
2759
- return `jetstream { store_dir: ${JSON.stringify(storeDir)}, max_file_store: ${maxFileStore}${limits} }`;
2760
- }
2761
- /** The one place a `tls{}` block is produced, shared by both broker renderers.
2762
- *
2763
- * `allow_non_tls` is deliberately never emitted. It is a TOP-LEVEL knob (nested inside `tls{}`
2764
- * nats-server rejects it as an unknown field), and it turns the listener into mixed mode: INFO
2765
- * then advertises `tls_available` instead of `tls_required`, and a client that declines to
2766
- * upgrade is served in cleartext — precisely the credential exposure this transport closes.
2767
- * There is no supported migration mode; enabling TLS is all-or-nothing. */
2768
- function renderTlsBlock(transport) {
2769
- if (transport.kind === "plaintext")
2770
- return "";
2771
- return `tls {
2772
- cert_file: ${JSON.stringify(transport.certFile)}
2773
- key_file: ${JSON.stringify(transport.keyFile)}
2774
- }
2775
- `;
2776
- }
2777
- function renderAccountResolver(resolver) {
2778
- if (resolver === undefined)
2779
- return "resolver: MEMORY\n";
2780
- const keys = resolver !== null && typeof resolver === "object" && !Array.isArray(resolver) ? Object.keys(resolver) : [];
2781
- if (keys.length === 1 && keys[0] === "kind" && resolver.kind === "memory")
2782
- return "resolver: MEMORY\n";
2783
- if (keys.length !== 4 || resolver.kind !== "full" || !["kind", "directory", "limit", "intervalMs"].every((k) => keys.includes(k)) ||
2784
- typeof resolver.directory !== "string" || !isAbsolute(resolver.directory) || /[\0\r\n]/.test(resolver.directory) ||
2785
- !Number.isSafeInteger(resolver.limit) || resolver.limit < 1 ||
2786
- !Number.isSafeInteger(resolver.intervalMs) || resolver.intervalMs < 1000 || resolver.intervalMs > 86_400_000)
2787
- throw new Error('serverConfig: accountResolver must be { kind: "memory" } or { kind: "full", directory, limit, intervalMs } with an absolute directory, a positive whole limit and an interval of 1000 to 86400000 ms');
2788
- return `resolver: { type: full, dir: ${JSON.stringify(resolver.directory)}, allow_delete: false, interval: "${resolver.intervalMs}ms", limit: ${resolver.limit} }\n`;
2789
- }
2790
- /** Render the `nats-server` config that trusts ONE broker operator and serves N spaces' accounts,
2791
- * resolved by MEMORY unless {@link AccountResolver} `full` is chosen.
2792
- *
2793
- * Broker trust (operator + system account) comes from `broker` and has exactly one owner; the
2794
- * per-space data accounts are listed in `spaces`. Every space account is asserted to be signed by
2795
- * THIS broker's operator before it is preloaded: rendering a foreign-signed account would either
2796
- * refuse broker boot or, worse, advertise a tenant the broker cannot actually authenticate.
2797
- *
2798
- * NOTE: the MEMORY resolver is one static whole-broker map, so every mutation rewrites all of
2799
- * it. With the `full` resolver the preloads seed its directory at boot, and nats-server keeps a
2800
- * newer pushed claim over an older preload, so a later render does not undo a push. Concurrent
2801
- * add/remove of spaces needs a broker-authoritative inventory with generation/CAS and atomic
2802
- * promotion above this function; this renderer is deliberately pure. */
2803
- export function serverConfig(broker, spaces, opts) {
2804
- if (!spaces.length)
2805
- throw new Error("serverConfig: at least one space account is required");
2806
- for (const s of spaces)
2807
- assertAccountSignedByBroker(broker, s);
2808
- const seen = new Map();
2809
- for (const s of [...spaces.map((s) => ({ pub: s.account.pub, what: `space "${s.space}"` })), ...(opts.extraAccounts ?? []).map((a) => ({ pub: a.pub, what: "an extra account" }))]) {
2810
- const prior = seen.get(s.pub);
2811
- if (prior)
2812
- throw new Error(`serverConfig: account ${s.pub} is preloaded twice (${prior} and ${s.what}) - refusing to render an ambiguous resolver`);
2813
- seen.set(s.pub, s.what);
2814
- }
2815
- const port = opts.port ?? 4222;
2816
- const host = opts.host ?? "127.0.0.1";
2817
- // The websocket listener: LOCALHOST by default, no_tls for the dev loopback. Emitted only
2818
- // when wsPort is set — a broker with no console session client opens no ws surface.
2819
- const websocket = opts.wsPort === undefined ? "" : `websocket {
2820
- host: ${opts.wsHost ?? "127.0.0.1"}
2821
- port: ${opts.wsPort}
2822
- no_tls: true
2823
- }
2824
- `;
2825
- // A minted "agent" carries its full permission allow-list inline in its user JWT, which the
2826
- // client sends in the CONNECT protocol line. With per-channel + JetStream-API grants that JWT
2827
- // exceeds the 4 KB default max_control_line at ~2 channels, and the server then silently drops
2828
- // the connection (the client retries forever — a connect that "hangs"). Raise it to fit a rich
2829
- // agent JWT — but right-sized, not generous: the CONNECT line is parsed BEFORE auth, so the cap
2830
- // is a per-connection pre-auth allocation under connection flooding. See MAX_CONTROL_LINE_BYTES
2831
- // for the derivation; mintCreds/mintPublicUserJwt refuse a JWT that would not fit it BEFORE this
2832
- // config is ever reached, so a legal credential never depends on this margin alone.
2833
- const tlsBlock = renderTlsBlock(opts.transport);
2834
- const logBlock = renderLogBlock("serverConfig", opts);
2835
- if (opts.maxPayload !== undefined && (!Number.isSafeInteger(opts.maxPayload) || opts.maxPayload <= 0))
2836
- throw new Error("serverConfig: maxPayload must be a positive safe integer of bytes");
2837
- if (opts.authTimeout !== undefined && (!Number.isSafeInteger(opts.authTimeout) || opts.authTimeout <= 0))
2838
- throw new Error("serverConfig: authTimeout must be a positive whole number of seconds");
2839
- return `# Generated by \`cotal up\` - do not edit by hand.
2840
- host: ${host}
2841
- port: ${port}
2842
- max_control_line: ${MAX_CONTROL_LINE_BYTES}
2843
- ${opts.maxPayload === undefined ? "" : `max_payload: ${opts.maxPayload}\n`}${opts.authTimeout === undefined ? "" : `authorization { timeout: ${opts.authTimeout} }\n`}${logBlock}${tlsBlock}${renderJetStreamBlock("serverConfig", opts.storeDir, opts.maxFileStore, opts.brokerVersion)}
2844
- ${websocket}operator: ${broker.operator.jwt}
2845
- system_account: ${broker.sys.pub}
2846
- ${renderAccountResolver(opts.accountResolver)}resolver_preload: {
2847
- ${spaces.map((s) => ` ${s.account.pub}: ${s.account.jwt}`).join("\n")}
2848
- ${broker.sys.pub}: ${broker.sys.jwt}${(opts.extraAccounts ?? []).map((a) => `\n ${a.pub}: ${a.jwt}`).join("")}
2849
- }
2850
- `;
2851
- }
17
+ export { capabilityRole, taskRoles, permissionsFor, listingGrantRows } from "./provision-permissions.js";
18
+ export { MAX_CONTROL_LINE_BYTES, CONNECT_ENVELOPE_OVERHEAD_BYTES, MAX_MINTED_JWT_BYTES, STANDING_RENEWABLE_TTL_SEC, ROTATION_RENEWED_TTL_SEC, CREDENTIAL_LIFETIMES, credentialLifetime, inspectCredHealth, composeSpaceAuth, assertAccountSignedByBroker, stripSpaceAuth, accountRevocations, revokeAccountUser, retireAccountClaim, rotateSystemAccount, createBrokerAuth, createSpaceAccountAuth, createSpaceAuth, mintCreds, mintPublicUserJwt, mintServiceCalloutJwt, mintMembershipObserverCreds, mintAccountCensusCreds, mintConnectionEvictorCreds } from "./provision-jwt.js";
19
+ export { provisionAgent, provisionAgentDurables } from "./provision-resources.js";
20
+ export { openServerConfig, brokerJetStreamBlock, serverConfig } from "./provision-server-config.js";
2852
21
  //# sourceMappingURL=provision.js.map