@cotal-ai/core 0.167.0 → 0.169.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-file.d.ts.map +1 -1
- package/dist/agent-file.js +12 -9
- package/dist/agent-file.js.map +1 -1
- package/dist/connector-setup.d.ts +2 -0
- package/dist/connector-setup.d.ts.map +1 -1
- package/dist/connector.d.ts +8 -11
- package/dist/connector.d.ts.map +1 -1
- package/dist/control-exchange.d.ts +114 -0
- package/dist/control-exchange.d.ts.map +1 -0
- package/dist/control-exchange.js +416 -0
- package/dist/control-exchange.js.map +1 -0
- package/dist/endpoint-call.d.ts +6 -3
- package/dist/endpoint-call.d.ts.map +1 -1
- package/dist/endpoint-call.js +30 -14
- package/dist/endpoint-call.js.map +1 -1
- package/dist/endpoint-delivery-plane.d.ts +337 -0
- package/dist/endpoint-delivery-plane.d.ts.map +1 -0
- package/dist/endpoint-delivery-plane.js +1291 -0
- package/dist/endpoint-delivery-plane.js.map +1 -0
- package/dist/endpoint-envelope.d.ts +2 -1
- package/dist/endpoint-envelope.d.ts.map +1 -1
- package/dist/endpoint-envelope.js +9 -3
- package/dist/endpoint-envelope.js.map +1 -1
- package/dist/endpoint-history.d.ts +370 -0
- package/dist/endpoint-history.d.ts.map +1 -0
- package/dist/endpoint-history.js +969 -0
- package/dist/endpoint-history.js.map +1 -0
- package/dist/endpoint-inbound.d.ts +10 -0
- package/dist/endpoint-inbound.d.ts.map +1 -0
- package/dist/endpoint-inbound.js +28 -0
- package/dist/endpoint-inbound.js.map +1 -0
- package/dist/endpoint-provenance.d.ts +11 -0
- package/dist/endpoint-provenance.d.ts.map +1 -0
- package/dist/endpoint-provenance.js +20 -0
- package/dist/endpoint-provenance.js.map +1 -0
- package/dist/endpoint-serve.d.ts +11 -1
- package/dist/endpoint-serve.d.ts.map +1 -1
- package/dist/endpoint-serve.js +43 -14
- package/dist/endpoint-serve.js.map +1 -1
- package/dist/endpoint-subjects.d.ts +3 -0
- package/dist/endpoint-subjects.d.ts.map +1 -1
- package/dist/endpoint-subjects.js +3 -0
- package/dist/endpoint-subjects.js.map +1 -1
- package/dist/endpoint.d.ts +80 -252
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +248 -2027
- package/dist/endpoint.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/launch-material.d.ts +9 -3
- package/dist/launch-material.d.ts.map +1 -1
- package/dist/launch-material.js +22 -2
- package/dist/launch-material.js.map +1 -1
- package/dist/provision-jwt.d.ts +518 -0
- package/dist/provision-jwt.d.ts.map +1 -0
- package/dist/provision-jwt.js +641 -0
- package/dist/provision-jwt.js.map +1 -0
- package/dist/provision-permissions.d.ts +72 -0
- package/dist/provision-permissions.d.ts.map +1 -0
- package/dist/provision-permissions.js +2015 -0
- package/dist/provision-permissions.js.map +1 -0
- package/dist/provision-resources.d.ts +66 -0
- package/dist/provision-resources.d.ts.map +1 -0
- package/dist/provision-resources.js +61 -0
- package/dist/provision-resources.js.map +1 -0
- package/dist/provision-server-config.d.ts +115 -0
- package/dist/provision-server-config.d.ts.map +1 -0
- package/dist/provision-server-config.js +169 -0
- package/dist/provision-server-config.js.map +1 -0
- package/dist/provision.d.ts +19 -707
- package/dist/provision.d.ts.map +1 -1
- package/dist/provision.js +4 -2860
- package/dist/provision.js.map +1 -1
- package/dist/remote-manager-authority.d.ts +1 -1
- package/dist/run-journal.d.ts +2 -0
- package/dist/run-journal.d.ts.map +1 -1
- package/dist/run-journal.js +1 -1
- package/dist/run-journal.js.map +1 -1
- package/package.json +5 -1
package/dist/provision.js
CHANGED
|
@@ -14,2864 +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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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, epPrincipalServeGrantRows, epPrincipalOwnerGrantRows, 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 (opts.ledgerKind !== undefined) {
|
|
725
|
-
if (profile !== "agent")
|
|
726
|
-
throw new Error(`permissionsFor: ledgerKind marks an agent-profile mint of a ledger row, not "${profile}" (SPEC 13.21)`);
|
|
727
|
-
// Only the auth callout reads a row's kind from the ledger, and only the callout sets a
|
|
728
|
-
// connection's reader id. A static mint, whose connection is its own nkey, carries no kind.
|
|
729
|
-
if (pr.readerId === undefined)
|
|
730
|
-
throw new Error("permissionsFor: a static mint carries no ledger kind; only the auth callout marks a mint with the kind of the ledger row it read (SPEC 13.21)");
|
|
731
|
-
if (opts.ledgerKind !== "interactive" && opts.ledgerKind !== "managed-agent")
|
|
732
|
-
throw new Error(`permissionsFor: ledgerKind ${JSON.stringify(opts.ledgerKind)} is not "interactive" or "managed-agent"`);
|
|
733
|
-
}
|
|
734
|
-
if (isEnvironmentManagerProfile(profile))
|
|
735
|
-
return environmentManagerPermissions(profile, space, pr, opts.environmentManager);
|
|
736
|
-
if (opts.environmentManager)
|
|
737
|
-
throw new Error(`permissionsFor: environmentManager pins cannot ride ${profile}`);
|
|
738
|
-
if (profile === "delivery")
|
|
739
|
-
return deliveryPermissions(space, pr); // scoped server-side Plane-3 infra
|
|
740
|
-
if (profile === "manager-caller")
|
|
741
|
-
return managerCallerPermissions(space, pr, opts);
|
|
742
|
-
if (profile === "membership-rw")
|
|
743
|
-
return membershipRwPermissions(space, pr); // scoped graph-feed reader/writer
|
|
744
|
-
if (profile === "supervisor")
|
|
745
|
-
return supervisorPermissions(space, pr); // always-on daemon
|
|
746
|
-
if (profile === "provisioner")
|
|
747
|
-
return provisionerPermissions(space, pr); // ephemeral onboarding authority
|
|
748
|
-
if (profile === "deprovisioner") {
|
|
749
|
-
// Ephemeral, TARGET-PINNED teardown — the counterpart to `provisioner`. The target is a
|
|
750
|
-
// full principal dot-form for user-mode agents, or a bare static/dev actor id (keyed under
|
|
751
|
-
// DEV_OWNER) — see {@link deprovisionTargetPrincipal}.
|
|
752
|
-
if (!opts.deprovisionTarget)
|
|
753
|
-
throw new Error("permissionsFor: deprovisioner requires opts.deprovisionTarget ({principal, lifecycleUid} of the departed incarnation)");
|
|
754
|
-
return deprovisionerPermissions(space, pr, opts.deprovisionTarget);
|
|
755
|
-
}
|
|
756
|
-
if (profile === "retirement-requester") {
|
|
757
|
-
// Ephemeral request+reply on the AUTH ENDPOINT rail:
|
|
758
|
-
// publish EXACTLY this caller triple's own request subject for the ONE target it names +
|
|
759
|
-
// subscribe its own reply-plane filter and inbox. No store reads, no barrier/scanner/plane
|
|
760
|
-
// authority - the requester only asks; the auth plane holds every executing right and
|
|
761
|
-
// re-checks the serve registration at serve time.
|
|
762
|
-
// Validate the WHOLE shape, not just its presence. Each of these is a subject token: a missing
|
|
763
|
-
// one would otherwise surface as a raw "cannot read properties of undefined" from deep inside
|
|
764
|
-
// the subject builder, which tells the operator nothing about WHICH field it owes. The `target`
|
|
765
|
-
// arrived with #350 (the handle triple moved into the subject), so a caller written against the
|
|
766
|
-
// pre-#350 `{owner, actor}` shape lands here — and must be told exactly that.
|
|
767
|
-
const rr = opts.retirementRequester;
|
|
768
|
-
if (!rr)
|
|
769
|
-
throw new Error("permissionsFor: retirement-requester requires opts.retirementRequester ({owner, actor, uid, target} of the requesting manager)");
|
|
770
|
-
for (const [k, v] of [["owner", rr.owner], ["actor", rr.actor], ["uid", rr.uid]])
|
|
771
|
-
if (typeof v !== "string" || v.length === 0)
|
|
772
|
-
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)`);
|
|
773
|
-
if (!rr.target || typeof rr.target.owner !== "string" || typeof rr.target.actor !== "string" || typeof rr.target.lifecycleUid !== "string")
|
|
774
|
-
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");
|
|
775
|
-
const { owner, actor, uid, target } = rr;
|
|
776
|
-
const caller = { owner, actor, uid };
|
|
777
|
-
// The row is minted in `exact` mode: a privileged, non-redemption mode where this profile
|
|
778
|
-
// pins the arity-3 target triple directly from the manager's own coordinates under root
|
|
779
|
-
// authority, rather than through `handle`'s issuer-signed redemption provenance. The target is
|
|
780
|
-
// still confinement-pinned, so this credential can ask to retire the ONE incarnation it was
|
|
781
|
-
// minted for and nothing else - the same confinement the pre-#350 grant got from naming an
|
|
782
|
-
// exact `ctl` subject, now covering the TARGET as well as the caller. The nonce is the only
|
|
783
|
-
// wildcard token (§13.9): a bounded per-request suffix, not an addressing widening.
|
|
784
|
-
const rows = epRequestGrantRows(space, {
|
|
785
|
-
endpoint: AUTH_ENDPOINT,
|
|
786
|
-
command: EP_CMD_RETIRE_LIFECYCLE,
|
|
787
|
-
target: { mode: "exact", tOwner: target.owner, tActor: target.actor, tUid: target.lifecycleUid },
|
|
788
|
-
}, caller);
|
|
789
|
-
return {
|
|
790
|
-
pub: {
|
|
791
|
-
allow: [
|
|
792
|
-
...rows,
|
|
793
|
-
epDescribeAllGrantRow(space, caller),
|
|
794
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
|
|
795
|
-
],
|
|
796
|
-
},
|
|
797
|
-
sub: { allow: [epCallerReplyFilter(space, caller), `_INBOX_${pr.connId}.>`] },
|
|
798
|
-
};
|
|
799
|
-
}
|
|
800
|
-
if (profile === "manager-service")
|
|
801
|
-
throw new Error('permissionsFor: "manager-service" is not a generic profile; use the typed remote manager authority protocol');
|
|
802
|
-
if (profile === "remote-manager") {
|
|
803
|
-
if (!opts.remoteManager)
|
|
804
|
-
throw new Error('permissionsFor: "remote-manager" requires opts.remoteManager ({instanceId, owner} of the authorized manager lifecycle)');
|
|
805
|
-
return remoteManagerPermissions(space, pr, opts.remoteManager);
|
|
806
|
-
}
|
|
807
|
-
if (profile === "issuer")
|
|
808
|
-
return issuerPermissions(space, pr);
|
|
809
|
-
if (profile === "registry-reader")
|
|
810
|
-
return registryReaderPermissions(space, pr);
|
|
811
|
-
if (profile === "run-admitter") {
|
|
812
|
-
if (!opts.runAdmitter)
|
|
813
|
-
throw new Error("permissionsFor: run-admitter requires opts.runAdmitter ({endpoint, runId} of the ONE run it admits)");
|
|
814
|
-
return runAdmitterPermissions(space, pr, opts.runAdmitter);
|
|
815
|
-
}
|
|
816
|
-
if (profile === "transfer-writer") {
|
|
817
|
-
if (!opts.transferWriter)
|
|
818
|
-
throw new Error("permissionsFor: transfer-writer requires opts.transferWriter ({instanceId, hex} of the ONE object it writes)");
|
|
819
|
-
const g = transferWriterGrants(space, opts.transferWriter.instanceId, opts.transferWriter.hex, pr.connId);
|
|
820
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
821
|
-
}
|
|
822
|
-
if (profile === "transfer-reader") {
|
|
823
|
-
if (!opts.transferReader)
|
|
824
|
-
throw new Error("permissionsFor: transfer-reader requires opts.transferReader ({instanceId} whose own bucket it reads)");
|
|
825
|
-
const g = transferReaderGrants(space, opts.transferReader.instanceId, pr.connId);
|
|
826
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
827
|
-
}
|
|
828
|
-
if (profile === "endpoint-evictor") {
|
|
829
|
-
// A SCOPED delivery-admin caller for ONE re-registration's verify-evict.
|
|
830
|
-
// Publish EXACTLY this credential's OWN delivery-admin control subject + $JS.API.INFO; subscribe
|
|
831
|
-
// its own reply subtree + inbox. NO lease, presence, store read, consumer, KV, or executing
|
|
832
|
-
// right — the daemon does the $SYS scan/KICK (subject-gated authority, like the supervisor evictor
|
|
833
|
-
// it narrows) and the manager passes only the predecessor's principal. Narrower than the
|
|
834
|
-
// `supervisor` profile the auth barrier-evict reuses (its #30 residual, done here for the manager).
|
|
835
|
-
const req = controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor);
|
|
836
|
-
return { pub: { allow: [req, "$JS.API.INFO"] }, sub: { allow: [`${req}.reply.>`, `_INBOX_${pr.connId}.>`] } };
|
|
837
|
-
}
|
|
838
|
-
if (profile === "lifecycle-executor") {
|
|
839
|
-
if (!opts.lifecycleExecutor)
|
|
840
|
-
throw new Error("permissionsFor: lifecycle-executor requires opts.lifecycleExecutor ({owner, actor, lifecycleUid, alias} of the ONE incarnation it may move)");
|
|
841
|
-
return lifecycleExecutorPermissions(space, pr, opts.lifecycleExecutor);
|
|
842
|
-
}
|
|
843
|
-
if (profile === "endpoint-serve-executor") {
|
|
844
|
-
if (!opts.endpointServeExecutor)
|
|
845
|
-
throw new Error("permissionsFor: endpoint-serve-executor requires opts.endpointServeExecutor ({endpoint, instanceId} of the ONE endpoint instance it may register/serve-mint)");
|
|
846
|
-
return endpointServeExecutorPermissions(space, pr, opts.endpointServeExecutor);
|
|
847
|
-
}
|
|
848
|
-
if (profile === "goal-writer") {
|
|
849
|
-
if (!opts.goalWriter)
|
|
850
|
-
throw new Error("permissionsFor: goal-writer requires opts.goalWriter ({endpoint} whose action goals this connection binds + commits)");
|
|
851
|
-
return goalWriterPermissions(space, pr, opts.goalWriter);
|
|
852
|
-
}
|
|
853
|
-
if (profile === "purger")
|
|
854
|
-
return purgerPermissions(space, pr); // ephemeral history-purge
|
|
855
|
-
if (profile === "backup") {
|
|
856
|
-
if (!opts.backup)
|
|
857
|
-
throw new Error("permissionsFor: backup requires opts.backup");
|
|
858
|
-
return backupProfilePermissions(space, pr.connId, opts.backup);
|
|
859
|
-
}
|
|
860
|
-
if (profile === "restore") {
|
|
861
|
-
if (!opts.restore)
|
|
862
|
-
throw new Error("permissionsFor: restore requires opts.restore");
|
|
863
|
-
return restoreProfilePermissions(space, pr.connId, opts.restore);
|
|
864
|
-
}
|
|
865
|
-
if (profile === "operator")
|
|
866
|
-
return operatorPermissions(space, pr); // human-CLI client (send/dm/ask)
|
|
867
|
-
if (profile === "probe")
|
|
868
|
-
return probePermissions(pr); // connect-only liveness/auth preflight
|
|
869
|
-
if (profile === "channel-writer")
|
|
870
|
-
return channelWriterPermissions(space, pr); // channel-registry writes
|
|
871
|
-
if (profile === "channel-purger")
|
|
872
|
-
return channelPurgerPermissions(space, pr); // channel-writer + CHAT purge
|
|
873
|
-
if (profile === "teardown")
|
|
874
|
-
return teardownPermissions(space, pr, opts.transferStreams ?? []); // space-wide STREAM.DELETE holder
|
|
875
|
-
if (profile === "membership-store-recreate")
|
|
876
|
-
return membershipStoreRecreatePermissions(space, pr);
|
|
877
|
-
if (profile === "issued-store-recreate")
|
|
878
|
-
return issuedStoreRecreatePermissions(space, pr); // the two issued-authority stores only
|
|
879
|
-
if (profile === "control-caller-privileged")
|
|
880
|
-
return controlCallerPermissions(space, pr, "privileged", opts); // ps/start reads
|
|
881
|
-
if (profile === "control-caller-admin")
|
|
882
|
-
return controlCallerPermissions(space, pr, "admin", opts); // any-mode stop/attach
|
|
883
|
-
if (profile === "deployer")
|
|
884
|
-
return deployerPermissions(space, pr, opts.controlTier ?? "admin", opts); // spawn -f deploy authority (user-mode view rides privileged)
|
|
885
|
-
if (profile === "session-caller")
|
|
886
|
-
return sessionCallerPermissions(space, pr, opts.sessionCaller); // one §13.6 session's caller rails
|
|
887
|
-
if (profile === "dm-reader")
|
|
888
|
-
return dmReaderPermissions(space, pr); // one own dm_ durable, bind-only
|
|
889
|
-
if (profile === "session-serving")
|
|
890
|
-
return sessionServingPermissions(space, pr, opts.sessionServing); // one §13.6 session's SERVING rails
|
|
891
|
-
if (profile === "session-ledger")
|
|
892
|
-
return sessionLedgerPermissions(space, pr); // the dedicated session ledger, no rails
|
|
893
|
-
if (profile === "run-driver") {
|
|
894
|
-
if (!opts.runDriver)
|
|
895
|
-
throw new Error("permissionsFor: run-driver requires opts.runDriver ({endpoint, runId, takeoverId, instanceId, epoch} of the ONE run and attempt it drives)");
|
|
896
|
-
const g = runDriverGrants(space, opts.runDriver, pr.connId);
|
|
897
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
898
|
-
}
|
|
899
|
-
if (profile === "run-mediator") {
|
|
900
|
-
if (!opts.runMediator)
|
|
901
|
-
throw new Error("permissionsFor: run-mediator requires opts.runMediator for one run and attempt");
|
|
902
|
-
const g = runMediatorGrants(space, opts.runMediator, pr.connId);
|
|
903
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
904
|
-
}
|
|
905
|
-
if (profile === "run-operator") {
|
|
906
|
-
if (!opts.runOperator)
|
|
907
|
-
throw new Error("permissionsFor: run-operator requires opts.runOperator ({endpoint, takeoverId} of the ONE endpoint whose runs it reads and answers)");
|
|
908
|
-
const g = runOperatorGrants(space, opts.runOperator, pr.connId);
|
|
909
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
910
|
-
}
|
|
911
|
-
if (profile === "endpoint-serve")
|
|
912
|
-
// Serve rows are emitted ONLY by mintCreds behind the §13.1 issuance fence — never via this
|
|
913
|
-
// exported builder, so a direct signer/callout can't obtain unfenced serve rows (SPEC 13.1/13.9).
|
|
914
|
-
throw new Error("permissionsFor: endpoint-serve rows are emitted only by mintCreds behind the §13.1 issuance fence; call mintCreds");
|
|
915
|
-
const CHAT = chatStream(space), DM = dmStream(space), TASK = taskStream(space);
|
|
916
|
-
const PAYLOAD = eventPayloadStream(space);
|
|
917
|
-
const KV = `KV_${presenceBucket(space)}`;
|
|
918
|
-
const CHKV = `KV_${channelBucket(space)}`; // channel registry (read-only for everyone)
|
|
919
|
-
const MEMKV = `KV_${membershipBucket(space)}`; // derived graph membership feed (read-only — dashboard)
|
|
920
|
-
const DLVKV = `KV_${deliveryBucket(space)}`; // delivery lease/readiness (read-only — Component 6 health)
|
|
921
|
-
// Validate both principal tokens; the reply inbox keys on the connection nkey (see MintPrincipal).
|
|
922
|
-
principalKey(pr.owner, pr.actor);
|
|
923
|
-
const inbox = `_INBOX_${pr.connId}.>`;
|
|
924
|
-
if (profile === "observer" || profile === "admin") {
|
|
925
|
-
// Read-only: live feed via tap, history + presence via ephemeral/ordered consumers it
|
|
926
|
-
// creates on CHAT + the presence KV. No chat/inst/svc/ctl publish → can't post.
|
|
927
|
-
// observer — sub chat.> only; DM_<space>/svc never named → DMs + anycast structurally
|
|
928
|
-
// invisible (step-6 inbox scoping means it can't sniff deliveries either).
|
|
929
|
-
// admin — sub widened to the MESSAGING plane, enumerated (SPEC 13.9/13.11): the
|
|
930
|
-
// dashboard's tap also sees DMs (inst.>) and anycast (svc.>) live, PLUS DM-stream read
|
|
931
|
-
// verbs so it can backfill DM history. A deliberate god-view over messaging only: a
|
|
932
|
-
// space-wide `>` would additionally plain-subscribe every v0.4 endpoint request rail
|
|
933
|
-
// (collecting the reply nonces the queue-qualified-only rule protects) and every
|
|
934
|
-
// core-only session frame, so the ep/epe/epf/epj/ept/epr/epw/eps/epc planes are
|
|
935
|
-
// deliberately excluded. DMs are plaintext + ACL-gated, so mint this only for a
|
|
936
|
-
// trusted audit dashboard. CONSUMER.CREATE on DM_<space> is the DM-confidentiality
|
|
937
|
-
// surface — granted here ONLY for this elevated read-only profile, never to agents.
|
|
938
|
-
const sub = [
|
|
939
|
-
...eventPayloadReadSubjects(space, pr.owner, [], profile === "admin"),
|
|
940
|
-
...(profile === "admin"
|
|
941
|
-
? [`${spacePrefix(space)}.chat.>`, `${spacePrefix(space)}.inst.>`, `${spacePrefix(space)}.svc.>`, inbox]
|
|
942
|
-
: [`${spacePrefix(space)}.chat.>`, inbox]),
|
|
943
|
-
];
|
|
944
|
-
// History readers (channelHistory, multiChannelHistory, dmHistory) are named consumers keyed on
|
|
945
|
-
// this connection's reader id (see MintPrincipal.readerId). The profile may delete exactly those
|
|
946
|
-
// names and no other consumer (#4123): each read deletes its readers when it ends, so polling no
|
|
947
|
-
// longer fills the stream's consumer limit.
|
|
948
|
-
const readerId = pr.readerId ?? pr.connId;
|
|
949
|
-
const readerDeletes = (stream) => Array.from({ length: HISTORY_READERS }, (_, i) => `$JS.API.CONSUMER.DELETE.${stream}.${historyReaderConsumer(readerId, i)}`);
|
|
950
|
-
const allow = [
|
|
951
|
-
`$JS.API.STREAM.INFO.${PAYLOAD}`,
|
|
952
|
-
...eventPayloadReadSubjects(space, pr.owner, [], profile === "admin").flatMap(subject => Array.from({ length: HISTORY_READERS }, (_, i) => `$JS.API.CONSUMER.CREATE.${PAYLOAD}.${historyReaderConsumer(readerId, i)}.${subject}`)),
|
|
953
|
-
...Array.from({ length: HISTORY_READERS }, (_, i) => [
|
|
954
|
-
`$JS.API.CONSUMER.INFO.${PAYLOAD}.${historyReaderConsumer(readerId, i)}`,
|
|
955
|
-
`$JS.API.CONSUMER.MSG.NEXT.${PAYLOAD}.${historyReaderConsumer(readerId, i)}`,
|
|
956
|
-
]).flat(),
|
|
957
|
-
...readerDeletes(PAYLOAD),
|
|
958
|
-
"$JS.API.INFO",
|
|
959
|
-
`$JS.API.STREAM.INFO.${CHAT}`,
|
|
960
|
-
`$JS.API.STREAM.INFO.${KV}`,
|
|
961
|
-
// NO stream-wide CONSUMER.DELETE on any stream this profile reads (#691). Its watch consumers
|
|
962
|
-
// are client-named ordered consumers (`oc_<nuid>_<serial>`, the serial bumped on every
|
|
963
|
-
// rebuild), so the only expressible grant for them is stream-wide, and stream-wide let one
|
|
964
|
-
// observer delete another principal's live watch cursors and the delivery daemon's fan-out
|
|
965
|
-
// durable. The broker reaps those consumers at their inactive threshold instead, and the
|
|
966
|
-
// client treats a refused delete of its own watch consumer as that designed outcome.
|
|
967
|
-
//
|
|
968
|
-
// history reader consumer: a multi-filter create can't encode its filter in the subject → bare
|
|
969
|
-
// form; the .> form covers the single-filter named create.
|
|
970
|
-
`$JS.API.CONSUMER.CREATE.${CHAT}`,
|
|
971
|
-
`$JS.API.CONSUMER.CREATE.${CHAT}.>`,
|
|
972
|
-
`$JS.API.CONSUMER.INFO.${CHAT}.>`,
|
|
973
|
-
`$JS.API.CONSUMER.MSG.NEXT.${CHAT}.>`,
|
|
974
|
-
...readerDeletes(CHAT),
|
|
975
|
-
`$JS.ACK.${CHAT}.>`,
|
|
976
|
-
`$JS.API.CONSUMER.CREATE.${KV}.>`, // kv.watch ordered consumer (roster is public)
|
|
977
|
-
`$JS.API.CONSUMER.INFO.${KV}.>`,
|
|
978
|
-
// Channel registry read (watch + direct kv.get + enriched listChannels) — config is
|
|
979
|
-
// world-readable. STREAM.MSG.GET is the verb kv.get() rides (the bucket has no allow_direct).
|
|
980
|
-
`$JS.API.STREAM.INFO.${CHKV}`,
|
|
981
|
-
`$JS.API.STREAM.MSG.GET.${CHKV}`,
|
|
982
|
-
`$JS.API.CONSUMER.CREATE.${CHKV}.>`,
|
|
983
|
-
`$JS.API.CONSUMER.INFO.${CHKV}.>`,
|
|
984
|
-
// Derived graph-membership feed (broker-sourced who-is-subscribed) — watch + direct kv.get. The
|
|
985
|
-
// silent-reader set is sensitive, so read is admin/observer-only (this elevated profile), never an
|
|
986
|
-
// agent. Read-only: no `$KV.${membershipBucket}` publish — only the `membership-rw` cred writes it.
|
|
987
|
-
`$JS.API.STREAM.INFO.${MEMKV}`,
|
|
988
|
-
`$JS.API.STREAM.MSG.GET.${MEMKV}`,
|
|
989
|
-
// The snapshot read (`readMembership`) is paged batched Direct Gets whose request subject is the
|
|
990
|
-
// bare stream, binding no consumer (#4123): this profile may not delete a scan's consumer, so a
|
|
991
|
-
// consumer per read stayed to the inactive threshold and each refused delete was a broker log
|
|
992
|
-
// line. The reply subject is caller-chosen, the same vector the consumer create below already
|
|
993
|
-
// grants on this bucket, so the read reaches no byte the watch could not.
|
|
994
|
-
`$JS.API.DIRECT.GET.${MEMKV}`,
|
|
995
|
-
`$JS.API.CONSUMER.CREATE.${MEMKV}.>`,
|
|
996
|
-
`$JS.API.CONSUMER.INFO.${MEMKV}.>`,
|
|
997
|
-
// Delivery lease/readiness: READ-ONLY (STREAM.INFO + kv.get), the same pair the `agent` arm
|
|
998
|
-
// below already carries for its non-gating `cotal_channels` health surface. A read-only
|
|
999
|
-
// DIAGNOSTIC profile needs this axis for the same reason an agent does, and more: without it
|
|
1000
|
-
// an operator-facing surface can only report the daemon's PROCESS, which is green while the
|
|
1001
|
-
// responder is unbound (#1576). No `$KV.${deliveryBucket(space)}` publish — the lease has
|
|
1002
|
-
// exactly one writer, the `delivery` cred, and that is unchanged here.
|
|
1003
|
-
`$JS.API.STREAM.INFO.${DLVKV}`,
|
|
1004
|
-
`$JS.API.STREAM.MSG.GET.${DLVKV}`,
|
|
1005
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
1006
|
-
];
|
|
1007
|
-
if (profile === "admin") {
|
|
1008
|
-
// DM history backfill (dmHistory): same bare-form gotcha as CHAT — filter_subjects is
|
|
1009
|
-
// plural so the create lands on the bare subject; the .> form covers named consumers.
|
|
1010
|
-
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}.>`);
|
|
1011
|
-
}
|
|
1012
|
-
return { sub: { allow: sub }, pub: { allow } };
|
|
1013
|
-
}
|
|
1014
|
-
// ---- agent ----
|
|
1015
|
-
// No silent fallthrough: every non-agent profile is handled above, so anything else reaching here is a
|
|
1016
|
-
// stale/unwired profile string (e.g. a JS caller bypassing the closed `Profile` union). Fail loud rather
|
|
1017
|
-
// than mint it agent perms by accident (the no-fallbacks rule; matches the deleted `manager`'s intent).
|
|
1018
|
-
if (profile !== "agent")
|
|
1019
|
-
throw new Error(`permissionsFor: unhandled profile "${profile}" - add an explicit arm, do not fall through to agent`);
|
|
1020
|
-
const allowPublish = opts.allowPublish ?? []; // post ACL — DEFAULT-DENY (publish must be declared)
|
|
1021
|
-
// Read ACL — DEFAULT-DENY for channels, exactly like allowPublish above. Omitted or empty mints
|
|
1022
|
-
// NO channel row: no per-channel history-consumer create grant and no `chat.*.<ch>` sub.allow.
|
|
1023
|
-
// The DM/presence/anycast/control rows below are unconditional, so a channel-less agent is still
|
|
1024
|
-
// a full mesh participant, reachable by DM and visible on the roster.
|
|
1025
|
-
const allowSubscribe = opts.allowSubscribe ?? [];
|
|
1026
|
-
// Re-assert at the mint chokepoint (covers mint/spawn paths that bypass the file loader): a policy
|
|
1027
|
-
// channel must equal its wire token, or the minted grant would alias the logical ACL.
|
|
1028
|
-
for (const ch of [...allowSubscribe, ...allowPublish])
|
|
1029
|
-
assertValidChannel(ch);
|
|
1030
|
-
if (!pr.lifecycleUid)
|
|
1031
|
-
throw new Error("permissionsFor(agent): a lifecycleUid is required - the agent's dm/dlv/chathist grants are lifecycle-keyed exact names (SPEC 13.1)");
|
|
1032
|
-
const uid = assertLifecycleToken(pr.lifecycleUid);
|
|
1033
|
-
const chatHistD = chatHistDurable(pr.owner, pr.actor, uid), dmD = dmDurable(pr.owner, pr.actor, uid);
|
|
1034
|
-
const DLV = dlvStream(space), dlvD = dlvDurable(pr.owner, pr.actor, uid); // Plane-3 per-member delivery (bind-only when channel-readable)
|
|
1035
|
-
const roles = taskRoles(opts.role, opts.capabilities);
|
|
1036
|
-
const pubAllow = [
|
|
1037
|
-
// peer publish — owner+actor identity + channel scope, built from the real builders. Default-deny:
|
|
1038
|
-
// ONLY the declared allowPublish channels (none by default) get a chat-publish grant.
|
|
1039
|
-
...allowPublish.map((ch) => chatSubject(space, pr.owner, pr.actor, ch)),
|
|
1040
|
-
unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a> — DM any instance, as me
|
|
1041
|
-
anycastSubject(space, "*", pr.owner, pr.actor), // svc.*.<o>.<a> — anycast any role, as me
|
|
1042
|
-
// Self stop/despawn rides the v0.4 ep baseline (`stop` self-mode) — the manager `ctl` rail is
|
|
1043
|
-
// deleted. The delivery-daemon rail below is a separate service (Plane-3), kept.
|
|
1044
|
-
// ctl.delivery.<o>.<a> — request a durable backstop join/leave/list from the SERVER-SIDE delivery
|
|
1045
|
-
// daemon (NOT the manager). The reply rides this same subtree (`ctl.delivery.<o>.<a>.reply.<n>`, in
|
|
1046
|
-
// sub.allow below) so the daemon can answer without broad inbox-publish — see CONTROL_DELIVERY.
|
|
1047
|
-
controlServiceSubject(space, CONTROL_DELIVERY, pr.owner, pr.actor),
|
|
1048
|
-
// THE PEER-READABLE LIVENESS PROBE (#1577) — one publish row per plane, each pinned to THIS
|
|
1049
|
-
// agent's own principal slots, so a peer asks as itself and can never forge a probe from
|
|
1050
|
-
// another. This is the row that makes liveness askable by a NON-OWNER: without it, the only
|
|
1051
|
-
// hypothesis a peer could form for any failure was "my credentials are wrong", because the
|
|
1052
|
-
// subjects that answer "is the manager alive" were owner-only.
|
|
1053
|
-
//
|
|
1054
|
-
// WHAT THIS DOES NOT GRANT, which is the half that keeps it from being a back door. It is
|
|
1055
|
-
// PUBLISH ON A REQUEST SUBJECT, not a read of anything. The agent gains NO grant on the manager
|
|
1056
|
-
// bucket (still absent by deliberate omission, below) and NO new read of the delivery bucket.
|
|
1057
|
-
// The answer it can obtain is one enum per plane, because the responder reduces the lease row
|
|
1058
|
-
// before replying and the row never crosses the wire. It cannot subscribe the SERVE filter
|
|
1059
|
-
// either: `live.<plane>.*.*` is not in `sub.allow`, so an agent cannot impersonate a responder
|
|
1060
|
-
// and answer a peer's probe with a comforting lie.
|
|
1061
|
-
...LIVENESS_PLANES.map((plane) => livenessSubject(space, plane, pr.owner, pr.actor)),
|
|
1062
|
-
// JetStream control plane — scoped to this agent's own streams/durables.
|
|
1063
|
-
"$JS.API.INFO",
|
|
1064
|
-
// STREAM.INFO: CHAT (join watermark, recall drop-marker, channel-list counts — a documented
|
|
1065
|
-
// metadata surface, see SPEC §9) + the world-readable presence/registry KVs. NOT DM/DLV/EPC:
|
|
1066
|
-
// an agent reaches each of those by name — its own pre-created dm_<id>/dlv_<id> durable, or a
|
|
1067
|
-
// subject-scoped DIRECT.GET on EPC — so it never needs a stream-level read, and `subjects_filter`
|
|
1068
|
-
// is a REQUEST-BODY field no ACL can narrow, so INFO there would enumerate DM and delivery
|
|
1069
|
-
// subject metadata across peers (who DMed whom) for no functional gain. TASK's INFO row is
|
|
1070
|
-
// role-gated with the rest of its TASK grants, below.
|
|
1071
|
-
`$JS.API.STREAM.INFO.${CHAT}`, `$JS.API.STREAM.INFO.${KV}`, `$JS.API.STREAM.INFO.${CHKV}`,
|
|
1072
|
-
// Live channel delivery is the agent's own native core subscription (sub.allow over chat.*.<ch>,
|
|
1073
|
-
// below) — there is NO per-instance chat live-tail durable to bind. The durable backstop is
|
|
1074
|
-
// Plane-3 (the bind-only dlv_<id> durable below). So no CHAT consumer bind/ack grants here.
|
|
1075
|
-
// CHAT history reads (join-backfill, focus-recall, drop-marker) — single-filter EPHEMERAL
|
|
1076
|
-
// consumers named chathist_<id>. The create rides the extended subject
|
|
1077
|
-
// CONSUMER.CREATE.<CHAT>.<chathist_id>.<filter>, whose trailing filter token nats-server pins to
|
|
1078
|
-
// the request body (JSConsumerCreateFilterSubjectMismatchErr, code 10131) — so one create grant
|
|
1079
|
-
// per allowSubscribe channel makes history reads broker-bounded to the read ACL. Replaces the
|
|
1080
|
-
// old unfiltered DIRECT.GET.<CHAT> (which could fetch ANY message regardless of channel). The
|
|
1081
|
-
// name is the agent's own, so info/fetch/delete can't reach a peer's consumer. NO broad
|
|
1082
|
-
// CONSUMER.CREATE.<CHAT> / .> deny here: NATS deny beats allow, which would also kill these.
|
|
1083
|
-
...allowSubscribe.map((ch) => `$JS.API.CONSUMER.CREATE.${CHAT}.${chatHistD}.${chatSubject(space, "*", "*", ch)}`),
|
|
1084
|
-
`$JS.API.CONSUMER.INFO.${CHAT}.${chatHistD}`,
|
|
1085
|
-
`$JS.API.CONSUMER.MSG.NEXT.${CHAT}.${chatHistD}`,
|
|
1086
|
-
`$JS.API.CONSUMER.DELETE.${CHAT}.${chatHistD}`,
|
|
1087
|
-
// DM consumer: BIND ONLY — info/fetch/ack its own pre-created durable, never create.
|
|
1088
|
-
`$JS.API.CONSUMER.INFO.${DM}.${dmD}`,
|
|
1089
|
-
`$JS.API.CONSUMER.MSG.NEXT.${DM}.${dmD}`,
|
|
1090
|
-
`$JS.ACK.${DM}.${dmD}.>`,
|
|
1091
|
-
// Plane-3 DELIVER consumer (SPEC §8): when this credential can read at least one channel, BIND
|
|
1092
|
-
// ONLY its own pre-created dlv_<id> — info/fetch/ack, never create. A channel-less credential has
|
|
1093
|
-
// no DLV durable and no fetch or ack row. It can still ask CONSUMER.INFO for its own durable
|
|
1094
|
-
// name. A client older than 0.163.0 does that during start, and a permitted read answers that
|
|
1095
|
-
// the consumer is absent, which that client treats as nothing to bind. A refused publish fails
|
|
1096
|
-
// the start. It gets NO grant on the INBOX (mixed pre-auth) stream either.
|
|
1097
|
-
...(allowSubscribe.length > 0 ? [
|
|
1098
|
-
`$JS.API.CONSUMER.INFO.${DLV}.${dlvD}`,
|
|
1099
|
-
`$JS.API.CONSUMER.MSG.NEXT.${DLV}.${dlvD}`,
|
|
1100
|
-
`$JS.ACK.${DLV}.${dlvD}.>`,
|
|
1101
|
-
] : [`$JS.API.CONSUMER.INFO.${DLV}.${dlvD}`]),
|
|
1102
|
-
// Presence: on-demand read + watch (read, public roster) + flow control + PUT OWN KEY ONLY.
|
|
1103
|
-
// The read is a batched Direct Get of the bucket (SPEC §6): a seat reads the roster when it acts
|
|
1104
|
-
// instead of receiving every member's heartbeat. Its reply subject is caller-chosen, the same
|
|
1105
|
-
// vector the consumer create below already grants on the same world-readable bucket, so it
|
|
1106
|
-
// reaches no byte the watch could not. The watch rows stay for seats built before the read.
|
|
1107
|
-
`$JS.API.DIRECT.GET.${KV}`,
|
|
1108
|
-
`$JS.API.CONSUMER.CREATE.${KV}.>`,
|
|
1109
|
-
`$JS.API.CONSUMER.INFO.${KV}.>`,
|
|
1110
|
-
// No CONSUMER.DELETE here or on the registry below: the watch's `oc_<nuid>_<serial>` name
|
|
1111
|
-
// cannot be pinned, and a stream-wide delete reaches every peer's watch cursor (#691). A
|
|
1112
|
-
// rebuild's predecessor delete is not published under these claims (#4123), and the consumer
|
|
1113
|
-
// stays until the broker's inactive threshold.
|
|
1114
|
-
"$JS.FC.>",
|
|
1115
|
-
presenceKeySubject(space, pr.owner, pr.actor), // own presence key (owner+actor) only — can't spoof peers
|
|
1116
|
-
// Channel registry: read-only (watch + direct kv.get for the join-time replay decision).
|
|
1117
|
-
// No `$KV.${channelBucket(space)}.*` publish — privileged-write, default-deny gives that free.
|
|
1118
|
-
`$JS.API.STREAM.MSG.GET.${CHKV}`,
|
|
1119
|
-
// A seat reads the registry on demand, and the one-shot CLI reads it once, each with a batched
|
|
1120
|
-
// Direct Get whose request subject is the bare stream (SPEC §7, #4091). On a user-auth mesh the
|
|
1121
|
-
// CLI connects on the user's bearer, which the auth service mints with these rows, so the row is
|
|
1122
|
-
// what lets it leave no watch consumer behind. The same reply-subject reasoning as the presence
|
|
1123
|
-
// read above: the consumer create below already grants that vector on this world-readable bucket.
|
|
1124
|
-
`$JS.API.DIRECT.GET.${CHKV}`,
|
|
1125
|
-
`$JS.API.CONSUMER.CREATE.${CHKV}.>`,
|
|
1126
|
-
`$JS.API.CONSUMER.INFO.${CHKV}.>`,
|
|
1127
|
-
// Delivery lease/readiness: READ-ONLY (kv.get) for the non-gating `cotal_channels` delivery-health
|
|
1128
|
-
// surface (Component 6). The lease key is daemon-availability info, like the world-readable roster;
|
|
1129
|
-
// NO write grant — only the `delivery` cred writes it.
|
|
1130
|
-
`$JS.API.STREAM.INFO.${DLVKV}`,
|
|
1131
|
-
`$JS.API.STREAM.MSG.GET.${DLVKV}`,
|
|
1132
|
-
// Manager lease bucket (`cotal_manager_<space>`): NO grant at all. An agent must never read,
|
|
1133
|
-
// write, or delete it. The bucket holds one `lease.<instanceId>` key per manager instance and
|
|
1134
|
-
// the per-space `renewal` key. The `supervisor` credential writes `lease.*` and `renewal`; a
|
|
1135
|
-
// `remote-manager` credential writes only its own `lease.<instanceId>`. An agent that could
|
|
1136
|
-
// mutate a lease key could DoS that holder (evict it, or pre-create the key to block a fresh
|
|
1137
|
-
// one). Safety is by OMISSION (default-deny on the un-granted `KV_cotal_manager_*` stream and
|
|
1138
|
-
// `$KV.cotal_manager_*.>`), so do NOT add a broad `KV_*` or `$KV.<space>.>` grant that would
|
|
1139
|
-
// silently re-open it.
|
|
1140
|
-
];
|
|
1141
|
-
if (roles.length > 0) {
|
|
1142
|
-
// TASK consumer: BIND ONLY the pre-created durable (svc_<role>) of its own role and of each
|
|
1143
|
-
// `role:<r>` token it holds. Like DM, the create-time filter_subject isn't reliably
|
|
1144
|
-
// ACL-constrainable, so no create path is allowed — the privileged provisioner pre-creates
|
|
1145
|
-
// svc_<role> filtered to svc.<role>.>. STREAM.INFO rides the SAME role gate as the bind rows: a
|
|
1146
|
-
// role-less agent holds no TASK grant at all, so it can neither read the task stream's state
|
|
1147
|
-
// nor enumerate its subjects.
|
|
1148
|
-
pubAllow.push(`$JS.API.STREAM.INFO.${TASK}`);
|
|
1149
|
-
for (const role of roles) {
|
|
1150
|
-
const svcD = taskDurable(role);
|
|
1151
|
-
pubAllow.push(`$JS.API.CONSUMER.INFO.${TASK}.${svcD}`, `$JS.API.CONSUMER.MSG.NEXT.${TASK}.${svcD}`, `$JS.ACK.${TASK}.${svcD}.>`,
|
|
1152
|
-
// The take of one delivered request (SPEC §8.1), pinned to this role and this principal, so a
|
|
1153
|
-
// credential takes only for a role whose queue it binds. Its reply rides the sub row below.
|
|
1154
|
-
takeSubject(space, role, pr.owner, pr.actor));
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
// Spawn / admin capability control reach rides the v0.4 ep rows below (the manager `ctl` rail is
|
|
1158
|
-
// deleted) — the spawn set (owner-mode manager lifecycle) and the admin instrument set
|
|
1159
|
-
// (any-mode + manager.admin family) are added to the ep caller rows, not a ctl subject.
|
|
1160
|
-
// v0.4 endpoint rails (SPEC §13.9 caller rows). EVERY agent gets the Appendix-B BASELINE set
|
|
1161
|
-
// (wildcard describe + delivery join/leave/list + self-mode lifecycle + the reply rail), keyed
|
|
1162
|
-
// on the SAME lifecycle uid as the agent's durables; the spawn capability adds the owner-mode
|
|
1163
|
-
// manager lifecycle set. Beyond the baseline stays default-deny: only minted capabilities
|
|
1164
|
-
// produce rows, each pinning the full caller triple (§13.1 lifecycle UID included; the nonce
|
|
1165
|
-
// is the only wildcard token).
|
|
1166
|
-
// ONE lifecycle uid keys the whole caller rail (§13.1/§13.2 forge-lock: one credential names one
|
|
1167
|
-
// incarnation). `uid` is the already-asserted pr.lifecycleUid; the baseline, the spawn set, AND
|
|
1168
|
-
// the explicit capabilities ALL build their caller triple from it. opts.lifecycleUid is a public
|
|
1169
|
-
// seam (the IdP-adapter path) that must AGREE, never a second source of truth for the triple: a
|
|
1170
|
-
// divergent value would mint two reply rails on one credential, so it fails loud here.
|
|
1171
|
-
const epCaller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid }, opts);
|
|
1172
|
-
const baseline = epBaselineGrantRows(space, epCaller);
|
|
1173
|
-
pubAllow.push(...baseline.pub);
|
|
1174
|
-
if (opts.issued)
|
|
1175
|
-
pubAllow.push(acceptedReadGrant(space, opts.issued.acceptedToken));
|
|
1176
|
-
const epSub = [...baseline.sub];
|
|
1177
|
-
// The registry's listing question rides the issued rail (SPEC 13.20): under the credential's own
|
|
1178
|
-
// generation when its issuance carries it, else under a listing generation.
|
|
1179
|
-
if (opts.issued?.listing)
|
|
1180
|
-
pubAllow.push(...epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, epCaller));
|
|
1181
|
-
if (opts.listing) {
|
|
1182
|
-
const rows = listingGrantRows(space, epCaller, opts.listing);
|
|
1183
|
-
pubAllow.push(...rows.pub);
|
|
1184
|
-
epSub.push(...rows.sub);
|
|
1185
|
-
}
|
|
1186
|
-
// BOTH HALVES OF THE ROLLUP, NOT JUST `pub`. `epCallerGrantRows` returns `{pub, sub}` and its
|
|
1187
|
-
// `sub` is the per-goal progress row its own docblock promises: "a goal-bearing capability
|
|
1188
|
-
// (spawn/launch) adds ONE per-endpoint epGoalProgressGrantRow - the caller may follow its OWN
|
|
1189
|
-
// goal to terminal". Taking `.pub` alone minted a credential that may SUBMIT a goal and may not
|
|
1190
|
-
// HEAR it, so the broker refused the follow and the caller reported a timeout about a goal whose
|
|
1191
|
-
// terminal had already been committed (#610). `spawn` is goal-bearing, so this `sub` is never
|
|
1192
|
-
// empty here - the row was computed correctly and discarded one property access short of the
|
|
1193
|
-
// credential.
|
|
1194
|
-
if (opts.capabilities?.includes("spawn")) {
|
|
1195
|
-
const rows = epCallerGrantRows(space, spawnCallerCapabilities(pr.owner), epCaller);
|
|
1196
|
-
pubAllow.push(...rows.pub);
|
|
1197
|
-
for (const s of rows.sub)
|
|
1198
|
-
if (!epSub.includes(s))
|
|
1199
|
-
epSub.push(s);
|
|
1200
|
-
}
|
|
1201
|
-
// The `run` capability (SPEC 14.3): the manager-hosted workflow-run rows PLUS the spawn set a
|
|
1202
|
-
// program's own spawns need. Rows already minted by `spawn` above are exact duplicates and the
|
|
1203
|
-
// dedupe below folds them; the `sub` half carries the same goal-follow row for the same reason
|
|
1204
|
-
// the spawn branch keeps it.
|
|
1205
|
-
if (opts.capabilities?.includes("run")) {
|
|
1206
|
-
const rows = epCallerGrantRows(space, runCallerCapabilities(pr.owner), epCaller);
|
|
1207
|
-
for (const p of rows.pub)
|
|
1208
|
-
if (!pubAllow.includes(p))
|
|
1209
|
-
pubAllow.push(p);
|
|
1210
|
-
for (const s of rows.sub)
|
|
1211
|
-
if (!epSub.includes(s))
|
|
1212
|
-
epSub.push(s);
|
|
1213
|
-
}
|
|
1214
|
-
if (opts.capabilities?.includes("admin"))
|
|
1215
|
-
// The admin capability grants the admin instrument set on the ep rails, the set a
|
|
1216
|
-
// `control-caller-admin` holds — the any-mode rows + the `manager.admin` family + the reads. In
|
|
1217
|
-
// user mode this is the ledger `admin` scope arriving via the callout, the broker-enforced
|
|
1218
|
-
// half of the tier; the manager's ledger-derived per-op admin flag stays on top of it.
|
|
1219
|
-
{
|
|
1220
|
-
// Same `{pub, sub}` contract as the spawn branch above: an admin instrument's set carries the
|
|
1221
|
-
// goal-bearing lifecycle commands, so it earns the same follow row.
|
|
1222
|
-
const rows = epCallerGrantRows(space, operatorInstrumentCapabilities("admin", pr.owner), epCaller);
|
|
1223
|
-
pubAllow.push(...rows.pub);
|
|
1224
|
-
for (const s of rows.sub)
|
|
1225
|
-
if (!epSub.includes(s))
|
|
1226
|
-
epSub.push(s);
|
|
1227
|
-
}
|
|
1228
|
-
// THE PRINCIPAL ROUTE (SPEC 13.21), for a ledger row of either kind: serve its own `agent`
|
|
1229
|
-
// endpoint under its own principal and lifecycle, the runtime spanned. An interactive row also
|
|
1230
|
-
// calls its owner's agents with the `owner` word. The rows carry the caller triple alone: the
|
|
1231
|
-
// route has no versioned form, whatever rail the rest of the credential rides.
|
|
1232
|
-
if (opts.ledgerKind !== undefined) {
|
|
1233
|
-
const self = { owner: pr.owner, actor: pr.actor, uid };
|
|
1234
|
-
const serve = epPrincipalServeGrantRows(space, self);
|
|
1235
|
-
pubAllow.push(...serve.pub);
|
|
1236
|
-
epSub.push(...serve.sub);
|
|
1237
|
-
if (opts.ledgerKind === "interactive") {
|
|
1238
|
-
const own = epPrincipalOwnerGrantRows(space, self);
|
|
1239
|
-
pubAllow.push(...own.pub);
|
|
1240
|
-
epSub.push(...own.sub);
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
if (opts.endpointCapabilities?.length) {
|
|
1244
|
-
if (opts.lifecycleUid !== undefined && assertLifecycleToken(opts.lifecycleUid) !== uid)
|
|
1245
|
-
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)`);
|
|
1246
|
-
const rows = epCallerGrantRows(space, opts.endpointCapabilities, epCaller);
|
|
1247
|
-
pubAllow.push(...rows.pub);
|
|
1248
|
-
for (const s of rows.sub)
|
|
1249
|
-
if (!epSub.includes(s))
|
|
1250
|
-
epSub.push(s);
|
|
1251
|
-
}
|
|
1252
|
-
// Explicit create-deny (defense-in-depth over default-deny) on the two streams whose
|
|
1253
|
-
// create-time filter_subject is the attack surface — DM (private content) and TASK
|
|
1254
|
-
// (cross-role work-stealing). Covers the bare ephemeral form (no trailing token), the
|
|
1255
|
-
// named/new-API form, and the old durable form. No create path on either stream.
|
|
1256
|
-
const pubDeny = [
|
|
1257
|
-
`$JS.API.CONSUMER.CREATE.${DM}`,
|
|
1258
|
-
`$JS.API.CONSUMER.CREATE.${DM}.>`,
|
|
1259
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${DM}.>`,
|
|
1260
|
-
`$JS.API.CONSUMER.CREATE.${TASK}`,
|
|
1261
|
-
`$JS.API.CONSUMER.CREATE.${TASK}.>`,
|
|
1262
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${TASK}.>`,
|
|
1263
|
-
// Plane-3 DELIVER: bind-only, like DM — the create-time filter_subject is the attack surface, so
|
|
1264
|
-
// no create path (the provisioner pre-creates dlv_<id> filtered to dlv.<id>).
|
|
1265
|
-
`$JS.API.CONSUMER.CREATE.${DLV}`,
|
|
1266
|
-
`$JS.API.CONSUMER.CREATE.${DLV}.>`,
|
|
1267
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${DLV}.>`,
|
|
1268
|
-
];
|
|
1269
|
-
// CHAT live read boundary (SPEC v0.3 §9 / Appendix B): mint the read ACL as a native `sub.allow`
|
|
1270
|
-
// over cotal.<space>.chat.*.<channel> — one per allowSubscribe channel, wildcards passed through
|
|
1271
|
-
// (e.g. chat.*.review.>, chat.*.>). This is what lets an agent self-serve a live channel subscribe
|
|
1272
|
-
// with NO manager: join = nc.subscribe, broker-enforced per-subscribe, no consumer name to confine,
|
|
1273
|
-
// so an open ACL needs no enumeration. This sub.allow grant IS the live read path — there is no
|
|
1274
|
-
// per-instance chat durable; the durable backstop is Plane-3 (delivery-daemon fan-out → per-member DELIVER).
|
|
1275
|
-
const subChat = allowSubscribe.map((ch) => chatSubject(space, "*", "*", ch));
|
|
1276
|
-
const payloadReads = eventPayloadReadSubjects(space, pr.owner, allowSubscribe);
|
|
1277
|
-
if (opts.eventPayloads !== false)
|
|
1278
|
-
pubAllow.push(eventPayloadSubject(space, pr.owner, pr.actor));
|
|
1279
|
-
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}`);
|
|
1280
|
-
// Replies to this agent's durable join/leave/list requests ride `ctl.delivery.<o>.<a>.>` (NOT the
|
|
1281
|
-
// per-id _INBOX), so the scoped delivery daemon can answer without broad inbox-publish.
|
|
1282
|
-
const deliveryReplies = `${controlServiceSubject(space, CONTROL_DELIVERY, pr.owner, pr.actor)}.>`;
|
|
1283
|
-
// Liveness answers (#1577) ride the probe's OWN request subtree, exactly like the delivery
|
|
1284
|
-
// control replies above and for the same reason: the responder answers without needing broad
|
|
1285
|
-
// inbox-publish. One row per plane, pinned to this agent's principal, so it can hear answers to
|
|
1286
|
-
// ITS OWN probes and nothing else — it cannot subscribe a peer's reply lane and harvest answers
|
|
1287
|
-
// addressed elsewhere.
|
|
1288
|
-
const livenessReplies = LIVENESS_PLANES.map((plane) => `${livenessSubject(space, plane, pr.owner, pr.actor)}.>`);
|
|
1289
|
-
// Manager control replies ride the v0.4 ep reply rail (in `epSub`, keyed on the caller triple) —
|
|
1290
|
-
// the `ctl.<tier>.<id>.reply.>` subtrees are gone with the ctl rail.
|
|
1291
|
-
// A take's reply rides the take's own request subtree, like the delivery control replies.
|
|
1292
|
-
const takeReplies = roles.map((role) => `${takeSubject(space, role, pr.owner, pr.actor)}.>`);
|
|
1293
|
-
return { pub: { allow: pubAllow, deny: pubDeny }, sub: { allow: [inbox, deliveryReplies, ...takeReplies, ...livenessReplies, ...subChat, ...payloadReads, ...epSub] } };
|
|
1294
|
-
}
|
|
1295
|
-
/** The reads a spawn-scoped manager-caller view carries on its one pinned instance. A launch uses
|
|
1296
|
-
* `status` (execution mode and connectors), `models` (their catalogs), `resolve-cwd` (canonical
|
|
1297
|
-
* directory) and `list-dir` (directory navigation). The remaining read, `ps`,
|
|
1298
|
-
* lists the caller's own agents: the Manager bounds it to the caller's owner unless the caller
|
|
1299
|
-
* holds admin. The standing spawn set carries none of them, because it reaches every manager in
|
|
1300
|
-
* the space through the class rail. */
|
|
1301
|
-
const SPAWN_VIEW_READS = Object.freeze(["status", "models", "resolve-cwd", "list-dir", "ps"]);
|
|
1302
|
-
/** One seat's manager control view. It carries no agent messaging or delivery surface, and every
|
|
1303
|
-
* manager request, including describe, is pinned to one exact registered instance. */
|
|
1304
|
-
function managerCallerPermissions(space, pr, opts) {
|
|
1305
|
-
if (!pr.lifecycleUid)
|
|
1306
|
-
throw new Error("permissionsFor(manager-caller): a lifecycleUid is required");
|
|
1307
|
-
const instanceId = opts.managerInstanceId === undefined
|
|
1308
|
-
? (() => { throw new Error("permissionsFor(manager-caller): managerInstanceId is required"); })()
|
|
1309
|
-
: assertLifecycleToken(opts.managerInstanceId, "managerInstanceId");
|
|
1310
|
-
const caps = opts.capabilities ?? [];
|
|
1311
|
-
const ordinary = [
|
|
1312
|
-
{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: "describe" },
|
|
1313
|
-
...baselineCallerCapabilities().filter((cap) => cap.endpoint === BASELINE_LIFECYCLE_ENDPOINT),
|
|
1314
|
-
...(caps.includes("spawn") ? spawnCallerCapabilities(pr.owner) : []),
|
|
1315
|
-
...(caps.includes("spawn") ? SPAWN_VIEW_READS.map((command) => ({ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command })) : []),
|
|
1316
|
-
...(caps.includes(MANAGER_VITALS_SCOPE) ? [{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: MANAGER_VITALS_COMMAND }] : []),
|
|
1317
|
-
...(caps.includes("run") ? runCallerCapabilities(pr.owner) : []),
|
|
1318
|
-
...(caps.includes("admin") ? operatorInstrumentCapabilities("admin", pr.owner) : []),
|
|
1319
|
-
];
|
|
1320
|
-
const caller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid: assertLifecycleToken(pr.lifecycleUid) }, opts);
|
|
1321
|
-
const rows = epCallerGrantRows(space, instanceOnlyManagerCapabilities(ordinary, instanceId), caller);
|
|
1322
|
-
const listing = opts.listing ? listingGrantRows(space, caller, opts.listing) : { pub: [], sub: [] };
|
|
1323
|
-
return {
|
|
1324
|
-
pub: {
|
|
1325
|
-
allow: [
|
|
1326
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
|
|
1327
|
-
...(opts.issued ? [acceptedReadGrant(space, opts.issued.acceptedToken)] : []),
|
|
1328
|
-
...rows.pub,
|
|
1329
|
-
...(opts.issued?.listing ? epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, caller) : []),
|
|
1330
|
-
...listing.pub,
|
|
1331
|
-
],
|
|
1332
|
-
},
|
|
1333
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`, ...rows.sub, ...listing.sub] },
|
|
1334
|
-
};
|
|
1335
|
-
}
|
|
1336
|
-
/** The long-lived SUPERVISOR permission set — the always-on manager daemon
|
|
1337
|
-
* (`manager.ts` `this.ep`), carved down from the former allow-all `manager`. Its breadth is
|
|
1338
|
-
* STANDING, so tightening it removes the always-on DM/DLV body-read AND the stream-admin tamper
|
|
1339
|
-
* from the one connection that never goes away. It holds the manager bucket's `lease.*` instance keys
|
|
1340
|
-
* and the per-space renewal lease key, its own presence key + the roster watch, the ONE delivery-admin
|
|
1341
|
-
* call (request + bounded reply subtree), the manager-plane liveness serve + reply rows, and a
|
|
1342
|
-
* read-only point read of the delivery lease row — and nothing else. It serves no manager control:
|
|
1343
|
-
* that is the v0.4 `service` endpoint, served on a SEPARATE connection under its own
|
|
1344
|
-
* `endpoint-serve` credential. Provisioning (DM/DLV/TASK consumer-create + ACL
|
|
1345
|
-
* writes) moves to the EPHEMERAL `provisioner` (opened per-spawn); destructive history-purge moves to the
|
|
1346
|
-
* EPHEMERAL `purger`. So the supervisor holds NO chat/inst/svc publish (it never posts — only
|
|
1347
|
-
* `setActivity`, a presence write), NO DM/DLV read of any kind (no consumer-create, no native sub), NO
|
|
1348
|
-
* stream CREATE/DELETE/PURGE/UPDATE, NO channel-registry access (the daemon sets `watchChannels:false`).
|
|
1349
|
-
* `$JS` is an ENUMERATED allow-list — exactly the presence-watch + lease-KV verbs — never `$JS.>`. A
|
|
1350
|
-
* leaked supervisor cred can hold the lease and read the public roster; it cannot read a DM, forge an
|
|
1351
|
-
* actor, provision, purge, or tamper with a stream. */
|
|
1352
|
-
function supervisorPermissions(space, pr) {
|
|
1353
|
-
const PKV = `KV_${presenceBucket(space)}`, MKV = `KV_${managerBucket(space)}`;
|
|
1354
|
-
const SUP_DLVKV = `KV_${deliveryBucket(space)}`;
|
|
1355
|
-
return {
|
|
1356
|
-
pub: {
|
|
1357
|
-
allow: [
|
|
1358
|
-
"$JS.API.INFO",
|
|
1359
|
-
// Transcript startup checks read retained subject counts, never message bodies.
|
|
1360
|
-
`$JS.API.STREAM.INFO.${chatStream(space)}`,
|
|
1361
|
-
// Per-instance manager liveness lease (managerBucket, pre-created at `cotal up`): OPEN-ONLY bind +
|
|
1362
|
-
// CAS this instance's own `lease.<instanceId>` key (acquire/renew/release) + read the subtree. The
|
|
1363
|
-
// lease is per instance, so the write grant spans `lease.*` (every instance of this space
|
|
1364
|
-
// shares this one supervisor principal — the isolation between instances is the logical-id/CAS
|
|
1365
|
-
// boundary, not a cred boundary). NO STREAM.CREATE (pre-created), DELETE, or PURGE.
|
|
1366
|
-
`$JS.API.STREAM.INFO.${MKV}`,
|
|
1367
|
-
`$JS.API.STREAM.MSG.GET.${MKV}`, // readManagerLease (last_by_subj lease.*) + CAS-conflict kv.get
|
|
1368
|
-
`$KV.${managerBucket(space)}.${MANAGER_LEASE_KEY}.*`, // this instance's lease.<id> key (create/update/delete = $KV publishes)
|
|
1369
|
-
// #1634: the per-space daemon-credential renewal lease, the CAS that picks ONE renewal owner
|
|
1370
|
-
// when several managers share the daemon's store. Same bucket, its own key outside `lease.*`.
|
|
1371
|
-
`$KV.${managerBucket(space)}.${MANAGER_RENEWAL_LEASE_KEY}`,
|
|
1372
|
-
// Presence: publish OWN key + watch the roster. Own key only (no peer-key forge); no
|
|
1373
|
-
// presence-stream purge/delete (no force-offline tamper). No presence kv.get (roster is the in-memory
|
|
1374
|
-
// watch cache + sweep), so no STREAM.MSG.GET on presence.
|
|
1375
|
-
`$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`,
|
|
1376
|
-
`$JS.API.STREAM.INFO.${PKV}`,
|
|
1377
|
-
`$JS.API.CONSUMER.CREATE.${PKV}.>`, // kv.watch ordered consumer (roster)
|
|
1378
|
-
`$JS.API.CONSUMER.INFO.${PKV}.>`,
|
|
1379
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
1380
|
-
// The ONE control service the supervisor CALLS: the delivery daemon's privileged
|
|
1381
|
-
// admin rail — the manager is the daemon's renewal owner, and after re-signing the daemon creds
|
|
1382
|
-
// files it requests `reloadCreds` here so adoption is an explicit, auditable event. Self-scoped
|
|
1383
|
-
// request subject (its own owner+actor slots), bounded reply subtree in sub.allow below.
|
|
1384
|
-
controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor),
|
|
1385
|
-
// LIVENESS REPLIES for the MANAGER plane (#1577), bounded to the `.reply.` leaf under a
|
|
1386
|
-
// caller's own request subject. The supervisor is the natural responder for this plane: it
|
|
1387
|
-
// is the process that HOLDS the manager lease, so it is the one that can answer the
|
|
1388
|
-
// question honestly without anyone else being granted a read of the lease row.
|
|
1389
|
-
//
|
|
1390
|
-
// REPLIES ONLY, exactly like the delivery daemon's `ctl.delivery.*.*.reply.>`. The row stops
|
|
1391
|
-
// at the leaf, so the supervisor cannot publish to the liveness REQUEST subjects themselves
|
|
1392
|
-
// and therefore cannot forge a probe from a peer.
|
|
1393
|
-
livenessReplyGrant(space, "manager"),
|
|
1394
|
-
// #1694: a POINT READ of the delivery lease row, so the store-identity challenge can verify
|
|
1395
|
-
// that the process which answered the queue-grouped admin rail is the holder that actually
|
|
1396
|
-
// reloads the standing credentials. Without it the challenge can only report what some
|
|
1397
|
-
// responder sent, and a non-holder's store stands in for the reloading process's.
|
|
1398
|
-
//
|
|
1399
|
-
// READ ONLY, and that is the half that matters: a credential able to WRITE this row could
|
|
1400
|
-
// manufacture the very fact the challenge reads, which would put the determination back in
|
|
1401
|
-
// the hands of a participant. No `$KV.${deliveryBucket(space)}` publish, no watch consumer,
|
|
1402
|
-
// no STREAM.DELETE or PURGE.
|
|
1403
|
-
`$JS.API.STREAM.INFO.${SUP_DLVKV}`,
|
|
1404
|
-
`$JS.API.STREAM.MSG.GET.${SUP_DLVKV}`,
|
|
1405
|
-
`$JS.API.DIRECT.GET.${SUP_DLVKV}.>`,
|
|
1406
|
-
],
|
|
1407
|
-
},
|
|
1408
|
-
sub: {
|
|
1409
|
-
// Own reply inbox + the delivery-admin reply subtree for its OWN requests. NO chat/inst/dlv
|
|
1410
|
-
// native sub (the supervisor reads no feed), NO manager control-tier serve (that is
|
|
1411
|
-
// the endpoint-serve credential's), NO broad `$JS.>`/`$KV.>`.
|
|
1412
|
-
//
|
|
1413
|
-
// PLUS the manager-plane liveness SERVE filter (#1577): `live.manager.*.*`, queue-grouped, so
|
|
1414
|
-
// any credentialed peer's presence probe reaches the lease holder. This is a serve
|
|
1415
|
-
// subscription on a presence-only rail, not a widening of what the supervisor may read: the
|
|
1416
|
-
// request body is empty and the subject carries only the caller's own principal.
|
|
1417
|
-
allow: [
|
|
1418
|
-
`_INBOX_${pr.connId}.>`,
|
|
1419
|
-
`${controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor)}.>`,
|
|
1420
|
-
livenessServeFilter(space, "manager"),
|
|
1421
|
-
],
|
|
1422
|
-
},
|
|
1423
|
-
};
|
|
1424
|
-
}
|
|
1425
|
-
/** The long-lived REMOTE MANAGER base credential. This is intentionally smaller than the local
|
|
1426
|
-
* supervisor+provisioner union: it registers only its own manager presence, holds only its own
|
|
1427
|
-
* manager-instance lease key, and may provision only lifecycle-keyed resources under its derived
|
|
1428
|
-
* owner. Endpoint registration, contract publication and serving use separate instance-pinned
|
|
1429
|
-
* credentials returned by the same typed host protocol. Per-agent provisioning deliberately does
|
|
1430
|
-
* NOT ride this credential: NATS consumer names are single tokens, so a broker grant cannot safely
|
|
1431
|
-
* express a prefix wildcard inside `dm_<owner>-<actor>-<uid>`. That operation stays on the host's
|
|
1432
|
-
* authenticated provisioning protocol, where the requested descendant is fresh-validated before
|
|
1433
|
-
* an exact one-shot grant is used. */
|
|
1434
|
-
function remoteManagerPermissions(space, pr, pin) {
|
|
1435
|
-
if (pin.owner !== pr.owner)
|
|
1436
|
-
throw new Error(`permissionsFor: remote-manager owner ${JSON.stringify(pin.owner)} does not match the authenticated principal owner ${JSON.stringify(pr.owner)}`);
|
|
1437
|
-
const iid = assertLifecycleToken(pin.instanceId, "remote manager instanceId");
|
|
1438
|
-
const allowedActors = new Set([`manager_${iid}`, `manager_exec_${iid}`]);
|
|
1439
|
-
if (!allowedActors.has(pin.actor) || pr.actor !== pin.actor)
|
|
1440
|
-
throw new Error(`permissionsFor: remote-manager actor must be the server-selected manager_${iid} or manager_exec_${iid} for instance ${iid}`);
|
|
1441
|
-
const PKV = `KV_${presenceBucket(space)}`;
|
|
1442
|
-
const MKV = `KV_${managerBucket(space)}`;
|
|
1443
|
-
const AUTH = epAuthBucket(space);
|
|
1444
|
-
const REC = recordsBucket(space);
|
|
1445
|
-
const gateKey = epgateKey("manager", iid);
|
|
1446
|
-
const credPrefix = epcredFamilyPrefix("manager", iid);
|
|
1447
|
-
const repairKey = eprepairKey("manager", iid);
|
|
1448
|
-
// The SUPERVISOR actor of the pair, which is the one that runs `Manager.start()` and therefore
|
|
1449
|
-
// the only one that binds the manager plane's liveness responder (`service.ts` hands
|
|
1450
|
-
// `credentials.supervisor` to the manager; the executor gets the instance-scoped registration
|
|
1451
|
-
// surface). The liveness rows below are pinned to it so the executor does not carry authority to
|
|
1452
|
-
// answer a probe it never serves.
|
|
1453
|
-
const isSupervisorActor = pin.actor === `manager_${iid}`;
|
|
1454
|
-
const recordKeys = [
|
|
1455
|
-
recordSpecKey(RECORD_KINDS.svc, ["manager", iid]),
|
|
1456
|
-
recordStatusKey(RECORD_KINDS.svc, ["manager", iid]),
|
|
1457
|
-
recordAtomicKey(GOVERN_HEAD, ["manager"]),
|
|
1458
|
-
];
|
|
1459
|
-
return {
|
|
1460
|
-
pub: {
|
|
1461
|
-
allow: [
|
|
1462
|
-
"$JS.API.INFO",
|
|
1463
|
-
// Only the supervisor allocates names against retained transcript counts. This metadata
|
|
1464
|
-
// grant carries no consumer or message-body read, just like the agent CHAT info grant.
|
|
1465
|
-
...(isSupervisorActor ? [`$JS.API.STREAM.INFO.${chatStream(space)}`] : []),
|
|
1466
|
-
// Own manager-instance lease only. The local supervisor profile spans lease.* because one
|
|
1467
|
-
// host manages every local instance; a remote user grant must not.
|
|
1468
|
-
`$JS.API.STREAM.INFO.${MKV}`,
|
|
1469
|
-
`$JS.API.STREAM.MSG.GET.${MKV}`,
|
|
1470
|
-
`$KV.${managerBucket(space)}.${MANAGER_LEASE_KEY}.${iid}`,
|
|
1471
|
-
// Own presence key + roster watch.
|
|
1472
|
-
`$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`,
|
|
1473
|
-
`$JS.API.STREAM.INFO.${PKV}`,
|
|
1474
|
-
`$JS.API.CONSUMER.CREATE.${PKV}.>`,
|
|
1475
|
-
`$JS.API.CONSUMER.INFO.${PKV}.>`,
|
|
1476
|
-
"$JS.FC.>",
|
|
1477
|
-
// This instance's manager service registration + credential family only.
|
|
1478
|
-
`$KV.${AUTH}.${gateKey}`,
|
|
1479
|
-
`$KV.${AUTH}.${repairKey}`,
|
|
1480
|
-
`$KV.${AUTH}.${credPrefix}.>`,
|
|
1481
|
-
...recordKeys.map((key) => `$KV.${REC}.${key}`),
|
|
1482
|
-
`${spacePrefix(space)}.epc.*`,
|
|
1483
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
|
|
1484
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}`,
|
|
1485
|
-
`$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
|
|
1486
|
-
`$JS.API.CONSUMER.CREATE.KV_${AUTH}.>`,
|
|
1487
|
-
`$JS.API.CONSUMER.INFO.KV_${AUTH}.>`,
|
|
1488
|
-
`$JS.API.CONSUMER.DELETE.KV_${AUTH}.>`,
|
|
1489
|
-
...recordKeys.map((key) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${key}`),
|
|
1490
|
-
`$JS.API.STREAM.MSG.GET.KV_${REC}`,
|
|
1491
|
-
// LIVENESS REPLIES for the MANAGER plane (#1577), bounded to the `.reply.` leaf under a
|
|
1492
|
-
// caller's own request subject — the same row and the same bound as the local supervisor
|
|
1493
|
-
// profile holds.
|
|
1494
|
-
//
|
|
1495
|
-
// WHY THIS PROFILE NEEDS IT AT ALL. `Manager.start()` binds the manager plane's liveness
|
|
1496
|
-
// responder unconditionally, and a remote manager runs the same `start()` under this
|
|
1497
|
-
// credential. Without the serve subscription below the bind is denied, and a peer probing
|
|
1498
|
-
// the manager plane then gets the broker's own no-responders answer, which this surface
|
|
1499
|
-
// grades `unbound` — a definite verdict about the plane, produced by a gap in a credential,
|
|
1500
|
-
// while the remote manager is bound and serving. A surface that exists to stop a failure to
|
|
1501
|
-
// find out being rendered as a finding must not render its own missing grant as one.
|
|
1502
|
-
//
|
|
1503
|
-
// REPLIES ONLY. The row stops at the leaf, so a remote manager cannot publish to the
|
|
1504
|
-
// liveness REQUEST subjects and therefore cannot forge a probe that appears to come from a
|
|
1505
|
-
// peer, exactly as the supervisor row cannot.
|
|
1506
|
-
...(isSupervisorActor ? [livenessReplyGrant(space, "manager")] : []),
|
|
1507
|
-
],
|
|
1508
|
-
},
|
|
1509
|
-
sub: {
|
|
1510
|
-
allow: [
|
|
1511
|
-
`_INBOX_${pr.connId}.>`,
|
|
1512
|
-
// The manager-plane liveness SERVE filter (#1577): `live.manager.*.*`, queue-grouped, so a
|
|
1513
|
-
// credentialed peer's presence probe reaches this instance. A serve subscription on a
|
|
1514
|
-
// presence-only rail and not a widening of what a remote manager may read: the request body
|
|
1515
|
-
// is empty and the subject carries only the caller's own principal. The MANAGER plane only —
|
|
1516
|
-
// this credential cannot serve `delivery`, so each plane still answers for itself.
|
|
1517
|
-
...(isSupervisorActor ? [livenessServeFilter(space, "manager")] : []),
|
|
1518
|
-
],
|
|
1519
|
-
},
|
|
1520
|
-
};
|
|
1521
|
-
}
|
|
1522
|
-
/** The human-CLI OPERATOR permission set — the ephemeral key the headless
|
|
1523
|
-
* client commands mint (`cotal send dm|msg|ask`, `cotal dm`, `personas list --running`, via
|
|
1524
|
-
* `openTransient`). It does exactly what those do: POST as itself (chat/DM/anycast — self-scoped, can
|
|
1525
|
-
* never forge another actor), and READ the public roster (presence) + the channel registry to resolve a
|
|
1526
|
-
* name→id and a channel's delivery class. Much narrower than the old broad `manager`: NO serve-control,
|
|
1527
|
-
* NO DM/DLV body read, NO chat-history read, NO stream CREATE/DELETE/PURGE, NO ACL write, NO lease, NO
|
|
1528
|
-
* provisioning. A leaked operator cred can post as itself and read the roster — the same surface as the
|
|
1529
|
-
* human who ran the command. (The interactive `cotal join` console — chat read + own-DM receive — is a
|
|
1530
|
-
* separate, fuller surface, deferred: it needs the unprovisioned-console DM self-create fixed first.) */
|
|
1531
|
-
function operatorPermissions(space, pr) {
|
|
1532
|
-
const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
|
|
1533
|
-
return {
|
|
1534
|
-
pub: {
|
|
1535
|
-
allow: [
|
|
1536
|
-
// Post AS itself only — self-scoped (owner+actor), so a leaked operator cred can never forge a
|
|
1537
|
-
// message attributable to another principal.
|
|
1538
|
-
chatSubject(space, pr.owner, pr.actor, ">"), // chat.<o>.<a>.> — multicast any channel as me
|
|
1539
|
-
unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a> — DM any peer as me
|
|
1540
|
-
anycastSubject(space, "*", pr.owner, pr.actor), // svc.*.<o>.<a> — anycast any role as me
|
|
1541
|
-
`$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`, // own presence key only
|
|
1542
|
-
"$JS.API.INFO",
|
|
1543
|
-
// Presence read (name→id resolution + the roster). The transient endpoint reads the bucket once
|
|
1544
|
-
// with a batched Direct Get, whose request subject is the bare stream (#4091); the consumer rows
|
|
1545
|
-
// serve a watch. No STREAM.MSG.GET.
|
|
1546
|
-
`$JS.API.STREAM.INFO.${PKV}`,
|
|
1547
|
-
`$JS.API.DIRECT.GET.${PKV}`,
|
|
1548
|
-
`$JS.API.CONSUMER.CREATE.${PKV}.>`,
|
|
1549
|
-
`$JS.API.CONSUMER.INFO.${PKV}.>`,
|
|
1550
|
-
// Channel registry read — the transient endpoint reads it once (batched Direct Get), multicast
|
|
1551
|
-
// reads a channel's delivery class, and `channels list` scans it. Read-only (no `$KV.<channel>`
|
|
1552
|
-
// write — that's the provisioner).
|
|
1553
|
-
`$JS.API.STREAM.INFO.${CHKV}`,
|
|
1554
|
-
`$JS.API.DIRECT.GET.${CHKV}`,
|
|
1555
|
-
`$JS.API.STREAM.MSG.GET.${CHKV}`,
|
|
1556
|
-
// Keyed KV get rides `DIRECT.GET.<stream>.$KV.<bucket>.<key>` — the key is in the SUBJECT, so
|
|
1557
|
-
// the grant needs the trailing `.>` (unlike STREAM.MSG.GET, which carries it in the payload).
|
|
1558
|
-
`$JS.API.DIRECT.GET.${CHKV}.>`,
|
|
1559
|
-
`$JS.API.CONSUMER.CREATE.${CHKV}.>`,
|
|
1560
|
-
`$JS.API.CONSUMER.INFO.${CHKV}.>`,
|
|
1561
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
1562
|
-
],
|
|
1563
|
-
},
|
|
1564
|
-
// Own reply inbox only (presence/channel watch ordered-consumer delivery + any request replies land
|
|
1565
|
-
// here). NO chat/inst/dlv native sub — the operator posts and reads the roster, it receives no feed.
|
|
1566
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
1567
|
-
};
|
|
1568
|
-
}
|
|
1569
|
-
/** Connect-only PROBE — the liveness/auth preflight (`preflight.ts preflightTarget`, minted on
|
|
1570
|
-
* ~every CLI command that resolves a mesh). `probeConnect` opens a connection to prove the broker is up
|
|
1571
|
-
* and the creds are accepted, then closes it — it performs NO pub/sub. So the tightest possible grant:
|
|
1572
|
-
* deny ALL publish, subscribe only to the own reply inbox. A leaked probe cred can open a socket and do
|
|
1573
|
-
* nothing else. (Was the broad `manager` cred — minted on nearly every command, the worst over-grant.) */
|
|
1574
|
-
function probePermissions(pr) {
|
|
1575
|
-
return { pub: { deny: [">"] }, sub: { allow: [`_INBOX_${pr.connId}.>`] } };
|
|
1576
|
-
}
|
|
1577
|
-
/** CHANNEL-WRITER — edits the channel registry ONLY: `cotal channels set/default` and the
|
|
1578
|
-
* `spawn -f` new-channel seed (`seedChannelRegistry`). It VALUE-writes `$KV.<channelBucket>` (a channel's
|
|
1579
|
-
* config key) and read-before-writes it. NO stream data, NO other bucket, NO chat/DM — a leaked
|
|
1580
|
-
* channel-writer can only rewrite channel config, never post, read a body, or tear a stream down. */
|
|
1581
|
-
function channelWriterPermissions(space, pr) {
|
|
1582
|
-
const CHKV = `KV_${channelBucket(space)}`;
|
|
1583
|
-
return {
|
|
1584
|
-
pub: {
|
|
1585
|
-
allow: [
|
|
1586
|
-
"$JS.API.INFO",
|
|
1587
|
-
`$KV.${channelBucket(space)}.>`, // create/update/delete a channel config key
|
|
1588
|
-
`$JS.API.STREAM.INFO.${CHKV}`, // kvm.open/create existence check
|
|
1589
|
-
`$JS.API.STREAM.CREATE.${CHKV}`, // kvm.create is create-if-matching (bucket already exists post-up)
|
|
1590
|
-
// read-before-write: kvm.open rides STREAM.MSG.GET; kvm.create (direct=true) rides keyed DIRECT.GET.
|
|
1591
|
-
`$JS.API.STREAM.MSG.GET.${CHKV}`,
|
|
1592
|
-
`$JS.API.DIRECT.GET.${CHKV}.>`,
|
|
1593
|
-
],
|
|
1594
|
-
},
|
|
1595
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
1596
|
-
};
|
|
1597
|
-
}
|
|
1598
|
-
/** CHANNEL-PURGER — the `cotal web` dashboard's ONLY write path: delete a channel
|
|
1599
|
-
* (`clearChannel` = filtered `STREAM.PURGE.CHAT` to drop the channel's messages + a `$KV.<channelBucket>`
|
|
1600
|
-
* key delete). Pre-minted once by `web` so the account signing seed falls out of scope; the dashboard's
|
|
1601
|
-
* READ side runs on the separate read-only `admin` cred. = channel-writer + the scoped CHAT purge. */
|
|
1602
|
-
function channelPurgerPermissions(space, pr) {
|
|
1603
|
-
const CHKV = `KV_${channelBucket(space)}`;
|
|
1604
|
-
// `clearChannel` only kvm.OPENs the (already-created) bucket, key-deletes, and purges — it never
|
|
1605
|
-
// kvm.creates, so — unlike channel-writer's set/default back-compat path — this cred gets NO
|
|
1606
|
-
// `STREAM.CREATE`. Compose the shared channel-KV read + delete verbs + the scoped CHAT purge explicitly.
|
|
1607
|
-
return {
|
|
1608
|
-
pub: {
|
|
1609
|
-
allow: [
|
|
1610
|
-
"$JS.API.INFO",
|
|
1611
|
-
`$KV.${channelBucket(space)}.>`, // delete the channel's registry key
|
|
1612
|
-
`$JS.API.STREAM.INFO.${CHKV}`, // kvm.open existence check
|
|
1613
|
-
`$JS.API.STREAM.MSG.GET.${CHKV}`, // read-before-delete
|
|
1614
|
-
`$JS.API.DIRECT.GET.${CHKV}.>`,
|
|
1615
|
-
`$JS.API.STREAM.PURGE.${chatStream(space)}`, // drop the channel's chat messages
|
|
1616
|
-
],
|
|
1617
|
-
},
|
|
1618
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
1619
|
-
};
|
|
1620
|
-
}
|
|
1621
|
-
/** TEARDOWN — `cotal down -f` space teardown. The space-wide cred that keeps `STREAM.DELETE` (the
|
|
1622
|
-
* tamper verb). `down -f` is multi-step: `connectProbe` (presence-watch + channel-registry read)
|
|
1623
|
-
* → invoke the manager's `ps` + any-mode `despawn` over the ep rails to politely stop the managed
|
|
1624
|
-
* agents → `readMembership` (the membership-feed read that keeps an owned channel another member
|
|
1625
|
-
* still uses) → `deleteChannels`
|
|
1626
|
-
* (channel-registry key delete + CHAT purge) → `deleteSpace` (STREAM.DELETE every owned stream/bucket).
|
|
1627
|
-
* So it reads state, CALLS admin control, deletes channels, and deletes streams — but NEVER reads a
|
|
1628
|
-
* DM/DLV body, posts chat, or forges. Isolated here so no standing operator/provisioner/supervisor cred
|
|
1629
|
-
* can delete a stream; a leaked teardown can wipe a space you own + stop its agents (that IS its job),
|
|
1630
|
-
* nothing else. Minted ephemerally per teardown from the local trust material (same-checkout `down -f`). */
|
|
1631
|
-
function teardownPermissions(space, pr, transferStreams) {
|
|
1632
|
-
// The ep-rail mirror of the admin deploy tier: teardown reads `ps` and stops owned agents
|
|
1633
|
-
// it did not spawn (any-mode despawn) - the admin instrument set. Lifecycle-keyed, so a uid is
|
|
1634
|
-
// required at mint (fail-loud).
|
|
1635
|
-
const ep = instrumentEpRows(space, pr, "admin");
|
|
1636
|
-
const CHAT = chatStream(space);
|
|
1637
|
-
const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
|
|
1638
|
-
const MSHIP = `KV_${membershipBucket(space)}`;
|
|
1639
|
-
const RECORDS = `KV_${recordsBucket(space)}`;
|
|
1640
|
-
// The deletion path and the exact per-stream grants use one target list. Reject any caller-
|
|
1641
|
-
// supplied transfer name that is not this space's transfer bucket before minting the grant.
|
|
1642
|
-
for (const name of transferStreams)
|
|
1643
|
-
if (!isTransferStream(space, name))
|
|
1644
|
-
throw new Error(`permissionsFor: teardown transferStreams names ${JSON.stringify(name)}, not one of ${space}'s transfer streams`);
|
|
1645
|
-
const del = spaceDeletionStreams(space, transferStreams)
|
|
1646
|
-
.flatMap((s) => [`$JS.API.STREAM.INFO.${s}`, `$JS.API.STREAM.DELETE.${s}`]);
|
|
1647
|
-
return {
|
|
1648
|
-
pub: {
|
|
1649
|
-
allow: [
|
|
1650
|
-
"$JS.API.INFO",
|
|
1651
|
-
BROKER_USER_INFO_SUBJECT, // confirm the current teardown connection's account before native impact reads
|
|
1652
|
-
// deleteSpace() enumerates the transfer streams (one per manager instance that received a
|
|
1653
|
-
// carried resume) by name shape; their names are not derivable from the space alone.
|
|
1654
|
-
"$JS.API.STREAM.NAMES",
|
|
1655
|
-
// connectProbe read: presence watch (name→id + roster) + channel registry read.
|
|
1656
|
-
`$JS.API.CONSUMER.CREATE.${PKV}.>`,
|
|
1657
|
-
`$JS.API.CONSUMER.INFO.${PKV}.>`,
|
|
1658
|
-
`$JS.API.STREAM.MSG.GET.${CHKV}`,
|
|
1659
|
-
`$JS.API.DIRECT.GET.${CHKV}.>`,
|
|
1660
|
-
`$JS.API.CONSUMER.CREATE.${CHKV}.>`,
|
|
1661
|
-
`$JS.API.CONSUMER.INFO.${CHKV}.>`,
|
|
1662
|
-
// readMembership's one-pass scan of the feed (its STREAM.INFO is in `del`). No `$KV` publish:
|
|
1663
|
-
// only `membership-rw` writes the feed.
|
|
1664
|
-
// Batched snapshots read the same feed as the watch below, without a consumer.
|
|
1665
|
-
`$JS.API.DIRECT.GET.${MSHIP}`,
|
|
1666
|
-
`$JS.API.CONSUMER.CREATE.${MSHIP}.>`,
|
|
1667
|
-
`$JS.API.CONSUMER.INFO.${MSHIP}.>`,
|
|
1668
|
-
// Space deletion names the workflow runs it removes by their status records: a non-fencing
|
|
1669
|
-
// direct get confined to run status keys (§13.9), on a stream this grant may already delete.
|
|
1670
|
-
`$JS.API.DIRECT.GET.${RECORDS}.$KV.${recordsBucket(space)}.run.*.*.status`,
|
|
1671
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
1672
|
-
// Stop the managed agents over the v0.4 ep rails only (ps + any-mode despawn) — the admin
|
|
1673
|
-
// instrument set. The manager `ctl` rail is deleted.
|
|
1674
|
-
...ep.pub,
|
|
1675
|
-
...del,
|
|
1676
|
-
// deleteChannels/clearChannel: purge the channel's chat messages + delete its registry key.
|
|
1677
|
-
`$JS.API.STREAM.PURGE.${CHAT}`,
|
|
1678
|
-
`$KV.${channelBucket(space)}.>`,
|
|
1679
|
-
],
|
|
1680
|
-
},
|
|
1681
|
-
// Own inbox (connectProbe presence-watch delivery + JS API responses) + the ep reply rail (the
|
|
1682
|
-
// ps + any-mode despawn calls reply there). The `ctl.admin.<id>.reply.>` subtree is gone.
|
|
1683
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
|
|
1684
|
-
};
|
|
1685
|
-
}
|
|
1686
|
-
/** MEMBERSHIP-STORE-RECREATE — explicit conversion of the derived membership feed from File to
|
|
1687
|
-
* Memory. The credential can inspect and delete exactly that one stream. It cannot create the
|
|
1688
|
-
* replacement, read membership values, or touch another stream; the ordinary short-lived
|
|
1689
|
-
* provisioner creates and verifies the empty Memory replacement after deletion. */
|
|
1690
|
-
function membershipStoreRecreatePermissions(space, pr) {
|
|
1691
|
-
const stream = `KV_${membershipBucket(space)}`;
|
|
1692
|
-
return {
|
|
1693
|
-
pub: {
|
|
1694
|
-
allow: [
|
|
1695
|
-
"$JS.API.INFO",
|
|
1696
|
-
`$JS.API.STREAM.INFO.${stream}`,
|
|
1697
|
-
`$JS.API.STREAM.DELETE.${stream}`,
|
|
1698
|
-
],
|
|
1699
|
-
},
|
|
1700
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
1701
|
-
};
|
|
1702
|
-
}
|
|
1703
|
-
/** ISSUED-STORE-RECREATE — `cotal up --recreate-issued-stores`, and an embedder's call of
|
|
1704
|
-
* `removeIssuedStoresBeforeRetention`: back up, then delete, the two issued-authority stores of ONE
|
|
1705
|
-
* space that predate bounded retention. Exactly `STREAM.INFO`, `STREAM.SNAPSHOT` and
|
|
1706
|
-
* `STREAM.DELETE` on those two streams, the snapshot's delivery inside its own inbox, and the
|
|
1707
|
-
* snapshot ACK subjects of those two streams ({@link snapshotAckGrant}). Nothing reads a row,
|
|
1708
|
-
* writes a store or reaches another stream. */
|
|
1709
|
-
function issuedStoreRecreatePermissions(space, pr) {
|
|
1710
|
-
return {
|
|
1711
|
-
pub: {
|
|
1712
|
-
allow: [
|
|
1713
|
-
"$JS.API.INFO",
|
|
1714
|
-
...issuedStoreStreamNames(space).flatMap((s) => [`$JS.API.STREAM.INFO.${s}`, `$JS.API.STREAM.SNAPSHOT.${s}`, `$JS.API.STREAM.DELETE.${s}`, snapshotAckGrant(s)]),
|
|
1715
|
-
],
|
|
1716
|
-
},
|
|
1717
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
1718
|
-
};
|
|
1719
|
-
}
|
|
1720
|
-
/** CONTROL-CALLER (ep rails only) — the operator's lifecycle commands
|
|
1721
|
-
* (`cotal ps/start/stop/attach`, `manager/commands.ts`). It invokes the manager's v0.4 service
|
|
1722
|
-
* endpoint and reads the bounded reply on the ep reply rail. That is ALL — no `$JS`, no `$KV`,
|
|
1723
|
-
* no chat/DM: it forges nothing, reads no body.
|
|
1724
|
-
*
|
|
1725
|
-
* The tiers stay SPLIT because the BROKER grant is load-bearing: an any-mode
|
|
1726
|
-
* despawn/attach row *is* cross-agent reach — the manager maps mode `any` to its admin
|
|
1727
|
-
* authorization path, so which ROWS an instrument holds is the tier boundary. Therefore:
|
|
1728
|
-
* • `control-caller-privileged` (ps/start) holds the manager reads + untargeted `spawn` +
|
|
1729
|
-
* `define-persona` — structurally barred from cross-agent ops (no any-mode row). This is the
|
|
1730
|
-
* high-frequency path; it never needs admin reach.
|
|
1731
|
-
* • `control-caller-admin` (stop/attach) adds the any-mode despawn/attach rows + the
|
|
1732
|
-
* `manager.admin` family — it genuinely needs cross-agent reach. Its containment is the
|
|
1733
|
-
* broker gating the any-mode rows + the cred being ephemeral (mint → one request →
|
|
1734
|
-
* disconnect, from the local signing seed); on a user mesh the manager's serve-time ledger
|
|
1735
|
-
* re-check sits on top. */
|
|
1736
|
-
function controlCallerPermissions(space, pr, epTier, opts = {}) {
|
|
1737
|
-
// The manager `ctl` rail is gone — an operator instrument holds ONLY its v0.4 ep rows (the
|
|
1738
|
-
// tier-matched request set, the reply rail, describe, the one epc fetch). The `epTier` selects
|
|
1739
|
-
// privileged (ps/start reads) vs admin (any-mode stop/attach) exactly as the ctl tier did.
|
|
1740
|
-
//
|
|
1741
|
-
// `--on <instanceId>`: these instruments are ONE-SHOT, minted per control call, and the
|
|
1742
|
-
// resolve that pins the instance happens BEFORE the mint. So the caller can hand the exact
|
|
1743
|
-
// instance id down and get the exact `ep.inst.<endpoint>.<iid>.<command>` row for THIS invocation
|
|
1744
|
-
// and nothing else — the least-privilege issuance, with no standing wildcard anywhere. The
|
|
1745
|
-
// `extra` seam is the same one the deployer's owner-equality `launch` row already rides, and the
|
|
1746
|
-
// emitter's `if (cap.instanceId)` branch validates the token, so a malformed id fails loud at
|
|
1747
|
-
// mint rather than widening a subject.
|
|
1748
|
-
const ep = instrumentEpRows(space, pr, epTier, opts.endpointCapabilities ?? [], opts);
|
|
1749
|
-
return {
|
|
1750
|
-
// The PRIVILEGED tier (the `cotal ps` instrument) also carries the SCOPED §13.9 records read the
|
|
1751
|
-
// class scatter's freeze rides: `freezeExpectedSet` enumerates `svc.<endpoint>.*.spec`
|
|
1752
|
-
// and LEADER-reads each frozen slot's svc spec/status before it scatters `ps` on the `all` rail.
|
|
1753
|
-
// The admin tier (stop/attach) never scatters, so it gets no records read.
|
|
1754
|
-
pub: { allow: epTier === "privileged" ? [...ep.pub, ...scatterFreezeReadRows(space)] : ep.pub },
|
|
1755
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
|
|
1756
|
-
};
|
|
1757
|
-
}
|
|
1758
|
-
/** The SCOPED §13.9 records-read rows the class-scatter freeze rides (`cotal ps`): the
|
|
1759
|
-
* `svc.*` enumeration consumer + the leader-served per-slot spec/status read of the endpoint's
|
|
1760
|
-
* `svc` registry — a READ of exactly the service-registration keys, no write, no other bucket.
|
|
1761
|
-
* The keyed Direct Get is subject-PINNED to `svc.>`; the enumeration consumer
|
|
1762
|
-
* and the leader `STREAM.MSG.GET` are STREAM-scoped because the requested key rides the PAYLOAD
|
|
1763
|
-
* (which a subject grant cannot narrow) — the SAME NAMED RESIDUAL every records reader already
|
|
1764
|
-
* accepts (the provisioner, the lifecycle/serve executors): for this EPHEMERAL one-shot instrument's
|
|
1765
|
-
* lifetime it can READ (never write) any records-store row — registration metadata, no secrets. */
|
|
1766
|
-
function scatterFreezeReadRows(space) {
|
|
1767
|
-
const REC = recordsBucket(space);
|
|
1768
|
-
return [
|
|
1769
|
-
// The `svc.<e>.*.spec` enumeration is a `STREAM.INFO` carrying a `subjects_filter` — ONE
|
|
1770
|
-
// read-only metadata verb. It replaced a `kv.keys()` that rode an ordered ephemeral consumer and
|
|
1771
|
-
// therefore needed CONSUMER.CREATE/INFO/DELETE on this bucket: three consumer-lifecycle verbs to
|
|
1772
|
-
// list keys, on a credential that only ever wanted to read them.
|
|
1773
|
-
//
|
|
1774
|
-
// MEASURED, not assumed: with the enumeration converted and this row absent, the static/operator
|
|
1775
|
-
// `cotal ps` is refused on `$JS.API.STREAM.INFO.KV_<records>` — a path that works today. The
|
|
1776
|
-
// conversion and this row land TOGETHER or the operator path regresses.
|
|
1777
|
-
`$JS.API.STREAM.INFO.KV_${REC}`,
|
|
1778
|
-
// The per-slot spec/status reads (`freezeExpectedSet` + the registration reconcile) are
|
|
1779
|
-
// leader-served `STREAM.MSG.GET` — stream-scoped (NAMED RESIDUAL above), plus the subject-pinned
|
|
1780
|
-
// keyed Direct Get form for any direct-aware read path (scoped to the `svc.` registry prefix).
|
|
1781
|
-
`$JS.API.STREAM.MSG.GET.KV_${REC}`,
|
|
1782
|
-
`$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.>`,
|
|
1783
|
-
];
|
|
1784
|
-
}
|
|
1785
|
-
/** The v0.4 ep-rail rows of an operator INSTRUMENT credential: the tier-matched
|
|
1786
|
-
* {@link operatorInstrumentCapabilities} request rows + the caller's reply rail, the wildcard
|
|
1787
|
-
* `describe` form, and the ONE subject-scoped §13.7 contract-store fetch row (the same shape the
|
|
1788
|
-
* agent baseline holds). No ctl row exists, so these ARE the instrument. The caller triple pins the instrument's own mint-time lifecycle uid
|
|
1789
|
-
* ({@link MintPrincipal.lifecycleUid}) — REQUIRED here: without it the reply rail cannot be pinned
|
|
1790
|
-
* and the mint fails loud rather than emit a triple-less (unfenced) caller surface. `extra` lets a
|
|
1791
|
-
* profile append its tier-refined additions (the user-mode deployer's owner-equality `launch`). */
|
|
1792
|
-
function instrumentEpRows(space, pr, tier, extra = [], opts = {}) {
|
|
1793
|
-
if (!pr.lifecycleUid)
|
|
1794
|
-
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`);
|
|
1795
|
-
const epCaller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid: pr.lifecycleUid }, opts);
|
|
1796
|
-
const rows = epCallerGrantRows(space, [...operatorInstrumentCapabilities(tier, pr.owner), ...extra], epCaller);
|
|
1797
|
-
return {
|
|
1798
|
-
pub: [
|
|
1799
|
-
epDescribeAllGrantRow(space, epCaller),
|
|
1800
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
|
|
1801
|
-
...(opts.issued ? [acceptedReadGrant(space, opts.issued.acceptedToken)] : []),
|
|
1802
|
-
...rows.pub,
|
|
1803
|
-
],
|
|
1804
|
-
sub: rows.sub,
|
|
1805
|
-
};
|
|
1806
|
-
}
|
|
1807
|
-
/** The ep caller a mint pins: the triple, plus the issued generation when the mint is an
|
|
1808
|
-
* issuance (SPEC 13.15). One place decides the rail so a credential's request rows, its reply
|
|
1809
|
-
* read, and its describe row all land on the same one. */
|
|
1810
|
-
function issuedCallerFor(triple, opts) {
|
|
1811
|
-
if (!opts.issued)
|
|
1812
|
-
return triple;
|
|
1813
|
-
assertGeneration(opts.issued.acceptedToken, "acceptedToken");
|
|
1814
|
-
return { ...triple, generation: assertGeneration(opts.issued.generation) };
|
|
1815
|
-
}
|
|
1816
|
-
/** The rows a listing generation adds to a legacy-rail credential (SPEC 13.15, "Listing
|
|
1817
|
-
* issuance"): the registry's `endpoints` request publish and its reply subscribe on `ep.v1`, and
|
|
1818
|
-
* the per-key read of the generation's accepted row. Exactly these: one caller value emits one
|
|
1819
|
-
* rail, so these are the only `ep.v1` rows such a credential holds. */
|
|
1820
|
-
export function listingGrantRows(space, caller, listing) {
|
|
1821
|
-
if (isIssuedCaller(caller))
|
|
1822
|
-
throw new Error("listingGrantRows: an issued caller lists under its own generation");
|
|
1823
|
-
assertGeneration(listing.acceptedToken, "acceptedToken");
|
|
1824
|
-
const issued = { owner: caller.owner, actor: caller.actor, uid: caller.uid, generation: assertGeneration(listing.generation) };
|
|
1825
|
-
return {
|
|
1826
|
-
pub: [...epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, issued), acceptedReadGrant(space, listing.acceptedToken)],
|
|
1827
|
-
sub: [epCallerReplyFilter(space, issued)],
|
|
1828
|
-
};
|
|
1829
|
-
}
|
|
1830
|
-
/** ENDPOINT-SERVE (v0.4, SPEC §13.9 "Serve grants") — the per-instance serve credential:
|
|
1831
|
-
* EXACTLY the instance's registered rails and nothing else. Subscribe: the queue-qualified
|
|
1832
|
-
* class rail, the plain scatter rail, and the own-instance rail for the FULL registered
|
|
1833
|
-
* command set plus the derived `describe`, and the own epoch-pinned timer-fire subjects;
|
|
1834
|
-
* publish: the epoch-pinned egress (reply / `epe` events / `ept` schedule requests / `epr`
|
|
1835
|
-
* record-write ingress) plus, from the branded snapshot only, the §13.9 bind rows: the shared
|
|
1836
|
-
* `eff_<e>` effects bind iff the surface is journal-class and each owned `pool_<e>_<pool>`
|
|
1837
|
-
* bind (bind-only + `$JS.API.INFO`; an ephemeral-only poolless endpoint emits none). No agent
|
|
1838
|
-
* baseline of any kind — no chat/DM/anycast/presence/ctl, no broad `$JS.>`. The value MUST be the
|
|
1839
|
-
* branded ARTIFACT `authorizeServeGrant` returned, and its mint context binds: same space, and
|
|
1840
|
-
* the minted principal is the registered owner. This builds the ROWS; the RELEASE fence is the
|
|
1841
|
-
* durable issuance-gate CAS `mintCreds` runs (SPEC §13.1) — a raw/copied/diverging value or a
|
|
1842
|
-
* foreign space/principal refuses here, and a stale incarnation loses the gate CAS. */
|
|
1843
|
-
function endpointServePermissions(space, pr, opts) {
|
|
1844
|
-
if (!opts.endpointServe)
|
|
1845
|
-
throw new Error("permissionsFor: endpoint-serve requires opts.endpointServe (the authorized serve artifact)");
|
|
1846
|
-
// The fence is INSEPARABLE from serve-row emission: a serve credential's rows are only ever
|
|
1847
|
-
// valid when released behind the §13.1 issuance CAS, so this builder refuses to emit them
|
|
1848
|
-
// without the gate seam — closing the exported-permissionsFor bypass where a direct signer
|
|
1849
|
-
// could obtain unfenced serve rows past the brand/space/owner check. `mintCreds` runs the CAS.
|
|
1850
|
-
if (!opts.serveIssuance)
|
|
1851
|
-
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)");
|
|
1852
|
-
const snap = assertServeGrantMintable(opts.endpointServe, { space, holderOwner: pr.owner });
|
|
1853
|
-
// Rail subscribe rows cover the EPHEMERAL commands only (journal commands ride epj, never the
|
|
1854
|
-
// request rails) + the derived describe; the descriptor surface stays full. The class comes
|
|
1855
|
-
// from the brand-verified artifact surface, not the caller.
|
|
1856
|
-
const ephemeralCommands = snap.commands.filter((cmd) => opts.endpointServe.surface[cmd].class === "ephemeral");
|
|
1857
|
-
const rows = epServeGrantRows(space, {
|
|
1858
|
-
endpoint: snap.endpoint, instanceId: snap.instanceId, epoch: snap.epoch, ephemeralCommands,
|
|
1859
|
-
});
|
|
1860
|
-
// §13.9 bind rows, from the BRANDED snapshot only (journal class is registered truth,
|
|
1861
|
-
// pools are the authorizing provisioner's pre-created durables): a journal-class instance
|
|
1862
|
-
// binds the shared `eff_<e>` effects durable, a pool-owning one binds each owned
|
|
1863
|
-
// `pool_<e>_<pool>` — all bind-only (INFO/MSG.NEXT/ACK, never create/delete), plus the one
|
|
1864
|
-
// `$JS.API.INFO` a pull consumer needs. An ephemeral-only poolless endpoint emits NONE of
|
|
1865
|
-
// these rows (default-deny both directions).
|
|
1866
|
-
const bindRows = [];
|
|
1867
|
-
if (snap.journalClass)
|
|
1868
|
-
bindRows.push(...effectsBindGrants(space, snap.endpoint));
|
|
1869
|
-
for (const pool of snap.pools)
|
|
1870
|
-
bindRows.push(...poolOwnerBindGrants(space, snap.endpoint, pool));
|
|
1871
|
-
if (bindRows.length > 0)
|
|
1872
|
-
bindRows.push("$JS.API.INFO");
|
|
1873
|
-
return {
|
|
1874
|
-
pub: { allow: [...rows.pub, ...bindRows] },
|
|
1875
|
-
sub: { allow: [...rows.sub, `_INBOX_${pr.connId}.>`] },
|
|
1876
|
-
};
|
|
1877
|
-
}
|
|
1878
|
-
/** DEPLOYER — the `cotal spawn -f` manifest-deploy authority. `spawn -f` drives ONE
|
|
1879
|
-
* `connectProbe` endpoint that both READS live state (roster/presence watch, channel registry,
|
|
1880
|
-
* membership feed, manager-singleton lease) AND invokes the running manager's `launch` + `ps`
|
|
1881
|
-
* readiness over the v0.4 ep rails. Those interleave on one connection, so a strict 3-connection
|
|
1882
|
-
* split would only refactor `live.ts` for marginal gain; `deployer` is that one coherent,
|
|
1883
|
-
* ephemeral deploy cred. It is the SOLE profile that combines reads + admin-control — NOT a template a
|
|
1884
|
-
* 4th command should reach for (revisit the connection split before adding a second such caller).
|
|
1885
|
-
*
|
|
1886
|
-
* Boundaries (all enforced by omission / default-deny): NO self-post (`chat`/`inst`/`svc`), NO `$JS.>`,
|
|
1887
|
-
* NO `STREAM.DELETE`/`PURGE`/`UPDATE`, NO DM/DLV/TASK `CONSUMER.CREATE` (no body-read surface), NO `$KV`
|
|
1888
|
-
* writes (channel seeding rides a SEPARATE `channel-writer` cred). It holds the admin INSTRUMENT ep
|
|
1889
|
-
* set (any-mode despawn/attach + the manager.admin family + reads) because manifest launch/ps
|
|
1890
|
-
* genuinely need cross-agent reach — and that IS real power: the manager's any-mode authz is
|
|
1891
|
-
* subject-gated (the any-mode ep row is mintable only under operator policy), so holding it lets it
|
|
1892
|
-
* stop/attach/launch ANY agent. The BROKER gating that row is the boundary. Containment is therefore
|
|
1893
|
-
* the LIFETIME, not a manager re-check: minted from LOCAL same-checkout auth for one `spawn -f`,
|
|
1894
|
-
* memory-only, dropped after deploy. If it is ever persisted, handed to user-supplied `--creds`, or
|
|
1895
|
-
* reused as a general "read + admin" cred, revisit. */
|
|
1896
|
-
function deployerPermissions(space, pr, epTier = "admin", opts = {}) {
|
|
1897
|
-
// The v0.4 ep rows of the deploy authority: static (admin) deploys carry the admin instrument
|
|
1898
|
-
// set; the user-mode deployer VIEW (privileged) carries the privileged set PLUS an untargeted
|
|
1899
|
-
// `launch` row — its launch stays owner-equality-authorized (the manager's ledger-derived admin
|
|
1900
|
-
// flag is false for a spawn-scoped deployer), exactly the v0.3 user-mode privileged-tier launch.
|
|
1901
|
-
// `--on`: the per-invocation pin APPENDS to this profile's standing set, never replaces it -
|
|
1902
|
-
// the privileged deployer view keeps its owner-equality `launch` row and additionally gets the one
|
|
1903
|
-
// exact `ep.inst.<endpoint>.<iid>.<command>` row for the instance this deploy resolved.
|
|
1904
|
-
const pinned = opts.endpointCapabilities ?? [];
|
|
1905
|
-
const ep = epTier === "admin"
|
|
1906
|
-
? instrumentEpRows(space, pr, "admin", pinned, opts)
|
|
1907
|
-
: instrumentEpRows(space, pr, "privileged", [{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: "launch" }, ...pinned], opts);
|
|
1908
|
-
const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
|
|
1909
|
-
const MSHIP = `KV_${membershipBucket(space)}`, MGRKV = `KV_${managerBucket(space)}`;
|
|
1910
|
-
const DLVKV = `KV_${deliveryBucket(space)}`;
|
|
1911
|
-
// Read verbs for a KV bucket SCANNED/WATCHED via an ordered consumer (presence, channel registry, and
|
|
1912
|
-
// the membership feed — `readMembership` enumerates keys via `kv.keys()`): existence + kv.get (both
|
|
1913
|
-
// STREAM.MSG.GET and keyed DIRECT.GET forms) + the ordered consumer. NO `$KV.<bucket>` publish → no write.
|
|
1914
|
-
const kvScan = (bucket) => [
|
|
1915
|
-
`$JS.API.STREAM.INFO.${bucket}`,
|
|
1916
|
-
`$JS.API.STREAM.MSG.GET.${bucket}`,
|
|
1917
|
-
`$JS.API.DIRECT.GET.${bucket}.>`,
|
|
1918
|
-
`$JS.API.CONSUMER.CREATE.${bucket}.>`,
|
|
1919
|
-
`$JS.API.CONSUMER.INFO.${bucket}.>`,
|
|
1920
|
-
];
|
|
1921
|
-
// A KV bucket read by a KEYED point-get only (`readManagerLease` = kvm.open + `kv.get(LEASE_KEY)`, no
|
|
1922
|
-
// scan/watch): existence + kv.get, but NO ordered-consumer verbs (nothing enumerates or watches it).
|
|
1923
|
-
const kvPointRead = (bucket) => [
|
|
1924
|
-
`$JS.API.STREAM.INFO.${bucket}`,
|
|
1925
|
-
`$JS.API.STREAM.MSG.GET.${bucket}`,
|
|
1926
|
-
`$JS.API.DIRECT.GET.${bucket}.>`,
|
|
1927
|
-
];
|
|
1928
|
-
return {
|
|
1929
|
-
pub: {
|
|
1930
|
-
allow: [
|
|
1931
|
-
"$JS.API.INFO",
|
|
1932
|
-
...kvScan(PKV), // presence watch — roster + name→id
|
|
1933
|
-
...kvScan(CHKV), // channel registry read (readChannelRegistry + classifyChannels)
|
|
1934
|
-
...kvScan(MSHIP), // membership FEED read (readMembership → detectUnmanagedActors) — the membership_ bucket
|
|
1935
|
-
...kvPointRead(MGRKV), // manager-singleton lease keyed read (waitManagerReady) — point-get, NO write, NO watch
|
|
1936
|
-
...kvPointRead(DLVKV), // delivery-lease keyed read (preserve-state quiescence proof) — point-get, NO write, NO watch
|
|
1937
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
1938
|
-
// Launch + ps readiness ride the v0.4 ep rows only (the manager `ctl` rail is gone).
|
|
1939
|
-
// Static deploys carry the admin instrument set; the user-mode deployer VIEW carries the
|
|
1940
|
-
// privileged set + an owner-equality `launch` row (the manager's ledger-derived admin flag
|
|
1941
|
-
// is false for a spawn-scoped deployer, so its launch stays owner-equality-authorized).
|
|
1942
|
-
...ep.pub,
|
|
1943
|
-
],
|
|
1944
|
-
},
|
|
1945
|
-
// Own inbox (presence/registry watch delivery + JS API responses) + the ep reply rail.
|
|
1946
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
|
|
1947
|
-
};
|
|
1948
|
-
}
|
|
1949
|
-
/** The ephemeral PURGER permission set — minted per-purge inside the daemon's
|
|
1950
|
-
* `opPurge` and `cotal history clear`. Isolates the DESTRUCTIVE history-purge grant
|
|
1951
|
-
* (`STREAM.PURGE.CHAT` + `STREAM.PURGE.DM`) off the always-on supervisor: `--dms` purges the DM stream,
|
|
1952
|
-
* exactly the grant the supervisor must not hold. It PURGES but never READS — no DM/chat consumer, no
|
|
1953
|
-
* `MSG.GET` — so a leaked purger can drop history but cannot read a body. Short-lived (one purge call). */
|
|
1954
|
-
function purgerPermissions(space, pr) {
|
|
1955
|
-
const CHAT = chatStream(space), DM = dmStream(space);
|
|
1956
|
-
return {
|
|
1957
|
-
pub: {
|
|
1958
|
-
allow: [
|
|
1959
|
-
"$JS.API.INFO", // jetstreamManager bootstrap; STREAM.PURGE needs no prior STREAM.INFO
|
|
1960
|
-
`$JS.API.STREAM.PURGE.${CHAT}`, // clearSpaceHistory chat purge
|
|
1961
|
-
`$JS.API.STREAM.PURGE.${DM}`, // clearSpaceHistory includeDms — the isolated DM-purge grant
|
|
1962
|
-
],
|
|
1963
|
-
// NOTE: this profile does NOT cover `clearChannel` (web/`down -f` channel-delete) — that also does a
|
|
1964
|
-
// `$KV.<channelBucket>.<ch>` registry delete this cred lacks, which `channel-purger` and `teardown` hold.
|
|
1965
|
-
},
|
|
1966
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
1967
|
-
};
|
|
1968
|
-
}
|
|
1969
|
-
/** The ephemeral PROVISIONER permission set — the onboarding authority,
|
|
1970
|
-
* carved off the long-lived manager. Minted short-lived for per-spawn provisioning (pre-create each
|
|
1971
|
-
* agent's bind-only DM/DLV/TASK durables + record its read ACL via `commitAcl`) — the daemon opens it per
|
|
1972
|
-
* spawn (`manager.ts withProvisioner`). It is ALSO the cred that creates the space's streams + KV buckets
|
|
1973
|
-
* and seeds the channel registry via `setupSpaceStreams` (exercised by the manager-split smoke) — and
|
|
1974
|
-
* `cotal up`'s ephemeral setup cred (`up.ts authSetup`) now mints THIS profile, not the broad `manager`.
|
|
1975
|
-
* NEVER minted for an agent — `cotal mint` whitelists
|
|
1976
|
-
* agent/observer/admin only, like `manager`/`delivery`.
|
|
1977
|
-
*
|
|
1978
|
-
* This profile HOLDS the DM/DLV `CONSUMER.CREATE` push-consumer surface — the irreducible onboarding
|
|
1979
|
-
* power (the create-time `deliver_subject` of a push consumer is not ACL-constrained, so whoever can
|
|
1980
|
-
* create a DM/DLV consumer can stream the bodies). That is exactly why it is split OFF the always-on
|
|
1981
|
-
* supervisor and made EPHEMERAL: the daemon opens a provisioner connection per spawn and drains it
|
|
1982
|
-
* immediately, so the surface exists only for the provisioning window, not as a standing target. The
|
|
1983
|
-
* cred is MEMORY-ONLY (never written to `.cotal`) and carries a short profile-default `exp`.
|
|
1984
|
-
*
|
|
1985
|
-
* `$JS` is an ENUMERATED allow-list, never `$JS.>`: STREAM.CREATE + INFO for the space streams/buckets,
|
|
1986
|
-
* DM/DLV/TASK consumer CREATE/DURABLE.CREATE/INFO — and deliberately NO `MSG.NEXT`/`MSG.GET`/`ACK` on
|
|
1987
|
-
* DM/DLV (it creates the bind-only mailbox but never reads it), and NO STREAM.DELETE/PURGE/MSG.DELETE
|
|
1988
|
-
* (it provisions, it does not tear down). STREAM.UPDATE is held on EXACTLY thirteen streams and no others:
|
|
1989
|
-
* the three TTL'd KV buckets (presence + the two leases, #286: an existing bucket's `max_age` cannot be
|
|
1990
|
-
* fixed by `kvm.create`, so reconciling a pre-TTL deployment requires updating it), the four hardened
|
|
1991
|
-
* authority stores (records, issued, accepted, admission), each updated once at creation, and the
|
|
1992
|
-
* membership KV and artifact Object Store, whose legacy `max_bytes` values setup reconciles to -1 (the
|
|
1993
|
-
* reservation a positive cap holds against the broker's `max_file_store` is what stopped a tenth space
|
|
1994
|
-
* from being provisioned; `Objm.create` cannot fix an existing bucket's cap either), and the CHAT,
|
|
1995
|
-
* INBOX, DLV and DM streams, whose history limits `cotal history limit` writes (`setHistoryLimit`).
|
|
1996
|
-
* Stated positively on purpose: this docblock previously read "NO …/UPDATE", which was already untrue of
|
|
1997
|
-
* the records stream and became untrue of the buckets, and a comment that denies a credential's real
|
|
1998
|
-
* power is worse than none — it is the document a reader trusts instead of checking. KV value-writes are
|
|
1999
|
-
* scoped to exactly the two
|
|
2000
|
-
* registries provisioning touches: the read-ACL bucket (`commitAcl`) and the channel registry (seed). */
|
|
2001
|
-
function provisionerPermissions(space, pr) {
|
|
2002
|
-
const CHAT = chatStream(space), DM = dmStream(space), TASK = taskStream(space);
|
|
2003
|
-
const INBOX = inboxStream(space), DLV = dlvStream(space);
|
|
2004
|
-
// Every non-endpoint KV backing stream the provisioner pre-creates. Endpoint control streams and
|
|
2005
|
-
// their records/auth/session buckets come from endpointPlaneStreamNames below, the same downstream
|
|
2006
|
-
// ownership list consumed by inventory and teardown. The provisioner holds create-or-verify only on
|
|
2007
|
-
// those authority stores; lifecycle/session writes ride their narrower executor credentials.
|
|
2008
|
-
const buckets = [
|
|
2009
|
-
presenceBucket, channelBucket, membersBucket, aclBucket, membershipBucket, anycastBucket, deliveryBucket, managerBucket,
|
|
2010
|
-
].map((b) => `KV_${b(space)}`);
|
|
2011
|
-
// STREAM.CREATE + INFO for each (idempotent setup at `cotal up`; CREATE is create-if-matching, INFO covers
|
|
2012
|
-
// the client's existence checks). NO DELETE/PURGE — provisioning never tears a stream down.
|
|
2013
|
-
// The §13.7 CONTRACT store (EPC) joins the list for the static manager's start-time
|
|
2014
|
-
// `ensureContractStore`: create-or-verify only — the provisioner holds no
|
|
2015
|
-
// artifact-publish grant on it (publication rides the scoped endpoint-serve executor).
|
|
2016
|
-
// The seven §13.12 ENDPOINT streams join the list: spawn-as-action makes the manager
|
|
2017
|
-
// the first EPF (goal facts) + EPE (progress) writer, and nothing provisioned the endpoint streams
|
|
2018
|
-
// before (no manager code wrote to them), so `createEndpointStreams` now runs at the manager's
|
|
2019
|
-
// start-time ensure over this provisioner. Create-or-verify only (idempotent, fail-loud on drift);
|
|
2020
|
-
// the provisioner holds no value-write on any of them (goal facts ride the scoped goal-writer cred).
|
|
2021
|
-
// WFJ and the EPC/records/auth/session stores join them through endpointPlaneStreamNames because
|
|
2022
|
-
// createEndpointStreams owns all twelve resources. Create-or-verify only; the provisioner appends
|
|
2023
|
-
// nothing (writes ride the narrower runtime and authority credentials).
|
|
2024
|
-
// The artifact Object Store joins the list: `setupSpaceStreams` creates it, and under auth mode the
|
|
2025
|
-
// provisioner is the cred doing that creating. Its backing stream is `OBJ_<bucket>` - named
|
|
2026
|
-
// explicitly, because `$O.<bucket>.>` is outside the `cotal.<space>.>` grammar and no space-prefix
|
|
2027
|
-
// grant reaches it. CREATE + INFO here, plus the ONE STREAM.UPDATE below (the legacy-cap reconcile):
|
|
2028
|
-
// the provisioner never publishes an object, never creates a consumer on it, and never deletes it.
|
|
2029
|
-
// That confinement is load-bearing rather than tidy - the
|
|
2030
|
-
// object-store client reads by creating an ephemeral PUSH consumer with a caller-chosen
|
|
2031
|
-
// `deliver_subject`, so a CONSUMER.CREATE here would be an exporter of every artifact in the space.
|
|
2032
|
-
const OBJ = objectStoreStream(artifactBucket(space));
|
|
2033
|
-
const streamSetup = [CHAT, DM, TASK, INBOX, DLV, eventPayloadStream(space), OBJ, ...endpointPlaneStreamNames(space), ...buckets].flatMap((s) => [
|
|
2034
|
-
`$JS.API.STREAM.CREATE.${s}`,
|
|
2035
|
-
`$JS.API.STREAM.INFO.${s}`,
|
|
2036
|
-
]);
|
|
2037
|
-
// #286: STREAM.UPDATE on EXACTLY the three TTL'd KV streams (presence + the two leases). `kvm.create`
|
|
2038
|
-
// never updates an existing bucket's config, so a bucket created by a cotal that predates the `max_age`
|
|
2039
|
-
// TTL keeps NO expiry forever — dead presence records (and stale leases) never age out. `setupSpaceStreams`
|
|
2040
|
-
// reconciles their `max_age` via STREAM.UPDATE at every `cotal up`, which needs this grant. Scoped to these
|
|
2041
|
-
// three streams here. The durable task stream and the channel/members/acl registries are never
|
|
2042
|
-
// updated (the history limits of the four message streams are the exception, below), and there is
|
|
2043
|
-
// still NO DELETE/PURGE. The supervisor profile keeps its full UPDATE
|
|
2044
|
-
// denial; this widening is provisioning-only.
|
|
2045
|
-
// Derived from the SAME inventory that creates and reconciles them, not a third hand-kept copy.
|
|
2046
|
-
// Review found this list was the last independent one: a fourth TTL'd bucket added to `ttlBuckets`
|
|
2047
|
-
// would be created and reconciled correctly and then die on a permissions violation here, because
|
|
2048
|
-
// the grant never learned about it. Same defect one seam out — a bucket the code knows to maintain
|
|
2049
|
-
// and the credential is not allowed to.
|
|
2050
|
-
const ttlStreams = ttlBuckets(space).map(([bucket]) => `KV_${bucket}`);
|
|
2051
|
-
// ...plus the membership KV and artifact Object Store. Both create at `max_bytes: -1` so they
|
|
2052
|
-
// reserve nothing against the broker's `max_file_store`, and both reconcile only their own stock
|
|
2053
|
-
// legacy caps so an EXISTING mesh releases those reservations too. The create clients never update
|
|
2054
|
-
// an existing bucket's config, so each reconcile is a STREAM.UPDATE and needs this grant — without
|
|
2055
|
-
// it the provisioner dies on a permissions violation on the first `cotal up` after the upgrade.
|
|
2056
|
-
// Still CREATE/INFO/UPDATE only:
|
|
2057
|
-
// no publish, no CONSUMER.CREATE (a push consumer's caller-chosen `deliver_subject` would export
|
|
2058
|
-
// every artifact in the space), no DELETE/PURGE.
|
|
2059
|
-
// ...plus the CHAT, INBOX, DLV and DM streams: `cotal history limit` sets their history limits
|
|
2060
|
-
// (SPEC §8). STREAM.UPDATE is a whole-config write, so the grant reaches every setting of them;
|
|
2061
|
-
// `setHistoryLimit` changes only `max_age` and `max_msgs_per_subject` and refuses a read back that is
|
|
2062
|
-
// not canonical apart from those two. TASK stays create-only.
|
|
2063
|
-
const streamReconcile = [...ttlStreams, `KV_${membershipBucket(space)}`, OBJ, CHAT, INBOX, DLV, DM]
|
|
2064
|
-
.map((s) => `$JS.API.STREAM.UPDATE.${s}`);
|
|
2065
|
-
// #404: one EXACT reserved key on each TTL bucket is the post-update enforcement canary. The
|
|
2066
|
-
// provisioner still cannot write presence identities or lease keys; it can only write this fixed
|
|
2067
|
-
// maintenance key, which expires through the policy the reconcile is proving.
|
|
2068
|
-
const ttlCanaries = ttlBuckets(space).map(([bucket]) => `$KV.${bucket}.${TTL_RECONCILE_CANARY_KEY}`);
|
|
2069
|
-
// DM/DLV/TASK durable pre-create (bind-only mailboxes): both the new-API CREATE and legacy DURABLE.CREATE
|
|
2070
|
-
// forms (the client's consumer-add path varies by version), plus INFO (the add returns ConsumerInfo).
|
|
2071
|
-
// NO MSG.NEXT/MSG.GET/ACK — the provisioner creates the consumer but MUST NOT read its body.
|
|
2072
|
-
const consumerCreate = [DM, DLV, TASK].flatMap((s) => [
|
|
2073
|
-
`$JS.API.CONSUMER.CREATE.${s}.>`,
|
|
2074
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${s}.>`,
|
|
2075
|
-
`$JS.API.CONSUMER.INFO.${s}.>`,
|
|
2076
|
-
]);
|
|
2077
|
-
return {
|
|
2078
|
-
pub: {
|
|
2079
|
-
allow: [
|
|
2080
|
-
"$JS.API.INFO",
|
|
2081
|
-
// Current-connection identity only; the broker maps the account and requesting user.
|
|
2082
|
-
// No subject containing another account/user and no system credential is granted.
|
|
2083
|
-
BROKER_USER_INFO_SUBJECT,
|
|
2084
|
-
...streamSetup,
|
|
2085
|
-
...streamReconcile,
|
|
2086
|
-
...ttlCanaries,
|
|
2087
|
-
...consumerCreate,
|
|
2088
|
-
// KV value-writes — exactly the two registries provisioning writes: the agent read-ACL registry
|
|
2089
|
-
// (`commitAcl` at provision) and the channel registry (seed defaults at `cotal up`, channel admin).
|
|
2090
|
-
// NO presence/members/membership/delivery writes (the agent's own key, the delivery cred, and the
|
|
2091
|
-
// membership-rw cred own those).
|
|
2092
|
-
`$KV.${aclBucket(space)}.>`,
|
|
2093
|
-
`$KV.${channelBucket(space)}.>`,
|
|
2094
|
-
// ...and READ both: commitAcl read-before-writes the ACL (`kvm.open`, direct=false ⇒ STREAM.MSG.GET);
|
|
2095
|
-
// the channel seed read-before-writes defaults (`kvm.create`, direct=true ⇒ DIRECT.GET). Grant both
|
|
2096
|
-
// read verbs on both buckets to cover the open/create-path variance — reads of registries it already
|
|
2097
|
-
// writes, no escalation. Without these the read-before-write rejects and provisioning/seed throws.
|
|
2098
|
-
`$JS.API.STREAM.MSG.GET.KV_${aclBucket(space)}`,
|
|
2099
|
-
`$JS.API.DIRECT.GET.KV_${aclBucket(space)}.>`, // keyed get: `.>` (the key rides the subject)
|
|
2100
|
-
`$JS.API.STREAM.MSG.GET.KV_${channelBucket(space)}`,
|
|
2101
|
-
`$JS.API.DIRECT.GET.KV_${channelBucket(space)}.>`, // keyed get: `.>` (the key rides the subject)
|
|
2102
|
-
// The static-manager start path: `ensureAuthorityStores` UPDATEs the records store's
|
|
2103
|
-
// deny-flags exactly once at fresh creation (create → update → verify), and the boot
|
|
2104
|
-
// reconciliation sweep enumerates the manager's slot rows (`keys()` → an ordered consumer)
|
|
2105
|
-
// then reads each slot BODY (phase/uid/actor) to plan resume — the reads ride the
|
|
2106
|
-
// stream-scoped MSG.GET residual named below (records lifecycle metadata, no secrets).
|
|
2107
|
-
// The issued, accepted and admission stores (SPEC 13.15, 14.8) take the same one-time
|
|
2108
|
-
// hardening UPDATE at fresh creation as the records store: their rows are create-only and
|
|
2109
|
-
// their markers permanent, and a holder's own key row would otherwise replace them as a
|
|
2110
|
-
// value write. One list in core names the hardened stores for every seam that creates them.
|
|
2111
|
-
...hardenedAuthorityStreamNames(space).map((s) => `$JS.API.STREAM.UPDATE.${s}`),
|
|
2112
|
-
`$JS.API.CONSUMER.CREATE.KV_${recordsBucket(space)}.>`,
|
|
2113
|
-
`$JS.API.CONSUMER.INFO.KV_${recordsBucket(space)}.>`,
|
|
2114
|
-
`$JS.API.CONSUMER.DELETE.KV_${recordsBucket(space)}.>`,
|
|
2115
|
-
// ...and reads the slot-mapping rows so the sweep can plan resume actions. The KV client
|
|
2116
|
-
// reads a lazily-bound bucket via leader-served `STREAM.MSG.GET` — stream-scoped, NOT
|
|
2117
|
-
// key-scoped (the requested key rides the PAYLOAD). NAMED RESIDUAL: for its one-shot
|
|
2118
|
-
// lifetime the provisioner can READ (never write) any records-store row — lifecycle
|
|
2119
|
-
// metadata, no secrets. The keyed Direct Get grant stays for direct-aware read paths.
|
|
2120
|
-
`$JS.API.STREAM.MSG.GET.KV_${recordsBucket(space)}`,
|
|
2121
|
-
`$JS.API.DIRECT.GET.KV_${recordsBucket(space)}.$KV.${recordsBucket(space)}.${STATIC_SLOT_PREFIX}.>`,
|
|
2122
|
-
],
|
|
2123
|
-
},
|
|
2124
|
-
// Replies only: every stream/consumer/KV-create PubAck and JS API response lands on the per-id inbox.
|
|
2125
|
-
// NO chat/inst/dlv/ctl subscription — the provisioner never serves control nor reads any feed.
|
|
2126
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2127
|
-
};
|
|
2128
|
-
}
|
|
2129
|
-
/** The ISSUER permission set (SPEC 13.15): value-writes on the evidence store (evidence, attempt,
|
|
2130
|
-
* source index: create-only and CAS rows, keyed by generation) and on the accepted-row store
|
|
2131
|
-
* (create-only, keyed by the client's token); `STREAM.INFO` on both, the bind-time shape check;
|
|
2132
|
-
* the leader-served point read on the evidence store; and the ordered `keys()` walk a source
|
|
2133
|
-
* retirement enumerates the reverse index with.
|
|
2134
|
-
* NAMED RESIDUAL (the contract's section 8): this profile holds a write and a raw read on ONE
|
|
2135
|
-
* stream, the pairing no peer-held profile may hold, so it is never issuable to a peer. */
|
|
2136
|
-
function issuerPermissions(space, pr) {
|
|
2137
|
-
const ISSUED = `KV_${issuedBucket(space)}`;
|
|
2138
|
-
return {
|
|
2139
|
-
pub: {
|
|
2140
|
-
allow: [
|
|
2141
|
-
"$JS.API.INFO",
|
|
2142
|
-
`$KV.${issuedBucket(space)}.>`,
|
|
2143
|
-
`$KV.${acceptedBucket(space)}.>`,
|
|
2144
|
-
// A user-auth connection's renewal finds the accepted row its nonce names (SPEC 13.15).
|
|
2145
|
-
`$JS.API.DIRECT.GET.KV_${acceptedBucket(space)}.$KV.${acceptedBucket(space)}.>`,
|
|
2146
|
-
`$JS.API.STREAM.INFO.${ISSUED}`,
|
|
2147
|
-
`$JS.API.STREAM.INFO.KV_${acceptedBucket(space)}`,
|
|
2148
|
-
`$JS.API.STREAM.MSG.GET.${ISSUED}`,
|
|
2149
|
-
// Source liveness: the leader-served point read of a static incarnation's issuance gate on
|
|
2150
|
-
// the auth store (body-selected, stream-wide: the same named residual every records
|
|
2151
|
-
// reader accepts). No auth-store WRITE of any shape.
|
|
2152
|
-
`$JS.API.STREAM.MSG.GET.KV_${epAuthBucket(space)}`,
|
|
2153
|
-
`$JS.API.CONSUMER.CREATE.${ISSUED}.>`,
|
|
2154
|
-
`$JS.API.CONSUMER.INFO.${ISSUED}.>`,
|
|
2155
|
-
`$JS.API.CONSUMER.DELETE.${ISSUED}.>`,
|
|
2156
|
-
"$JS.FC.>",
|
|
2157
|
-
],
|
|
2158
|
-
},
|
|
2159
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2160
|
-
};
|
|
2161
|
-
}
|
|
2162
|
-
/** The REGISTRY READER permission set (SPEC 13.20). The evidence store's `STREAM.MSG.GET` is
|
|
2163
|
-
* stream-scoped because the key rides the request body: NAMED RESIDUAL, the holder can read every
|
|
2164
|
-
* recorded ceiling in the space, so this credential is never a peer's. The records reads are the
|
|
2165
|
-
* key list and the per-key `svc` spec/status Direct Get, no stream-wide read; contract artifacts
|
|
2166
|
-
* ride the agent's subject-scoped fetch row. No write of any shape. */
|
|
2167
|
-
function registryReaderPermissions(space, pr) {
|
|
2168
|
-
const ISSUED = `KV_${issuedBucket(space)}`;
|
|
2169
|
-
const REC = recordsBucket(space);
|
|
2170
|
-
return {
|
|
2171
|
-
pub: {
|
|
2172
|
-
allow: [
|
|
2173
|
-
`$JS.API.STREAM.INFO.${ISSUED}`,
|
|
2174
|
-
`$JS.API.STREAM.MSG.GET.${ISSUED}`,
|
|
2175
|
-
`$JS.API.STREAM.INFO.KV_${REC}`,
|
|
2176
|
-
`$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.*.*.spec`,
|
|
2177
|
-
`$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.*.*.status`,
|
|
2178
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
|
|
2179
|
-
],
|
|
2180
|
-
},
|
|
2181
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2182
|
-
};
|
|
2183
|
-
}
|
|
2184
|
-
/** The RUN ADMITTER permission set (SPEC 14.8): exactly ONE run's admission record and
|
|
2185
|
-
* revocation marker on the admission store (both create-only), plus the leader-served read the
|
|
2186
|
-
* create-before-read and the marker's own re-read ride. No other run's keys, no other store. */
|
|
2187
|
-
function runAdmitterPermissions(space, pr, pin) {
|
|
2188
|
-
const bucket = admissionBucket(space);
|
|
2189
|
-
return {
|
|
2190
|
-
pub: {
|
|
2191
|
-
allow: [
|
|
2192
|
-
"$JS.API.INFO",
|
|
2193
|
-
`$KV.${bucket}.${admissionKey(pin.endpoint, pin.runId)}`,
|
|
2194
|
-
`$KV.${bucket}.${revocationKey(pin.endpoint, pin.runId)}`,
|
|
2195
|
-
...(pin.submission ? [`$KV.${bucket}.${runSubmissionKey(pin.endpoint, pin.submission.caller, pin.submission.id)}`] : []),
|
|
2196
|
-
`$JS.API.STREAM.MSG.GET.KV_${bucket}`,
|
|
2197
|
-
],
|
|
2198
|
-
},
|
|
2199
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2200
|
-
};
|
|
2201
|
-
}
|
|
2202
|
-
/** The ephemeral, LIFECYCLE-PINNED §13.1 state-write permission set for the STATIC manager's
|
|
2203
|
-
* lifecycle executor. One credential per lifecycle OPERATION (activation, terminal,
|
|
2204
|
-
* renewal ledger append): every grant names exactly ONE incarnation's keys — the alias head,
|
|
2205
|
-
* the uid reservation, the manager slot row, the issuance gate, and the `cred.<uid>.>` ledger
|
|
2206
|
-
* family — so a leaked executor cred can move one incarnation's state machine and nothing else.
|
|
2207
|
-
*
|
|
2208
|
-
* Reads: records reads ride the keyed Direct Get form (the key is ON the subject, so the read
|
|
2209
|
-
* grant stays key-pinned); the auth store is leader-served (`allow_direct=false`), so its reads
|
|
2210
|
-
* are body-selected `STREAM.MSG.GET` — stream-scoped, NOT key-scoped (the requested key rides
|
|
2211
|
-
* the PAYLOAD, which a subject grant cannot see). NAMED RESIDUAL: for its one-shot lifetime the
|
|
2212
|
-
* executor can READ (never write) other rows in the auth store. */
|
|
2213
|
-
function lifecycleExecutorPermissions(space, pr, pin) {
|
|
2214
|
-
const REC = recordsBucket(space), AUTH = epAuthBucket(space);
|
|
2215
|
-
// ALL keys DERIVED here from the pin coordinates — the slot key is `staticSlotKey(owner, alias)`,
|
|
2216
|
-
// NOT a caller-supplied literal, so a mis-constructed pin can only ever name ONE coherent
|
|
2217
|
-
// incarnation's rows (guard the core: the profile enforces the "one incarnation" promise, it
|
|
2218
|
-
// does not merely assert it). The builders throw on any non-KV-safe segment.
|
|
2219
|
-
const recordKeys = [
|
|
2220
|
-
lifecycleHeadKey(pin.owner, pin.actor), uidReservationKey(pin.lifecycleUid), staticSlotKey(pin.owner, pin.alias),
|
|
2221
|
-
recordSpecKey(RECORD_KINDS.lifecycle, [pin.owner, pin.actor, pin.lifecycleUid]),
|
|
2222
|
-
];
|
|
2223
|
-
return {
|
|
2224
|
-
pub: {
|
|
2225
|
-
allow: [
|
|
2226
|
-
"$JS.API.INFO",
|
|
2227
|
-
// Records-store CAS writes — the value-publish carries the key on the subject, so each
|
|
2228
|
-
// grant names exactly one of this incarnation's keys.
|
|
2229
|
-
...recordKeys.map((k) => `$KV.${REC}.${k}`),
|
|
2230
|
-
// Auth-store CAS writes — this incarnation's gate + its cred-ledger family (renewals
|
|
2231
|
-
// append rows here; the terminal's revoke CASes them).
|
|
2232
|
-
`$KV.${AUTH}.${issuanceGateKey(pin.lifecycleUid)}`,
|
|
2233
|
-
`$KV.${AUTH}.cred.${pin.lifecycleUid}.>`,
|
|
2234
|
-
// Keyed Direct Get reads of the same records keys (key-pinned) for direct-aware read
|
|
2235
|
-
// paths, PLUS the leader-served `STREAM.MSG.GET` the lazily-bound KV client actually
|
|
2236
|
-
// uses — stream-scoped, NOT key-scoped (the requested key rides the PAYLOAD, which a
|
|
2237
|
-
// subject grant cannot see). NAMED RESIDUAL: for its one-shot lifetime the executor can
|
|
2238
|
-
// READ (never write) other rows in BOTH authority stores — lifecycle metadata, no
|
|
2239
|
-
// secrets; every WRITE stays key-pinned above.
|
|
2240
|
-
...recordKeys.map((k) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${k}`),
|
|
2241
|
-
`$JS.API.STREAM.MSG.GET.KV_${REC}`,
|
|
2242
|
-
`$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
|
|
2243
|
-
],
|
|
2244
|
-
},
|
|
2245
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2246
|
-
};
|
|
2247
|
-
}
|
|
2248
|
-
/** The SELF-MEDIATED goal-writer profile (spawn-as-action): exactly
|
|
2249
|
-
* {@link goalWriterGrants} for ITS endpoint — the goal bind + terminal facts, the goal-record KV
|
|
2250
|
-
* writes, and the leader-served fencing reads — plus the connection-scoped reply inbox. Disjoint
|
|
2251
|
-
* from the endpoint's serve credential: a serve connection carries none of these rows, so it
|
|
2252
|
-
* is broker-denied every goal write. */
|
|
2253
|
-
function goalWriterPermissions(space, pr, pin) {
|
|
2254
|
-
const g = goalWriterGrants(space, pin.endpoint, pr.connId);
|
|
2255
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
2256
|
-
}
|
|
2257
|
-
/** The console/CLI per-session CALLER rows: RAILS-ONLY for ONE §13.6 session — pub the
|
|
2258
|
-
* session's epoch-pinned `in` rail, sub its `out` rail plus the caller's own reply inbox, and
|
|
2259
|
-
* NOTHING else. Deliberately NO KV, NO JetStream API, NO store: the caller drives the terminal over
|
|
2260
|
-
* the two core-only eps subjects and never reads the session ledger, so there is no subject-blind
|
|
2261
|
-
* store read to widen (SPEC §13.9). The endpoint+sessionId+epoch pin the EXACT pair, so a cred for
|
|
2262
|
-
* session A authorizes nothing of session B (no wildcard). `epsSubject` validates every token, so a
|
|
2263
|
-
* malformed coordinate refuses at the mint rather than emitting a broadened subject. */
|
|
2264
|
-
function sessionCallerPermissions(space, pr, pin) {
|
|
2265
|
-
if (!pin)
|
|
2266
|
-
throw new Error('permissionsFor: "session-caller" requires opts.sessionCaller ({endpoint, sessionId, epoch}) - the ONE session\'s rails this cred may use');
|
|
2267
|
-
return {
|
|
2268
|
-
pub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "in")] },
|
|
2269
|
-
sub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "out"), `_INBOX_${pr.connId}.>`] },
|
|
2270
|
-
};
|
|
2271
|
-
}
|
|
2272
|
-
/** The own-DM reader rows (#4189): CONSUMER.INFO and MSG.NEXT on the principal's own
|
|
2273
|
-
* lifecycle-keyed `dm_` durable, its `$JS.ACK` subtree, and the connection inbox. Nothing else:
|
|
2274
|
-
* no publish of any message, no CONSUMER.CREATE (the durable is provisioned, never created), no
|
|
2275
|
-
* `$JS.API.INFO`, no STREAM.INFO, no presence, channel, CHAT or `dlv_` row. It is exactly what
|
|
2276
|
-
* `EndpointOptions.dmOnly` sends. */
|
|
2277
|
-
function dmReaderPermissions(space, pr) {
|
|
2278
|
-
if (!pr.lifecycleUid)
|
|
2279
|
-
throw new Error('permissionsFor(dm-reader): a lifecycleUid is required - the dm_ durable name is lifecycle-keyed (SPEC 13.1)');
|
|
2280
|
-
const DM = dmStream(space), dmD = dmDurable(pr.owner, pr.actor, assertLifecycleToken(pr.lifecycleUid));
|
|
2281
|
-
return {
|
|
2282
|
-
pub: { allow: [`$JS.API.CONSUMER.INFO.${DM}.${dmD}`, `$JS.API.CONSUMER.MSG.NEXT.${DM}.${dmD}`, `$JS.ACK.${DM}.${dmD}.>`] },
|
|
2283
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2284
|
-
};
|
|
2285
|
-
}
|
|
2286
|
-
/** The manager's per-session SERVING rows: the EXACT mirror of
|
|
2287
|
-
* {@link sessionCallerPermissions} with the directions swapped — sub the ONE session's epoch-pinned
|
|
2288
|
-
* `in` rail (caller→serving), pub its `out` rail (serving→caller), plus the connection-scoped reply
|
|
2289
|
-
* inbox, and NOTHING else. Same asymmetry §13.6 states: "the caller publishes `in` and subscribes
|
|
2290
|
-
* `out`; the serving instance the reverse".
|
|
2291
|
-
*
|
|
2292
|
-
* Deliberately NO KV and NO JetStream API — not even the session ledger. The serving side drives
|
|
2293
|
-
* bytes; the ledger is the standing `session-ledger` credential's, on a different connection. That
|
|
2294
|
-
* separation is what lets this credential be one-shot and die with its session while the durable
|
|
2295
|
-
* revocation authority outlives it (§13.6).
|
|
2296
|
-
*
|
|
2297
|
-
* This REPLACES a standing writer that held `eps.<endpoint>.*.<epoch>.{in,out}` and so could read
|
|
2298
|
-
* and write every live session's bytes at its epoch. The pin makes a credential for session A
|
|
2299
|
-
* authorize nothing of session B, and `epsSubject` validates every token, so a malformed
|
|
2300
|
-
* coordinate refuses at the mint rather than emitting a broadened subject. */
|
|
2301
|
-
function sessionServingPermissions(space, pr, pin) {
|
|
2302
|
-
if (!pin)
|
|
2303
|
-
throw new Error('permissionsFor: "session-serving" requires opts.sessionServing ({endpoint, sessionId, epoch}) - the ONE session\'s rails this cred may serve');
|
|
2304
|
-
return {
|
|
2305
|
-
pub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "out")] },
|
|
2306
|
-
sub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "in"), `_INBOX_${pr.connId}.>`] },
|
|
2307
|
-
};
|
|
2308
|
-
}
|
|
2309
|
-
/** The manager's SESSION-LEDGER rows: the DEDICATED sessions-bucket rows and nothing
|
|
2310
|
-
* else — no session rail of any shape. Needs no pin: the grant carries no endpoint, epoch, or
|
|
2311
|
-
* session component, because §13.6's durable revocation authority is per-space, not per-session
|
|
2312
|
-
* (it must still be able to resolve and revoke a row after the endpoint that served it is gone).
|
|
2313
|
-
* {@link sessionLedgerGrants} carries the row rationale, the §13.9 subject-blindness confinement,
|
|
2314
|
-
* and the named `session.*` breadth residual. */
|
|
2315
|
-
function sessionLedgerPermissions(space, pr) {
|
|
2316
|
-
const g = sessionLedgerGrants(space, pr.connId);
|
|
2317
|
-
return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
|
|
2318
|
-
}
|
|
2319
|
-
/** The ephemeral, ENDPOINT-INSTANCE-PINNED endpoint-serve executor permission set:
|
|
2320
|
-
* the manager mints this per registration/serve-mint op and drives the endpoint
|
|
2321
|
-
* registration barrier's `epgate` CAS + the mint fence's `epcred` stage/revoke THROUGH it — never
|
|
2322
|
-
* its standing seed/supervisor connection. Every
|
|
2323
|
-
* WRITE is key-pinned to exactly ONE (endpoint, instanceId): the gate `epgate.<ep>.<iid>`, its
|
|
2324
|
-
* serving ledger family `epcred.<ep>.<iid>.>`, and the registration's two records keys (the
|
|
2325
|
-
* instance's `svc` spec + the endpoint's governance head — `registerServiceInstance` drives the
|
|
2326
|
-
* slot-take/promote over this same connection). A leaked/mis-constructed executor can move exactly
|
|
2327
|
-
* one endpoint instance's serve state and nothing else. The auth store is `allow_direct=false`, so
|
|
2328
|
-
* reads are leader-served `STREAM.MSG.GET` (stream-scoped, NOT key-scoped — the key rides the
|
|
2329
|
-
* payload); enumeration of the epcred family rides an ordered `keys()` consumer. NAMED RESIDUAL:
|
|
2330
|
-
* for its one-shot lifetime the executor can READ (never write) other auth rows — endpoint/
|
|
2331
|
-
* credential metadata, no bearer bytes; every WRITE stays key-pinned. */
|
|
2332
|
-
function endpointServeExecutorPermissions(space, pr, pin) {
|
|
2333
|
-
const AUTH = epAuthBucket(space), REC = recordsBucket(space);
|
|
2334
|
-
// DERIVED from (endpoint, instanceId) via the core builders — never a caller literal.
|
|
2335
|
-
const gateKey = epgateKey(pin.endpoint, pin.instanceId);
|
|
2336
|
-
const credPrefix = epcredFamilyPrefix(pin.endpoint, pin.instanceId);
|
|
2337
|
-
const repairKey = eprepairKey(pin.endpoint, pin.instanceId);
|
|
2338
|
-
// The registration writes this ONE instance's spec key plus the endpoint's governance head
|
|
2339
|
-
// (`registerServiceInstance` PHASE 1/3b: the slot-take + promote ride the SAME executor), and this
|
|
2340
|
-
// instance's own svc STATUS key (the manager writes its CONVERGED `ready` status so it
|
|
2341
|
-
// is a §13.5 scatter member — `freezeExpectedSet` requires a status caught up to the current
|
|
2342
|
-
// registration; the write is epoch-fenced by `writeServiceStatus`).
|
|
2343
|
-
const recordKeys = [
|
|
2344
|
-
recordSpecKey(RECORD_KINDS.svc, [pin.endpoint, assertLifecycleToken(pin.instanceId, "instanceId")]),
|
|
2345
|
-
recordStatusKey(RECORD_KINDS.svc, [pin.endpoint, assertLifecycleToken(pin.instanceId, "instanceId")]),
|
|
2346
|
-
recordAtomicKey(GOVERN_HEAD, [pin.endpoint]),
|
|
2347
|
-
];
|
|
2348
|
-
return {
|
|
2349
|
-
pub: {
|
|
2350
|
-
allow: [
|
|
2351
|
-
"$JS.API.INFO",
|
|
2352
|
-
// The key-pinned WRITE grants: the gate (provision create + barrier freeze/reopen CAS),
|
|
2353
|
-
// the serving ledger family (mint-fence stage + barrier revoke), and the registration's
|
|
2354
|
-
// two records-store keys (spec CAS + governance slot/promote). The value-publish carries
|
|
2355
|
-
// the key on the subject, so each grant names exactly this instance's keys.
|
|
2356
|
-
`$KV.${AUTH}.${gateKey}`,
|
|
2357
|
-
`$KV.${AUTH}.${repairKey}`,
|
|
2358
|
-
`$KV.${AUTH}.${credPrefix}.>`,
|
|
2359
|
-
...recordKeys.map((k) => `$KV.${REC}.${k}`),
|
|
2360
|
-
// §13.7 contract-artifact publication: the registration publishes the
|
|
2361
|
-
// endpoint's cluster document, closure manifests, and schema roots to the EPC store so
|
|
2362
|
-
// callers can fetch-verify-compile the registered digests. A digest subject is a SINGLE
|
|
2363
|
-
// hex token (`epc.<64hex>`), so the grant is the single-token `epc.*` form (matching
|
|
2364
|
-
// `contractPublisherGrants`), never the multi-token `epc.>`. Digest subjects cannot be
|
|
2365
|
-
// key-pinned pre-mint; the store's SHAPE is the defense (ensureContractStore): a digest
|
|
2366
|
-
// subject holds exactly one broker-immutable message (max_msgs_per_subject:1 +
|
|
2367
|
-
// discard-new-per-subject REJECTS a second publish regardless of the create-only header, so
|
|
2368
|
-
// a grant-holder CANNOT append a shadow over a published artifact), deny_delete/deny_purge
|
|
2369
|
-
// keep that message, and content addressing (verify-on-read, create-only-winner fallback)
|
|
2370
|
-
// makes a wrong-subject write unservable. NAMED RESIDUAL: for its one-shot lifetime the
|
|
2371
|
-
// executor can publish NEW digest-addressed artifacts at previously-unused subjects (a
|
|
2372
|
-
// bounded storage flood; unreferenced artifacts carry no authority) — it can NOT overwrite,
|
|
2373
|
-
// shadow, or replace an existing one.
|
|
2374
|
-
`${spacePrefix(space)}.epc.*`,
|
|
2375
|
-
// The lost-CAS verify-read `publishContractArtifact` runs when a re-publish (every re-up /
|
|
2376
|
-
// restart against an existing store) loses the create-only CAS: it fetches the recorded
|
|
2377
|
-
// artifact to confirm the idempotent no-op. BOTH Direct Get forms — the subject-scoped
|
|
2378
|
-
// `last_by_subj` (the fast path) and the bare stream form (the create-only-winner
|
|
2379
|
-
// `next_by_subj` fallback) — so the publish path never dies on a broker denial regardless
|
|
2380
|
-
// of stream config. Without this the manager exits on its SECOND boot (the tester's
|
|
2381
|
-
// upgrade-path regression). Reads public content-addressed artifacts only.
|
|
2382
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
|
|
2383
|
-
`$JS.API.DIRECT.GET.${epcStreamName(space)}`,
|
|
2384
|
-
// Leader-served reads (the auth store is allow_direct=false): stream-scoped MSG.GET (the
|
|
2385
|
-
// barrier/fence read the gate + each epcred row), plus the ordered consumer the epcred
|
|
2386
|
-
// `keys()` enumeration binds. The records store IS direct-servable, so its reads add the
|
|
2387
|
-
// key-pinned DIRECT.GET forms beside the leader-served fallback. NAMED RESIDUAL: reads
|
|
2388
|
-
// any row in both stores for its one-shot lifetime (metadata, no bearer bytes).
|
|
2389
|
-
`$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
|
|
2390
|
-
`$JS.API.CONSUMER.CREATE.KV_${AUTH}.>`,
|
|
2391
|
-
`$JS.API.CONSUMER.INFO.KV_${AUTH}.>`,
|
|
2392
|
-
`$JS.API.CONSUMER.DELETE.KV_${AUTH}.>`,
|
|
2393
|
-
// Ordered value scans acknowledge flow control only for this authorized auth stream.
|
|
2394
|
-
`$JS.FC.KV_${AUTH}.>`,
|
|
2395
|
-
...recordKeys.map((k) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${k}`),
|
|
2396
|
-
`$JS.API.STREAM.MSG.GET.KV_${REC}`,
|
|
2397
|
-
],
|
|
2398
|
-
},
|
|
2399
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2400
|
-
};
|
|
2401
|
-
}
|
|
2402
|
-
/** The ephemeral, TARGET-PINNED DEPROVISIONER permission set — the teardown counterpart
|
|
2403
|
-
* to {@link provisionerPermissions}, minted per departed agent inside the manager's `deprovision` tail
|
|
2404
|
-
* (`withProvisioner`-style: a fresh scoped cred per teardown is cheap). It deletes exactly the
|
|
2405
|
-
* dev/static principal footprint the provisioner created for ONE agent: that agent's two bind-only
|
|
2406
|
-
* durables (`dm_local-<actor>`, `dlv_local-<actor>`) and its read-ACL row — pinned BY NAME to the target
|
|
2407
|
-
* actor under {@link DEV_OWNER}, so a leaked deprovisioner cred can tear down that one already-dead
|
|
2408
|
-
* agent and NOTHING else.
|
|
2409
|
-
*
|
|
2410
|
-
* Deliberately NOT granted (least-privilege / correctness): the role-SHARED `svc_<role>` TASK durable
|
|
2411
|
-
* (one consumer for ALL agents of a role — deleting it on one agent's exit would break its siblings; it
|
|
2412
|
-
* lives until space teardown), any peer's `dm_`/`dlv_`/ACL (the grants are target-name-pinned, never
|
|
2413
|
-
* `.>`), any MSG.NEXT/MSG.GET/ACK (it deletes mailboxes, never reads a body), and any STREAM
|
|
2414
|
-
* DELETE/PURGE (it removes per-agent consumers, never a stream). The `chathist_<id>` history consumers
|
|
2415
|
-
* need no grant here — they are ephemeral (`mem_storage`, 30s inactive threshold) and agent-deleted
|
|
2416
|
-
* after each read, so they self-clean on the agent's disconnect.
|
|
2417
|
-
*
|
|
2418
|
-
* Blast radius of a leaked cred (minted for target T): it can delete T's `dm_local-<T>`/`dlv_local-<T>`
|
|
2419
|
-
* durables + purge T's ACL row — a denial-of-DELIVERY for T (broken DM/DLV bind + the reader DEFERs on
|
|
2420
|
-
* the absent ACL) if fired while T is still alive. It CANNOT read T's bodies, impersonate T, reach any peer, or
|
|
2421
|
-
* delete a stream — and it is ephemeral (one per-exit teardown, minted then dropped). Contained and
|
|
2422
|
-
* recoverable (re-provision T). */
|
|
2423
|
-
function deprovisionerPermissions(space, pr, deprovisionTarget) {
|
|
2424
|
-
const DM = dmStream(space), DLV = dlvStream(space);
|
|
2425
|
-
const t = deprovisionTargetPrincipal(deprovisionTarget);
|
|
2426
|
-
const target = principalKey(t.owner, t.actor);
|
|
2427
|
-
return {
|
|
2428
|
-
pub: {
|
|
2429
|
-
allow: [
|
|
2430
|
-
"$JS.API.INFO", // jetstreamManager bootstrap
|
|
2431
|
-
// Delete the target LIFECYCLE's two bind-only durables BY EXACT NAME — no `.>`, no cross-agent
|
|
2432
|
-
// reach, and no reach into a same-alias successor: its names carry a different uid, so a
|
|
2433
|
-
// replayed teardown is broker-DENIED there (SPEC 13.1 / Appendix "deprovisioner").
|
|
2434
|
-
`$JS.API.CONSUMER.DELETE.${DM}.${dmDurable(t.owner, t.actor, t.lifecycleUid)}`,
|
|
2435
|
-
`$JS.API.CONSUMER.DELETE.${DLV}.${dlvDurable(t.owner, t.actor, t.lifecycleUid)}`,
|
|
2436
|
-
`$JS.API.CONSUMER.INFO.${DM}.${dmDurable(t.owner, t.actor, t.lifecycleUid)}`,
|
|
2437
|
-
`$JS.API.CONSUMER.INFO.${DLV}.${dlvDurable(t.owner, t.actor, t.lifecycleUid)}`,
|
|
2438
|
-
// Purge the target lifecycle's read-ACL row (own-target exact key only — the reader then treats
|
|
2439
|
-
// it as an unknown owner). `kvm.open` binds the pre-created bucket; the purge rides
|
|
2440
|
-
// `$KV.<aclBucket>.<key>`.
|
|
2441
|
-
`$JS.API.STREAM.INFO.KV_${aclBucket(space)}`,
|
|
2442
|
-
`$JS.API.DIRECT.GET.KV_${aclBucket(space)}.$KV.${aclBucket(space)}.${aclKey(target.key, t.lifecycleUid)}`,
|
|
2443
|
-
`$KV.${aclBucket(space)}.${aclKey(target.key, t.lifecycleUid)}`,
|
|
2444
|
-
// Purge the target lifecycle's durable membership rows, one exact key per named concrete
|
|
2445
|
-
// channel or family (a family's `>` is `=` in the key, so no grant here is a wildcard). The key
|
|
2446
|
-
// embeds the uid, so a successor's row is unreachable by name.
|
|
2447
|
-
...(t.memberChannels.length > 0 ? [`$JS.API.STREAM.INFO.KV_${membersBucket(space)}`] : []),
|
|
2448
|
-
...t.memberChannels.map((ch) => `$JS.API.DIRECT.GET.KV_${membersBucket(space)}.$KV.${membersBucket(space)}.${memberKey(ch, target.key, t.lifecycleUid)}`),
|
|
2449
|
-
...t.memberChannels.map((ch) => `$KV.${membersBucket(space)}.${memberKey(ch, target.key, t.lifecycleUid)}`),
|
|
2450
|
-
],
|
|
2451
|
-
},
|
|
2452
|
-
// Replies only: the CONSUMER.DELETE PubAcks + KV purge ack land on the per-connection inbox. NO chat/DM/ctl
|
|
2453
|
-
// subscription — the deprovisioner serves nothing and reads no feed.
|
|
2454
|
-
sub: { allow: [`_INBOX_${pr.connId}.>`] },
|
|
2455
|
-
};
|
|
2456
|
-
}
|
|
2457
|
-
/** The scoped `delivery` daemon permission set (server-side Plane-3 infra; NEVER allow-all, never
|
|
2458
|
-
* minted for an agent — `cotal mint` excludes it, like `manager`). Least-privilege: exactly what the
|
|
2459
|
-
* fan-out writer + trusted reader + activation catch-up + membership/ACL reads + members-KV writes +
|
|
2460
|
-
* the lease + the `ctl.delivery` control service touch. `sub.allow` is the per-identity inbox (all JS
|
|
2461
|
-
* pull delivery / KV-watch / request replies land there) PLUS the `ctl.delivery` control subtree it
|
|
2462
|
-
* serves; ALL stream/KV reads ride the JS API (publishes), so there is NO native `chat`/`dinbox`/`dlv`
|
|
2463
|
-
* subscription — a leaked cred can't natively sniff the mixed pre-auth store. Honest blast radius
|
|
2464
|
-
* (delivery-daemon.mdx): it can write any owner's `dlv` (the post-auth store agents trust); the future
|
|
2465
|
-
* fan-out/reader cred split bounds that. */
|
|
2466
|
-
function deliveryPermissions(space, pr) {
|
|
2467
|
-
const p = spacePrefix(space);
|
|
2468
|
-
const CHAT = chatStream(space), INBOX = inboxStream(space), DLV = dlvStream(space);
|
|
2469
|
-
const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
|
|
2470
|
-
const MKV = `KV_${membersBucket(space)}`, AKV = `KV_${aclBucket(space)}`, DKV = `KV_${deliveryBucket(space)}`;
|
|
2471
|
-
const TASK = taskStream(space), AKVR = `KV_${anycastBucket(space)}`;
|
|
2472
|
-
const kvRead = (bucket) => [
|
|
2473
|
-
`$JS.API.STREAM.INFO.${bucket}`,
|
|
2474
|
-
`$JS.API.STREAM.MSG.GET.${bucket}`, // kv.get
|
|
2475
|
-
`$JS.API.CONSUMER.CREATE.${bucket}.>`, // kv.watch ordered consumer
|
|
2476
|
-
`$JS.API.CONSUMER.INFO.${bucket}.>`,
|
|
2477
|
-
`$JS.API.CONSUMER.DELETE.${bucket}.>`,
|
|
2478
|
-
];
|
|
2479
|
-
const pub = [
|
|
2480
|
-
"$JS.API.INFO",
|
|
2481
|
-
`$JS.API.STREAM.INFO.${CHAT}`, `$JS.API.STREAM.INFO.${INBOX}`, `$JS.API.STREAM.INFO.${DLV}`,
|
|
2482
|
-
// Fan-out durable + activation-catch-up ephemerals live on CHAT — the daemon legitimately reads ALL
|
|
2483
|
-
// chat (the fan-out consumes the whole stream), so a stream-wide CHAT consumer grant is no
|
|
2484
|
-
// escalation. The catch-up ephemeral names (`cu_<owner>_<gen>`) are dynamic, so they can't be
|
|
2485
|
-
// name-pinned; CHAT-wide is correct here.
|
|
2486
|
-
//
|
|
2487
|
-
// BOTH forms, and the bare one is not redundant: a create carrying `filter_subjects` cannot encode
|
|
2488
|
-
// its filter in the subject, so the client publishes to the BARE `…CREATE.<CHAT>` while a named
|
|
2489
|
-
// consumer goes to the `.>` form. The mediated history read (`readHistory`) builds exactly that
|
|
2490
|
-
// multi-filter ephemeral, and with only the `.>` grant it fails with a Permissions Violation on the
|
|
2491
|
-
// bare subject — measured, not predicted. The observer profile already carries both for the same
|
|
2492
|
-
// reason. Grants the daemon nothing new in substance: it may already create any named consumer on
|
|
2493
|
-
// this stream and already reads all of it.
|
|
2494
|
-
`$JS.API.CONSUMER.CREATE.${CHAT}`,
|
|
2495
|
-
`$JS.API.CONSUMER.CREATE.${CHAT}.>`,
|
|
2496
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${CHAT}.>`,
|
|
2497
|
-
`$JS.API.CONSUMER.INFO.${CHAT}.>`,
|
|
2498
|
-
`$JS.API.CONSUMER.MSG.NEXT.${CHAT}.>`,
|
|
2499
|
-
`$JS.API.CONSUMER.DELETE.${CHAT}.>`,
|
|
2500
|
-
`$JS.ACK.${CHAT}.>`,
|
|
2501
|
-
// Trusted reader on INBOX — NAME-PINNED to the single `reader` durable (the meaningful confinement:
|
|
2502
|
-
// no arbitrary INBOX consumer create against the mixed pre-auth store).
|
|
2503
|
-
`$JS.API.CONSUMER.CREATE.${INBOX}.${INBOX_READER_DURABLE}.>`,
|
|
2504
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${INBOX}.${INBOX_READER_DURABLE}`,
|
|
2505
|
-
`$JS.API.CONSUMER.INFO.${INBOX}.${INBOX_READER_DURABLE}`,
|
|
2506
|
-
`$JS.API.CONSUMER.MSG.NEXT.${INBOX}.${INBOX_READER_DURABLE}`,
|
|
2507
|
-
`$JS.API.CONSUMER.DELETE.${INBOX}.${INBOX_READER_DURABLE}`,
|
|
2508
|
-
`$JS.ACK.${INBOX}.${INBOX_READER_DURABLE}.>`,
|
|
2509
|
-
// The reader removes an entry addressed to a retired lifecycle (its ACL row is tombstoned), so the
|
|
2510
|
-
// store does not keep what no reader can ever deliver. Nothing new in substance: the reader can
|
|
2511
|
-
// already ack any INBOX entry away.
|
|
2512
|
-
`$JS.API.STREAM.MSG.DELETE.${INBOX}`,
|
|
2513
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
2514
|
-
// Reads: presence (@mention resolve) + channel registry (delivery class) + members + ACL (re-auth).
|
|
2515
|
-
...kvRead(PKV), ...kvRead(CHKV), ...kvRead(MKV), ...kvRead(AKV),
|
|
2516
|
-
// Members-KV WRITE — the daemon is the durable-membership authority (join/leave/activate/catch-up).
|
|
2517
|
-
`$KV.${membersBucket(space)}.>`,
|
|
2518
|
-
// Delivery lease/readiness KV: read the bucket (renew CAS) + write ONLY lease keys. The
|
|
2519
|
-
// CONSUMER.* rows are kv.watch's ordered consumer for the lease-loss watch (#1596) — the same
|
|
2520
|
-
// read axis the other kvRead buckets carry, on the bucket this cred already reads point-wise:
|
|
2521
|
-
// a watch is a READ of the row's changes, never a write. CONSUMER.DELETE rides with it for the
|
|
2522
|
-
// same reason it does on every watched bucket: an ordered consumer rebuilds by deleting its
|
|
2523
|
-
// predecessor, and a refused delete strands consumers on every rebuild (measured on the
|
|
2524
|
-
// presence bucket; the comment there carries the full story).
|
|
2525
|
-
`$JS.API.STREAM.INFO.${DKV}`, `$JS.API.STREAM.MSG.GET.${DKV}`,
|
|
2526
|
-
`$JS.API.CONSUMER.CREATE.${DKV}.>`,
|
|
2527
|
-
`$JS.API.CONSUMER.INFO.${DKV}.>`,
|
|
2528
|
-
`$JS.API.CONSUMER.DELETE.${DKV}.>`,
|
|
2529
|
-
`$KV.${deliveryBucket(space)}.lease.*`,
|
|
2530
|
-
// The timer writer (SPEC 13.2): the daemon hosts the pump that turns `.schedule` requests into
|
|
2531
|
-
// the authoritative `.armed` publishes — without it no workflow pause on the space ever
|
|
2532
|
-
// expires. Its consumer rows are the shared timer-writer grant set; both create forms for the
|
|
2533
|
-
// same reason CHAT carries both (the client picks by whether the create embeds a filter). The
|
|
2534
|
-
// arm itself needs the fence's two leader reads — the `.armed` head on EPT and the checkpoint
|
|
2535
|
-
// status on the records KV — and exactly ONE publish: the `.armed` subject. Never `.fire`
|
|
2536
|
-
// (the broker's own schedule delivery) and never `.schedule` (it consumes those).
|
|
2537
|
-
...timerWriterGrants(space),
|
|
2538
|
-
`$JS.API.CONSUMER.DURABLE.CREATE.${eptReqStreamName(space)}.${timerWriterDurable(space)}`,
|
|
2539
|
-
`$JS.API.STREAM.INFO.${eptReqStreamName(space)}`,
|
|
2540
|
-
`$JS.API.STREAM.INFO.${eptStreamName(space)}`,
|
|
2541
|
-
`$JS.API.STREAM.MSG.GET.${eptStreamName(space)}`,
|
|
2542
|
-
`$JS.API.STREAM.INFO.KV_${recordsBucket(space)}`,
|
|
2543
|
-
`$JS.API.STREAM.MSG.GET.KV_${recordsBucket(space)}`,
|
|
2544
|
-
`${p}.ept.*.*.*.*.armed`,
|
|
2545
|
-
// Plane-3 data writes: dinbox (fan-out target) + dlv (post-auth handoff) for ANY lifecycle — the
|
|
2546
|
-
// identity slots widen to `.*.*.*` (owner+actor+lifecycleUid: dinbox/dlv are per-LIFECYCLE now,
|
|
2547
|
-
// SPEC 13.1; NATS subject arity is exact, so the old two-token form is broker-denied on every
|
|
2548
|
-
// three-token write).
|
|
2549
|
-
`${p}.dinbox.*.*.*`, `${p}.dlv.*.*.*`,
|
|
2550
|
-
// ctl.delivery control REPLIES ONLY (requests arrive on the sub below; the daemon only ever
|
|
2551
|
-
// m.respond()s to a requester's reply subject `ctl.delivery.<owner>.<actor>.reply.<n>`). Scoped to
|
|
2552
|
-
// the `.reply.>` leaf so the daemon can't publish to the request subjects themselves — tighter than a
|
|
2553
|
-
// blanket `ctl.delivery.>` (fact-check precision, review panel). The caller slots widened to `.*.*`.
|
|
2554
|
-
`${p}.ctl.delivery.*.*.reply.>`,
|
|
2555
|
-
// The privileged delivery-admin rail: same replies-only shape. Requests reach the
|
|
2556
|
-
// daemon on the sub below; only the supervisor cred can PUBLISH them (nats-server is the boundary).
|
|
2557
|
-
`${p}.ctl.delivery-admin.*.*.reply.>`,
|
|
2558
|
-
// LIVENESS REPLIES for the DELIVERY plane (#1577) — same replies-only shape as the two control
|
|
2559
|
-
// rails above. The daemon is the only process that can grade its own responder honestly: it
|
|
2560
|
-
// knows its own incarnation, so a predecessor's `ready:true` corpse in the lease classifies as
|
|
2561
|
-
// stale rather than as its own health. Bounded to the `.reply.` leaf, so it cannot publish to
|
|
2562
|
-
// the request subjects and forge a probe from a peer.
|
|
2563
|
-
livenessReplyGrant(space, "delivery"),
|
|
2564
|
-
// Anycast request status (SPEC §8.1). The daemon reads a request at the seq a take, status or
|
|
2565
|
-
// cancel names, and deletes one its sender cancelled while it waited: a read of every request
|
|
2566
|
-
// body in the space and a delete of any of them, both bounded by the take record. It owns the
|
|
2567
|
-
// records bucket, creating it on a mesh that predates it, and lists it for the maintenance pass.
|
|
2568
|
-
// It DMs a request's sender from its own principal only, and answers takes on their bounded
|
|
2569
|
-
// reply leaf.
|
|
2570
|
-
`$JS.API.STREAM.INFO.${TASK}`,
|
|
2571
|
-
`$JS.API.STREAM.MSG.GET.${TASK}`,
|
|
2572
|
-
`$JS.API.STREAM.MSG.DELETE.${TASK}`,
|
|
2573
|
-
`$JS.API.STREAM.CREATE.${AKVR}`,
|
|
2574
|
-
...kvRead(AKVR),
|
|
2575
|
-
`$JS.API.DIRECT.GET.${AKVR}.>`,
|
|
2576
|
-
`$KV.${anycastBucket(space)}.>`,
|
|
2577
|
-
unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a>: a notice to a sender, as itself
|
|
2578
|
-
takeReplyGrant(space),
|
|
2579
|
-
];
|
|
2580
|
-
const sub = [
|
|
2581
|
-
`_INBOX_${pr.connId}.>`,
|
|
2582
|
-
takeServeFilter(space), // serve anycast takes (queue-grouped; role + owner+actor caller slots)
|
|
2583
|
-
`${p}.ctl.delivery.*.*`, // serve the delivery control service (queue-grouped; owner+actor caller slots)
|
|
2584
|
-
`${p}.ctl.delivery-admin.*.*`, // serve the privileged admin rail (reloadCreds; eviction executor next)
|
|
2585
|
-
// Serve the delivery plane's liveness probe (#1577), queue-grouped. Presence-only: the handler
|
|
2586
|
-
// reduces the lease row to one enum before replying, so this subscription lets the daemon ANSWER
|
|
2587
|
-
// a peer without any peer gaining a read of the lease.
|
|
2588
|
-
livenessServeFilter(space, "delivery"),
|
|
2589
|
-
];
|
|
2590
|
-
return { pub: { allow: pub }, sub: { allow: sub } };
|
|
2591
|
-
}
|
|
2592
|
-
/** The scoped DATA-account `membership-rw` permission set (the graph feed's conn B; NEVER allow-all,
|
|
2593
|
-
* never minted for an agent — `cotal mint` excludes it, like `manager`/`delivery`). Least-privilege:
|
|
2594
|
-
* READ the members registry (the durable arm of the merge) + READ/WRITE the one derived membership
|
|
2595
|
-
* bucket, and nothing else. It holds NO chat/DM/anycast/ctl grant and never touches `$SYS` (account
|
|
2596
|
-
* isolation keeps the system-account CONNZ read on the SEPARATE conn-A cred). A leaked conn-B cred can
|
|
2597
|
-
* read durable-membership records and forge the feed — bounded to "dashboard integrity" by the
|
|
2598
|
-
* display-only invariant; it reads no message bodies and admins nothing. */
|
|
2599
|
-
function membershipRwPermissions(space, pr) {
|
|
2600
|
-
const MKV = `KV_${membersBucket(space)}`; // durable arm — read
|
|
2601
|
-
const MEMKV = `KV_${membershipBucket(space)}`; // derived feed — read (diff/prune) + write
|
|
2602
|
-
const kvRead = (bucket) => [
|
|
2603
|
-
`$JS.API.STREAM.INFO.${bucket}`,
|
|
2604
|
-
`$JS.API.STREAM.MSG.GET.${bucket}`, // kv.get
|
|
2605
|
-
`$JS.API.CONSUMER.CREATE.${bucket}.>`, // kv.keys()/kv.watch ordered consumer
|
|
2606
|
-
`$JS.API.CONSUMER.INFO.${bucket}.>`,
|
|
2607
|
-
`$JS.API.CONSUMER.DELETE.${bucket}.>`,
|
|
2608
|
-
];
|
|
2609
|
-
const pub = [
|
|
2610
|
-
"$JS.API.INFO",
|
|
2611
|
-
...kvRead(MKV),
|
|
2612
|
-
...kvRead(MEMKV),
|
|
2613
|
-
`$KV.${membershipBucket(space)}.>`, // write derived feed (kv.put + kv.delete)
|
|
2614
|
-
"$JS.FC.>", // ordered-consumer flow control
|
|
2615
|
-
];
|
|
2616
|
-
return { pub: { allow: pub }, sub: { allow: [`_INBOX_${pr.connId}.>`] } };
|
|
2617
|
-
}
|
|
2618
|
-
/** The scoped SYSTEM-account `membership-observer` permission set (the graph feed's conn A). An EXPLICIT
|
|
2619
|
-
* block is MANDATORY: a system-account user with NO permissions block defaults to ALLOW-ALL = full
|
|
2620
|
-
* `$SYS` = broker admin (verified — pre-flight spike + docs). Least-privilege allowlist:
|
|
2621
|
-
* - **pub:** the account-scoped CONNZ request subject ONLY (not server-wide `PING.CONNZ`, not
|
|
2622
|
-
* `REQ.SERVER.*`/`REQ.CLAIMS.*`).
|
|
2623
|
-
* - **sub:** the scoped reply inbox (`<MEMBERSHIP_INBOX_PREFIX>.>`) + this ONE account's
|
|
2624
|
-
* CONNECT/DISCONNECT events (re-poll triggers) — never `$SYS.ACCOUNT.*.…` (cross-tenant) nor
|
|
2625
|
-
* `$SYS.ACCOUNT.<id>.>` (pulls in SUBSZ/JSZ/purge).
|
|
2626
|
-
* No `$SYS.>` deny that would shadow the allows (deny-beats-allow). A leaked conn-A cred enumerates THIS
|
|
2627
|
-
* account's connections (silent readers + nkeys) and can forge the feed; it reads no bodies, touches no
|
|
2628
|
-
* other account, and admins no server. */
|
|
2629
|
-
function membershipObserverPermissions(accountId) {
|
|
2630
|
-
return {
|
|
2631
|
-
pub: { allow: [connzRequestSubject(accountId)] },
|
|
2632
|
-
sub: {
|
|
2633
|
-
allow: [
|
|
2634
|
-
`${MEMBERSHIP_INBOX_PREFIX}.>`,
|
|
2635
|
-
accountConnectSubject(accountId),
|
|
2636
|
-
accountDisconnectSubject(accountId),
|
|
2637
|
-
],
|
|
2638
|
-
},
|
|
2639
|
-
};
|
|
2640
|
-
}
|
|
2641
|
-
/** Mint the scoped `membership-observer` creds — a SYSTEM-account user (conn A of the graph feed),
|
|
2642
|
-
* signed with the in-memory `auth.sys.signingSeed` from a fresh {@link createSpaceAuth}. THROWS if that
|
|
2643
|
-
* seed is absent (a re-`up` of an already-provisioned space, whose `$SYS` seed was discarded at its
|
|
2644
|
-
* original `up`): the observer can only be minted at the (re-)provision that creates the account — a
|
|
2645
|
-
* documented migration property, not a silent no-op. The CONNZ/event subjects pin the DATA account id
|
|
2646
|
-
* (`auth.account.pub`). Mirrors {@link mintCreds} but issues into the system account. */
|
|
2647
|
-
export async function mintMembershipObserverCreds(auth, identity, opts = {}) {
|
|
2648
|
-
if (!auth.sys.signingSeed)
|
|
2649
|
-
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.");
|
|
2650
|
-
const signer = nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed));
|
|
2651
|
-
const perms = membershipObserverPermissions(auth.account.pub);
|
|
2652
|
-
// Bounded exp: the observer is `rotation-renewed` — it carries the matrix's default
|
|
2653
|
-
// lifetime so a copied cred becomes broker-dead, but there is NO online renewal (the $SYS seed is
|
|
2654
|
-
// gone after `up`); renewal is a coordinated system-account rotation + restart.
|
|
2655
|
-
const validDates = userValidDates("membership-observer", opts);
|
|
2656
|
-
const userJwt = await encodeUser("membership-observer", fromPublic(identity.id), fromPublic(auth.sys.pub), perms, { signer, ...validDates });
|
|
2657
|
-
const creds = fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed)));
|
|
2658
|
-
return new TextDecoder().decode(creds);
|
|
2659
|
-
}
|
|
2660
|
-
/** Host-only read-only census credential. A registered system signer is required; no fallback
|
|
2661
|
-
* to a broader observer or eviction credential. Reissuing with a retained registered signer
|
|
2662
|
-
* needs no broker restart. The helper does not discover or persist that signer.
|
|
2663
|
-
*/
|
|
2664
|
-
export async function mintAccountCensusCreds(auth, identity, opts = {}) {
|
|
2665
|
-
const prefix = accountCensusInboxPrefix(auth.account.pub);
|
|
2666
|
-
if (!auth.sys.signingSeed)
|
|
2667
|
-
throw new Error("account census requires the registered system-account signer");
|
|
2668
|
-
const { exp } = userValidDates("account-census", opts), now = Math.floor(Date.now() / 1000);
|
|
2669
|
-
if (exp === undefined || !Number.isSafeInteger(exp) || exp <= now || exp > now + FIVE_MINUTES)
|
|
2670
|
-
throw new Error("account census requires a bounded future credential expiry");
|
|
2671
|
-
const user = fromSeed(new TextEncoder().encode(identity.seed));
|
|
2672
|
-
if (!isUserNkey(identity.id) || user.getPublicKey() !== identity.id)
|
|
2673
|
-
throw new Error("account census identity does not match its user key");
|
|
2674
|
-
const jwt = await encodeUser("account-census", fromPublic(identity.id), fromPublic(auth.sys.pub), {
|
|
2675
|
-
pub: { allow: [connzRequestSubject(auth.account.pub)] }, sub: { allow: [`${prefix}.>`] },
|
|
2676
|
-
}, { signer: nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed)), exp });
|
|
2677
|
-
if (exp <= Math.floor(Date.now() / 1000))
|
|
2678
|
-
throw new Error("account census credential expired before release");
|
|
2679
|
-
return new TextDecoder().decode(fmtCreds(jwt, user));
|
|
2680
|
-
}
|
|
2681
|
-
/** The KICK-ONLY connection-evictor permission set — a SYSTEM-account user that can do
|
|
2682
|
-
* exactly ONE thing: `$SYS.REQ.SERVER.*.KICK` (disconnect a live client by cid). It CANNOT read
|
|
2683
|
-
* CONNZ (discovery stays on the separate observer cred — never one broad sys user that both
|
|
2684
|
-
* enumerates and kills), touch any other `$SYS` verb, or reach another account's data. A leaked
|
|
2685
|
-
* evictor cred can DoS live connections on this broker (KICK is not account-scoped — the honest
|
|
2686
|
-
* blast radius), which is why it is a HIGH-POWER standing credential: minted only at `up`,
|
|
2687
|
-
* rate-limited + audited by its one caller (the delivery daemon), and its cid/server-id inputs come
|
|
2688
|
-
* only from the observer's own CONNZ scan, never a user-facing API. Wildcard `*` over server id
|
|
2689
|
-
* because a cluster's server ids aren't known at mint time; the scan pins the exact id per KICK. */
|
|
2690
|
-
function connectionEvictorPermissions() {
|
|
2691
|
-
return {
|
|
2692
|
-
pub: { allow: ["$SYS.REQ.SERVER.*.KICK"] },
|
|
2693
|
-
// Request/reply KICK replies land on the client's default inbox; no other subscription — it
|
|
2694
|
-
// serves nothing and reads no feed.
|
|
2695
|
-
sub: { allow: ["_INBOX.>"] },
|
|
2696
|
-
};
|
|
2697
|
-
}
|
|
2698
|
-
/** Mint the scoped `connection-evictor` creds — the kick-only SYSTEM-account user for live
|
|
2699
|
-
* eviction. Same mint-only-at-provision property as the observer (the $SYS seed is in-memory
|
|
2700
|
-
* only), same fail-loud when it's absent. Paired with the observer at `up`. */
|
|
2701
|
-
export async function mintConnectionEvictorCreds(auth, identity, opts = {}) {
|
|
2702
|
-
if (!auth.sys.signingSeed)
|
|
2703
|
-
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.");
|
|
2704
|
-
const signer = nativeNkeySigner(new TextEncoder().encode(auth.sys.signingSeed));
|
|
2705
|
-
// Bounded exp: `rotation-renewed`, same posture as the observer above.
|
|
2706
|
-
const validDates = userValidDates("connection-evictor", opts);
|
|
2707
|
-
const userJwt = await encodeUser("connection-evictor", fromPublic(identity.id), fromPublic(auth.sys.pub), connectionEvictorPermissions(), { signer, ...validDates });
|
|
2708
|
-
const creds = fmtCreds(userJwt, fromSeed(new TextEncoder().encode(identity.seed)));
|
|
2709
|
-
return new TextDecoder().decode(creds);
|
|
2710
|
-
}
|
|
2711
|
-
/**
|
|
2712
|
-
* Render the config for an OPEN (no-auth) broker.
|
|
2713
|
-
*
|
|
2714
|
-
* This exists so that no path reaches a listener without naming its transport. Open mode used to
|
|
2715
|
-
* start nats-server from bare CLI flags (`-js -sd … -p … -a …`) and never called `serverConfig` at
|
|
2716
|
-
* all, which meant the required `transport` union protected the auth path and was silent on the
|
|
2717
|
-
* open one: an operator could pass a cert and key, watch `up` print its normal banner, and get a
|
|
2718
|
-
* cleartext listener. That is the silent downgrade this feature exists to prevent, reachable by
|
|
2719
|
-
* someone who did everything right — so open mode renders a config too.
|
|
2720
|
-
*
|
|
2721
|
-
* It deliberately does NOT reuse `serverConfig`: that renders the operator, system account and
|
|
2722
|
-
* MEMORY resolver, none of which a no-auth broker should carry. What the two share is the thing
|
|
2723
|
-
* that matters — a REQUIRED transport, so the choice cannot be omitted on either path.
|
|
2724
|
-
*
|
|
2725
|
-
* IMPORTANT, and it must be said wherever open-mode TLS is surfaced to an operator: TLS ON AN
|
|
2726
|
-
* OPEN MESH GIVES CONFIDENTIALITY, NOT AUTHENTICATION. It hides traffic from a passive observer.
|
|
2727
|
-
* It does not verify who is connecting, because an open broker has no credentials to check — so
|
|
2728
|
-
* anyone who can reach the port still gets in, encrypted. It is a legitimate configuration for a
|
|
2729
|
-
* mesh crossing a network nobody controls, and it is NOT "secure" in the sense a reader will
|
|
2730
|
-
* assume from seeing `cotals://`. Describe it as the caveat it is rather than as a feature.
|
|
2731
|
-
*/
|
|
2732
|
-
export function openServerConfig(opts) {
|
|
2733
|
-
const port = opts.port ?? 4222;
|
|
2734
|
-
const host = opts.host ?? "127.0.0.1";
|
|
2735
|
-
const logBlock = renderLogBlock("openServerConfig", opts);
|
|
2736
|
-
if (opts.maxPayload !== undefined && (!Number.isSafeInteger(opts.maxPayload) || opts.maxPayload <= 0))
|
|
2737
|
-
throw new Error("openServerConfig: maxPayload must be a positive safe integer of bytes");
|
|
2738
|
-
return `# Generated by \`cotal up\` - do not edit by hand.
|
|
2739
|
-
host: ${host}
|
|
2740
|
-
port: ${port}
|
|
2741
|
-
max_control_line: ${MAX_CONTROL_LINE_BYTES}
|
|
2742
|
-
${opts.maxPayload !== undefined ? `max_payload: ${opts.maxPayload}\n` : ""}${logBlock}${renderTlsBlock(opts.transport)}${renderJetStreamBlock("openServerConfig", opts.storeDir, opts.maxFileStore, opts.brokerVersion)}
|
|
2743
|
-
`;
|
|
2744
|
-
}
|
|
2745
|
-
/** Render native nats-server file logging and rotation directives when requested. */
|
|
2746
|
-
function renderLogBlock(renderer, opts) {
|
|
2747
|
-
if (opts.logFile === undefined && (opts.logfileSizeLimit !== undefined || opts.logfileMaxNum !== undefined))
|
|
2748
|
-
throw new Error(`${renderer}: logfileSizeLimit and logfileMaxNum require logFile`);
|
|
2749
|
-
const lines = [];
|
|
2750
|
-
if (opts.logFile !== undefined) {
|
|
2751
|
-
if (!opts.logFile.trim() || /[\u0000-\u001f\u007f]/u.test(opts.logFile))
|
|
2752
|
-
throw new Error(`${renderer}: logFile must be a non-empty path without control characters`);
|
|
2753
|
-
lines.push(`log_file: ${JSON.stringify(opts.logFile)}`);
|
|
2754
|
-
}
|
|
2755
|
-
if (opts.logfileSizeLimit !== undefined) {
|
|
2756
|
-
if (!Number.isSafeInteger(opts.logfileSizeLimit) || opts.logfileSizeLimit <= 0)
|
|
2757
|
-
throw new Error(`${renderer}: logfileSizeLimit must be a positive integer number of bytes`);
|
|
2758
|
-
lines.push(`logfile_size_limit: ${opts.logfileSizeLimit}`);
|
|
2759
|
-
}
|
|
2760
|
-
if (opts.logfileMaxNum !== undefined) {
|
|
2761
|
-
if (!Number.isSafeInteger(opts.logfileMaxNum) || opts.logfileMaxNum <= 0)
|
|
2762
|
-
throw new Error(`${renderer}: logfileMaxNum must be a positive integer file count`);
|
|
2763
|
-
lines.push(`logfile_max_num: ${opts.logfileMaxNum}`);
|
|
2764
|
-
}
|
|
2765
|
-
return lines.length ? `${lines.join("\n")}\n` : "";
|
|
2766
|
-
}
|
|
2767
|
-
/** The exact `jetstream{}` block both broker renderers write for this store and cap, for a caller
|
|
2768
|
-
* that must find or replace it in a rendered configuration. */
|
|
2769
|
-
export function brokerJetStreamBlock(storeDir, maxFileStore, brokerVersion) {
|
|
2770
|
-
return renderJetStreamBlock("brokerJetStreamBlock", storeDir, maxFileStore, brokerVersion);
|
|
2771
|
-
}
|
|
2772
|
-
/** The shared JetStream block. A set file cap must be positive; brokers 2.15 and later
|
|
2773
|
-
* also need an explicit unlimited default consumer count. */
|
|
2774
|
-
function renderJetStreamBlock(renderer, storeDir, maxFileStore, brokerVersion) {
|
|
2775
|
-
const version = brokerVersion === undefined ? undefined : /^(\d+)\.(\d+)\.\d+/.exec(brokerVersion);
|
|
2776
|
-
if (brokerVersion !== undefined && !version)
|
|
2777
|
-
throw new Error(`${renderer}: invalid brokerVersion ${JSON.stringify(brokerVersion)}`);
|
|
2778
|
-
const limits = version && (Number(version[1]) > 2 || Number(version[1]) === 2 && Number(version[2]) >= 15)
|
|
2779
|
-
? ", limits { default_max_consumers: -1 }" : "";
|
|
2780
|
-
if (maxFileStore === undefined)
|
|
2781
|
-
return `jetstream { store_dir: ${JSON.stringify(storeDir)}${limits} }`;
|
|
2782
|
-
if (!Number.isSafeInteger(maxFileStore) || maxFileStore <= 0)
|
|
2783
|
-
throw new Error(`${renderer}: maxFileStore must be a positive integer number of bytes (got ${String(maxFileStore)})`);
|
|
2784
|
-
return `jetstream { store_dir: ${JSON.stringify(storeDir)}, max_file_store: ${maxFileStore}${limits} }`;
|
|
2785
|
-
}
|
|
2786
|
-
/** The one place a `tls{}` block is produced, shared by both broker renderers.
|
|
2787
|
-
*
|
|
2788
|
-
* `allow_non_tls` is deliberately never emitted. It is a TOP-LEVEL knob (nested inside `tls{}`
|
|
2789
|
-
* nats-server rejects it as an unknown field), and it turns the listener into mixed mode: INFO
|
|
2790
|
-
* then advertises `tls_available` instead of `tls_required`, and a client that declines to
|
|
2791
|
-
* upgrade is served in cleartext — precisely the credential exposure this transport closes.
|
|
2792
|
-
* There is no supported migration mode; enabling TLS is all-or-nothing. */
|
|
2793
|
-
function renderTlsBlock(transport) {
|
|
2794
|
-
if (transport.kind === "plaintext")
|
|
2795
|
-
return "";
|
|
2796
|
-
return `tls {
|
|
2797
|
-
cert_file: ${JSON.stringify(transport.certFile)}
|
|
2798
|
-
key_file: ${JSON.stringify(transport.keyFile)}
|
|
2799
|
-
}
|
|
2800
|
-
`;
|
|
2801
|
-
}
|
|
2802
|
-
function renderAccountResolver(resolver) {
|
|
2803
|
-
if (resolver === undefined)
|
|
2804
|
-
return "resolver: MEMORY\n";
|
|
2805
|
-
const keys = resolver !== null && typeof resolver === "object" && !Array.isArray(resolver) ? Object.keys(resolver) : [];
|
|
2806
|
-
if (keys.length === 1 && keys[0] === "kind" && resolver.kind === "memory")
|
|
2807
|
-
return "resolver: MEMORY\n";
|
|
2808
|
-
if (keys.length !== 4 || resolver.kind !== "full" || !["kind", "directory", "limit", "intervalMs"].every((k) => keys.includes(k)) ||
|
|
2809
|
-
typeof resolver.directory !== "string" || !isAbsolute(resolver.directory) || /[\0\r\n]/.test(resolver.directory) ||
|
|
2810
|
-
!Number.isSafeInteger(resolver.limit) || resolver.limit < 1 ||
|
|
2811
|
-
!Number.isSafeInteger(resolver.intervalMs) || resolver.intervalMs < 1000 || resolver.intervalMs > 86_400_000)
|
|
2812
|
-
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');
|
|
2813
|
-
return `resolver: { type: full, dir: ${JSON.stringify(resolver.directory)}, allow_delete: false, interval: "${resolver.intervalMs}ms", limit: ${resolver.limit} }\n`;
|
|
2814
|
-
}
|
|
2815
|
-
/** Render the `nats-server` config that trusts ONE broker operator and serves N spaces' accounts,
|
|
2816
|
-
* resolved by MEMORY unless {@link AccountResolver} `full` is chosen.
|
|
2817
|
-
*
|
|
2818
|
-
* Broker trust (operator + system account) comes from `broker` and has exactly one owner; the
|
|
2819
|
-
* per-space data accounts are listed in `spaces`. Every space account is asserted to be signed by
|
|
2820
|
-
* THIS broker's operator before it is preloaded: rendering a foreign-signed account would either
|
|
2821
|
-
* refuse broker boot or, worse, advertise a tenant the broker cannot actually authenticate.
|
|
2822
|
-
*
|
|
2823
|
-
* NOTE: the MEMORY resolver is one static whole-broker map, so every mutation rewrites all of
|
|
2824
|
-
* it. With the `full` resolver the preloads seed its directory at boot, and nats-server keeps a
|
|
2825
|
-
* newer pushed claim over an older preload, so a later render does not undo a push. Concurrent
|
|
2826
|
-
* add/remove of spaces needs a broker-authoritative inventory with generation/CAS and atomic
|
|
2827
|
-
* promotion above this function; this renderer is deliberately pure. */
|
|
2828
|
-
export function serverConfig(broker, spaces, opts) {
|
|
2829
|
-
if (!spaces.length)
|
|
2830
|
-
throw new Error("serverConfig: at least one space account is required");
|
|
2831
|
-
for (const s of spaces)
|
|
2832
|
-
assertAccountSignedByBroker(broker, s);
|
|
2833
|
-
const seen = new Map();
|
|
2834
|
-
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" }))]) {
|
|
2835
|
-
const prior = seen.get(s.pub);
|
|
2836
|
-
if (prior)
|
|
2837
|
-
throw new Error(`serverConfig: account ${s.pub} is preloaded twice (${prior} and ${s.what}) - refusing to render an ambiguous resolver`);
|
|
2838
|
-
seen.set(s.pub, s.what);
|
|
2839
|
-
}
|
|
2840
|
-
const port = opts.port ?? 4222;
|
|
2841
|
-
const host = opts.host ?? "127.0.0.1";
|
|
2842
|
-
// The websocket listener: LOCALHOST by default, no_tls for the dev loopback. Emitted only
|
|
2843
|
-
// when wsPort is set — a broker with no console session client opens no ws surface.
|
|
2844
|
-
const websocket = opts.wsPort === undefined ? "" : `websocket {
|
|
2845
|
-
host: ${opts.wsHost ?? "127.0.0.1"}
|
|
2846
|
-
port: ${opts.wsPort}
|
|
2847
|
-
no_tls: true
|
|
2848
|
-
}
|
|
2849
|
-
`;
|
|
2850
|
-
// A minted "agent" carries its full permission allow-list inline in its user JWT, which the
|
|
2851
|
-
// client sends in the CONNECT protocol line. With per-channel + JetStream-API grants that JWT
|
|
2852
|
-
// exceeds the 4 KB default max_control_line at ~2 channels, and the server then silently drops
|
|
2853
|
-
// the connection (the client retries forever — a connect that "hangs"). Raise it to fit a rich
|
|
2854
|
-
// agent JWT — but right-sized, not generous: the CONNECT line is parsed BEFORE auth, so the cap
|
|
2855
|
-
// is a per-connection pre-auth allocation under connection flooding. See MAX_CONTROL_LINE_BYTES
|
|
2856
|
-
// for the derivation; mintCreds/mintPublicUserJwt refuse a JWT that would not fit it BEFORE this
|
|
2857
|
-
// config is ever reached, so a legal credential never depends on this margin alone.
|
|
2858
|
-
const tlsBlock = renderTlsBlock(opts.transport);
|
|
2859
|
-
const logBlock = renderLogBlock("serverConfig", opts);
|
|
2860
|
-
if (opts.maxPayload !== undefined && (!Number.isSafeInteger(opts.maxPayload) || opts.maxPayload <= 0))
|
|
2861
|
-
throw new Error("serverConfig: maxPayload must be a positive safe integer of bytes");
|
|
2862
|
-
if (opts.authTimeout !== undefined && (!Number.isSafeInteger(opts.authTimeout) || opts.authTimeout <= 0))
|
|
2863
|
-
throw new Error("serverConfig: authTimeout must be a positive whole number of seconds");
|
|
2864
|
-
return `# Generated by \`cotal up\` - do not edit by hand.
|
|
2865
|
-
host: ${host}
|
|
2866
|
-
port: ${port}
|
|
2867
|
-
max_control_line: ${MAX_CONTROL_LINE_BYTES}
|
|
2868
|
-
${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)}
|
|
2869
|
-
${websocket}operator: ${broker.operator.jwt}
|
|
2870
|
-
system_account: ${broker.sys.pub}
|
|
2871
|
-
${renderAccountResolver(opts.accountResolver)}resolver_preload: {
|
|
2872
|
-
${spaces.map((s) => ` ${s.account.pub}: ${s.account.jwt}`).join("\n")}
|
|
2873
|
-
${broker.sys.pub}: ${broker.sys.jwt}${(opts.extraAccounts ?? []).map((a) => `\n ${a.pub}: ${a.jwt}`).join("")}
|
|
2874
|
-
}
|
|
2875
|
-
`;
|
|
2876
|
-
}
|
|
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";
|
|
2877
21
|
//# sourceMappingURL=provision.js.map
|