@cotal-ai/core 0.170.0 → 0.171.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/agent-endpoint.d.ts +146 -5
  2. package/dist/agent-endpoint.d.ts.map +1 -1
  3. package/dist/agent-endpoint.js +69 -12
  4. package/dist/agent-endpoint.js.map +1 -1
  5. package/dist/connector-setup.d.ts +2 -0
  6. package/dist/connector-setup.d.ts.map +1 -1
  7. package/dist/endpoint-action.d.ts +2 -2
  8. package/dist/endpoint-action.js +6 -7
  9. package/dist/endpoint-action.js.map +1 -1
  10. package/dist/endpoint-boot-memberships.d.ts +71 -0
  11. package/dist/endpoint-boot-memberships.d.ts.map +1 -0
  12. package/dist/endpoint-boot-memberships.js +119 -0
  13. package/dist/endpoint-boot-memberships.js.map +1 -0
  14. package/dist/endpoint-journal.d.ts.map +1 -1
  15. package/dist/endpoint-journal.js +14 -6
  16. package/dist/endpoint-journal.js.map +1 -1
  17. package/dist/endpoint-provisioning.d.ts +73 -0
  18. package/dist/endpoint-provisioning.d.ts.map +1 -0
  19. package/dist/endpoint-provisioning.js +122 -0
  20. package/dist/endpoint-provisioning.js.map +1 -0
  21. package/dist/endpoint.d.ts +10 -33
  22. package/dist/endpoint.d.ts.map +1 -1
  23. package/dist/endpoint.js +44 -150
  24. package/dist/endpoint.js.map +1 -1
  25. package/dist/provision-permission-builders.d.ts +356 -0
  26. package/dist/provision-permission-builders.d.ts.map +1 -0
  27. package/dist/provision-permission-builders.js +1383 -0
  28. package/dist/provision-permission-builders.js.map +1 -0
  29. package/dist/provision-permissions.d.ts +2 -47
  30. package/dist/provision-permissions.d.ts.map +1 -1
  31. package/dist/provision-permissions.js +9 -1378
  32. package/dist/provision-permissions.js.map +1 -1
  33. package/package.json +1 -1
@@ -1,24 +1,17 @@
1
1
  import { spaceQuiescenceReaderGrants } from "./space-quiescence-resources.js";
2
2
  import { eventPayloadReadSubjects, eventPayloadStream, eventPayloadSubject } from "./event-payloads.js";
3
- import { TTL_RECONCILE_CANARY_KEY, ttlBuckets } from "./streams.js";
4
- import { spaceDeletionStreams } from "./space-deletion-targets.js";
5
- import { BROKER_USER_INFO_SUBJECT } from "./broker-identity.js";
6
- import { spacePrefix, chatSubject, assertValidChannel, principalKey, deprovisionTargetPrincipal, assertInboxConnId, 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, accountConnectSubject, accountDisconnectSubject, MEMBERSHIP_INBOX_PREFIX, INBOX_READER_DURABLE, livenessSubject, livenessServeFilter, livenessReplyGrant, isTransferStream, takeSubject, takeServeFilter, takeReplyGrant, anycastBucket } from "./subjects.js";
3
+ import { spacePrefix, chatSubject, assertValidChannel, principalKey, assertInboxConnId, unicastSubject, anycastSubject, controlServiceSubject, CONTROL_DELIVERY, CONTROL_DELIVERY_ADMIN, chatStream, dmStream, taskStream, dlvStream, chatHistDurable, historyReaderConsumer, HISTORY_READERS, dmDurable, taskDurable, dlvDurable, presenceBucket, presenceKeySubject, channelBucket, assertLifecycleToken, membershipBucket, deliveryBucket, livenessSubject, takeSubject } from "./subjects.js";
7
4
  import { LIVENESS_PLANES } from "./liveness.js";
8
- 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";
9
- import { assertServeGrantMintable } from "./endpoint-service.js";
10
- import { effectsBindGrants, poolOwnerBindGrants, goalWriterGrants, sessionLedgerGrants, epAuthBucket, epcStreamName, endpointPlaneStreamNames, eptReqStreamName, eptStreamName, hardenedAuthorityStreamNames, timerWriterDurable, timerWriterGrants } from "./endpoint-binding.js";
11
- import { epsSubject, epCallerReplyFilter, assertGeneration, isIssuedCaller, AUTH_ENDPOINT, EP_CMD_RETIRE_LIFECYCLE } from "./endpoint-subjects.js";
12
- import { acceptedReadGrant, acceptedBucket, issuedBucket, issuedStoreStreamNames } from "./issued-authority.js";
5
+ import { epCallerGrantRows, epBaselineGrantRows, spawnCallerCapabilities, runCallerCapabilities, epRequestGrantRows, epPrincipalServeGrantRows, epPrincipalOwnerGrantRows, operatorInstrumentCapabilities, epDescribeAllGrantRow } from "./endpoint-grants.js";
6
+ import { epcStreamName } from "./endpoint-binding.js";
7
+ import { epCallerReplyFilter, AUTH_ENDPOINT, EP_CMD_RETIRE_LIFECYCLE } from "./endpoint-subjects.js";
8
+ import { acceptedReadGrant } from "./issued-authority.js";
13
9
  import { REGISTRY_ENDPOINTS_GRANT } from "./registry-contract.js";
14
- import { admissionBucket, admissionKey, revocationKey } from "./run-admission.js";
15
- import { runSubmissionKey } from "./run-submission.js";
16
10
  import { runDriverGrants, runMediatorGrants, runOperatorGrants } from "./run-driver-grants.js";
17
11
  import { transferReaderGrants, transferWriterGrants } from "./transfer.js";
18
- import { recordsBucket, recordSpecKey, recordStatusKey, recordAtomicKey, RECORD_KINDS, GOVERN_HEAD } from "./endpoint-records.js";
19
- import { lifecycleHeadKey, uidReservationKey, issuanceGateKey, staticSlotKey, STATIC_SLOT_PREFIX, epgateKey, epcredFamilyPrefix, eprepairKey } from "./lifecycle-state.js";
20
12
  import { environmentManagerPermissions, isEnvironmentManagerProfile } from "./environment-manager-grants.js";
21
- import { backupProfilePermissions, restoreProfilePermissions, snapshotAckGrant } from "./backup.js";
13
+ import { backupProfilePermissions, restoreProfilePermissions } from "./backup.js";
14
+ import { managerCallerPermissions, supervisorPermissions, remoteManagerPermissions, operatorPermissions, probePermissions, channelWriterPermissions, channelPurgerPermissions, teardownPermissions, membershipStoreRecreatePermissions, issuedStoreRecreatePermissions, controlCallerPermissions, issuedCallerFor, listingGrantRows, deployerPermissions, purgerPermissions, provisionerPermissions, issuerPermissions, registryReaderPermissions, runAdmitterPermissions, lifecycleExecutorPermissions, goalWriterPermissions, sessionCallerPermissions, dmReaderPermissions, sessionServingPermissions, sessionLedgerPermissions, endpointServeExecutorPermissions, deprovisionerPermissions, deliveryPermissions, membershipRwPermissions } from "./provision-permission-builders.js";
22
15
  const ROLE_CAPABILITY = /^role:([A-Za-z0-9_-]+)$/;
23
16
  /** The role a `role:<r>` capability token names, or `undefined` for any other token. */
24
17
  export function capabilityRole(token) {
@@ -651,1368 +644,6 @@ export function permissionsFor(profile, space, pr, opts) {
651
644
  const takeReplies = roles.map((role) => `${takeSubject(space, role, pr.owner, pr.actor)}.>`);
652
645
  return { pub: { allow: pubAllow, deny: pubDeny }, sub: { allow: [inbox, deliveryReplies, ...takeReplies, ...livenessReplies, ...subChat, ...payloadReads, ...epSub] } };
653
646
  }
654
- /** The reads a spawn-scoped manager-caller view carries on its one pinned instance. A launch uses
655
- * `status` (execution mode and connectors), `models` (their catalogs), `resolve-cwd` (canonical
656
- * directory) and `list-dir` (directory navigation). The remaining read, `ps`,
657
- * lists the caller's own agents: the Manager bounds it to the caller's owner unless the caller
658
- * holds admin. The standing spawn set carries none of them, because it reaches every manager in
659
- * the space through the class rail. */
660
- const SPAWN_VIEW_READS = Object.freeze(["status", "models", "resolve-cwd", "list-dir", "ps"]);
661
- /** One seat's manager control view. It carries no agent messaging or delivery surface, and every
662
- * manager request, including describe, is pinned to one exact registered instance. */
663
- function managerCallerPermissions(space, pr, opts) {
664
- if (!pr.lifecycleUid)
665
- throw new Error("permissionsFor(manager-caller): a lifecycleUid is required");
666
- const instanceId = opts.managerInstanceId === undefined
667
- ? (() => { throw new Error("permissionsFor(manager-caller): managerInstanceId is required"); })()
668
- : assertLifecycleToken(opts.managerInstanceId, "managerInstanceId");
669
- const caps = opts.capabilities ?? [];
670
- const ordinary = [
671
- { endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: "describe" },
672
- ...baselineCallerCapabilities().filter((cap) => cap.endpoint === BASELINE_LIFECYCLE_ENDPOINT),
673
- ...(caps.includes("spawn") ? spawnCallerCapabilities(pr.owner) : []),
674
- ...(caps.includes("spawn") ? SPAWN_VIEW_READS.map((command) => ({ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command })) : []),
675
- ...(caps.includes(MANAGER_VITALS_SCOPE) ? [{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: MANAGER_VITALS_COMMAND }] : []),
676
- ...(caps.includes("run") ? runCallerCapabilities(pr.owner) : []),
677
- ...(caps.includes("admin") ? operatorInstrumentCapabilities("admin", pr.owner) : []),
678
- ];
679
- const caller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid: assertLifecycleToken(pr.lifecycleUid) }, opts);
680
- const rows = epCallerGrantRows(space, instanceOnlyManagerCapabilities(ordinary, instanceId), caller);
681
- const listing = opts.listing ? listingGrantRows(space, caller, opts.listing) : { pub: [], sub: [] };
682
- return {
683
- pub: {
684
- allow: [
685
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
686
- ...(opts.issued ? [acceptedReadGrant(space, opts.issued.acceptedToken)] : []),
687
- ...rows.pub,
688
- ...(opts.issued?.listing ? epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, caller) : []),
689
- ...listing.pub,
690
- ],
691
- },
692
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...rows.sub, ...listing.sub] },
693
- };
694
- }
695
- /** The long-lived SUPERVISOR permission set — the always-on manager daemon
696
- * (`manager.ts` `this.ep`), carved down from the former allow-all `manager`. Its breadth is
697
- * STANDING, so tightening it removes the always-on DM/DLV body-read AND the stream-admin tamper
698
- * from the one connection that never goes away. It holds the manager bucket's `lease.*` instance keys
699
- * and the per-space renewal lease key, its own presence key + the roster watch, the ONE delivery-admin
700
- * call (request + bounded reply subtree), the manager-plane liveness serve + reply rows, and a
701
- * read-only point read of the delivery lease row — and nothing else. It serves no manager control:
702
- * that is the v0.4 `service` endpoint, served on a SEPARATE connection under its own
703
- * `endpoint-serve` credential. Provisioning (DM/DLV/TASK consumer-create + ACL
704
- * writes) moves to the EPHEMERAL `provisioner` (opened per-spawn); destructive history-purge moves to the
705
- * EPHEMERAL `purger`. So the supervisor holds NO chat/inst/svc publish (it never posts — only
706
- * `setActivity`, a presence write), NO DM/DLV read of any kind (no consumer-create, no native sub), NO
707
- * stream CREATE/DELETE/PURGE/UPDATE, NO channel-registry access (the daemon sets `watchChannels:false`).
708
- * `$JS` is an ENUMERATED allow-list — exactly the presence-watch + lease-KV verbs — never `$JS.>`. A
709
- * leaked supervisor cred can hold the lease and read the public roster; it cannot read a DM, forge an
710
- * actor, provision, purge, or tamper with a stream. */
711
- function supervisorPermissions(space, pr) {
712
- const PKV = `KV_${presenceBucket(space)}`, MKV = `KV_${managerBucket(space)}`;
713
- const SUP_DLVKV = `KV_${deliveryBucket(space)}`;
714
- return {
715
- pub: {
716
- allow: [
717
- "$JS.API.INFO",
718
- // Transcript startup checks read retained subject counts, never message bodies.
719
- `$JS.API.STREAM.INFO.${chatStream(space)}`,
720
- // Per-instance manager liveness lease (managerBucket, pre-created at `cotal up`): OPEN-ONLY bind +
721
- // CAS this instance's own `lease.<instanceId>` key (acquire/renew/release) + read the subtree. The
722
- // lease is per instance, so the write grant spans `lease.*` (every instance of this space
723
- // shares this one supervisor principal — the isolation between instances is the logical-id/CAS
724
- // boundary, not a cred boundary). NO STREAM.CREATE (pre-created), DELETE, or PURGE.
725
- `$JS.API.STREAM.INFO.${MKV}`,
726
- `$JS.API.STREAM.MSG.GET.${MKV}`, // readManagerLease (last_by_subj lease.*) + CAS-conflict kv.get
727
- `$KV.${managerBucket(space)}.${MANAGER_LEASE_KEY}.*`, // this instance's lease.<id> key (create/update/delete = $KV publishes)
728
- // #1634: the per-space daemon-credential renewal lease, the CAS that picks ONE renewal owner
729
- // when several managers share the daemon's store. Same bucket, its own key outside `lease.*`.
730
- `$KV.${managerBucket(space)}.${MANAGER_RENEWAL_LEASE_KEY}`,
731
- // Presence: publish OWN key + watch the roster. Own key only (no peer-key forge); no
732
- // presence-stream purge/delete (no force-offline tamper). No presence kv.get (roster is the in-memory
733
- // watch cache + sweep), so no STREAM.MSG.GET on presence.
734
- `$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`,
735
- `$JS.API.STREAM.INFO.${PKV}`,
736
- `$JS.API.CONSUMER.CREATE.${PKV}.>`, // kv.watch ordered consumer (roster)
737
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
738
- "$JS.FC.>", // ordered-consumer flow control
739
- // The ONE control service the supervisor CALLS: the delivery daemon's privileged
740
- // admin rail — the manager is the daemon's renewal owner, and after re-signing the daemon creds
741
- // files it requests `reloadCreds` here so adoption is an explicit, auditable event. Self-scoped
742
- // request subject (its own owner+actor slots), bounded reply subtree in sub.allow below.
743
- controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor),
744
- // LIVENESS REPLIES for the MANAGER plane (#1577), bounded to the `.reply.` leaf under a
745
- // caller's own request subject. The supervisor is the natural responder for this plane: it
746
- // is the process that HOLDS the manager lease, so it is the one that can answer the
747
- // question honestly without anyone else being granted a read of the lease row.
748
- //
749
- // REPLIES ONLY, exactly like the delivery daemon's `ctl.delivery.*.*.reply.>`. The row stops
750
- // at the leaf, so the supervisor cannot publish to the liveness REQUEST subjects themselves
751
- // and therefore cannot forge a probe from a peer.
752
- livenessReplyGrant(space, "manager"),
753
- // #1694: a POINT READ of the delivery lease row, so the store-identity challenge can verify
754
- // that the process which answered the queue-grouped admin rail is the holder that actually
755
- // reloads the standing credentials. Without it the challenge can only report what some
756
- // responder sent, and a non-holder's store stands in for the reloading process's.
757
- //
758
- // READ ONLY, and that is the half that matters: a credential able to WRITE this row could
759
- // manufacture the very fact the challenge reads, which would put the determination back in
760
- // the hands of a participant. No `$KV.${deliveryBucket(space)}` publish, no watch consumer,
761
- // no STREAM.DELETE or PURGE.
762
- `$JS.API.STREAM.INFO.${SUP_DLVKV}`,
763
- `$JS.API.STREAM.MSG.GET.${SUP_DLVKV}`,
764
- `$JS.API.DIRECT.GET.${SUP_DLVKV}.>`,
765
- ],
766
- },
767
- sub: {
768
- // Own reply inbox + the delivery-admin reply subtree for its OWN requests. NO chat/inst/dlv
769
- // native sub (the supervisor reads no feed), NO manager control-tier serve (that is
770
- // the endpoint-serve credential's), NO broad `$JS.>`/`$KV.>`.
771
- //
772
- // PLUS the manager-plane liveness SERVE filter (#1577): `live.manager.*.*`, queue-grouped, so
773
- // any credentialed peer's presence probe reaches the lease holder. This is a serve
774
- // subscription on a presence-only rail, not a widening of what the supervisor may read: the
775
- // request body is empty and the subject carries only the caller's own principal.
776
- allow: [
777
- `_INBOX_${pr.connId}.>`,
778
- `${controlServiceSubject(space, CONTROL_DELIVERY_ADMIN, pr.owner, pr.actor)}.>`,
779
- livenessServeFilter(space, "manager"),
780
- ],
781
- },
782
- };
783
- }
784
- /** The long-lived REMOTE MANAGER base credential. This is intentionally smaller than the local
785
- * supervisor+provisioner union: it registers only its own manager presence, holds only its own
786
- * manager-instance lease key, and may provision only lifecycle-keyed resources under its derived
787
- * owner. Endpoint registration, contract publication and serving use separate instance-pinned
788
- * credentials returned by the same typed host protocol. Per-agent provisioning deliberately does
789
- * NOT ride this credential: NATS consumer names are single tokens, so a broker grant cannot safely
790
- * express a prefix wildcard inside `dm_<owner>-<actor>-<uid>`. That operation stays on the host's
791
- * authenticated provisioning protocol, where the requested descendant is fresh-validated before
792
- * an exact one-shot grant is used. */
793
- function remoteManagerPermissions(space, pr, pin) {
794
- if (pin.owner !== pr.owner)
795
- throw new Error(`permissionsFor: remote-manager owner ${JSON.stringify(pin.owner)} does not match the authenticated principal owner ${JSON.stringify(pr.owner)}`);
796
- const iid = assertLifecycleToken(pin.instanceId, "remote manager instanceId");
797
- const allowedActors = new Set([`manager_${iid}`, `manager_exec_${iid}`]);
798
- if (!allowedActors.has(pin.actor) || pr.actor !== pin.actor)
799
- throw new Error(`permissionsFor: remote-manager actor must be the server-selected manager_${iid} or manager_exec_${iid} for instance ${iid}`);
800
- const PKV = `KV_${presenceBucket(space)}`;
801
- const MKV = `KV_${managerBucket(space)}`;
802
- const AUTH = epAuthBucket(space);
803
- const REC = recordsBucket(space);
804
- const gateKey = epgateKey("manager", iid);
805
- const credPrefix = epcredFamilyPrefix("manager", iid);
806
- const repairKey = eprepairKey("manager", iid);
807
- // The SUPERVISOR actor of the pair, which is the one that runs `Manager.start()` and therefore
808
- // the only one that binds the manager plane's liveness responder (`service.ts` hands
809
- // `credentials.supervisor` to the manager; the executor gets the instance-scoped registration
810
- // surface). The liveness rows below are pinned to it so the executor does not carry authority to
811
- // answer a probe it never serves.
812
- const isSupervisorActor = pin.actor === `manager_${iid}`;
813
- const recordKeys = [
814
- recordSpecKey(RECORD_KINDS.svc, ["manager", iid]),
815
- recordStatusKey(RECORD_KINDS.svc, ["manager", iid]),
816
- recordAtomicKey(GOVERN_HEAD, ["manager"]),
817
- ];
818
- return {
819
- pub: {
820
- allow: [
821
- "$JS.API.INFO",
822
- // Only the supervisor allocates names against retained transcript counts. This metadata
823
- // grant carries no consumer or message-body read, just like the agent CHAT info grant.
824
- ...(isSupervisorActor ? [`$JS.API.STREAM.INFO.${chatStream(space)}`] : []),
825
- // Own manager-instance lease only. The local supervisor profile spans lease.* because one
826
- // host manages every local instance; a remote user grant must not.
827
- `$JS.API.STREAM.INFO.${MKV}`,
828
- `$JS.API.STREAM.MSG.GET.${MKV}`,
829
- `$KV.${managerBucket(space)}.${MANAGER_LEASE_KEY}.${iid}`,
830
- // Own presence key + roster watch.
831
- `$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`,
832
- `$JS.API.STREAM.INFO.${PKV}`,
833
- `$JS.API.CONSUMER.CREATE.${PKV}.>`,
834
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
835
- "$JS.FC.>",
836
- // This instance's manager service registration + credential family only.
837
- `$KV.${AUTH}.${gateKey}`,
838
- `$KV.${AUTH}.${repairKey}`,
839
- `$KV.${AUTH}.${credPrefix}.>`,
840
- ...recordKeys.map((key) => `$KV.${REC}.${key}`),
841
- `${spacePrefix(space)}.epc.*`,
842
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
843
- `$JS.API.DIRECT.GET.${epcStreamName(space)}`,
844
- `$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
845
- `$JS.API.CONSUMER.CREATE.KV_${AUTH}.>`,
846
- `$JS.API.CONSUMER.INFO.KV_${AUTH}.>`,
847
- `$JS.API.CONSUMER.DELETE.KV_${AUTH}.>`,
848
- ...recordKeys.map((key) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${key}`),
849
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
850
- // LIVENESS REPLIES for the MANAGER plane (#1577), bounded to the `.reply.` leaf under a
851
- // caller's own request subject — the same row and the same bound as the local supervisor
852
- // profile holds.
853
- //
854
- // WHY THIS PROFILE NEEDS IT AT ALL. `Manager.start()` binds the manager plane's liveness
855
- // responder unconditionally, and a remote manager runs the same `start()` under this
856
- // credential. Without the serve subscription below the bind is denied, and a peer probing
857
- // the manager plane then gets the broker's own no-responders answer, which this surface
858
- // grades `unbound` — a definite verdict about the plane, produced by a gap in a credential,
859
- // while the remote manager is bound and serving. A surface that exists to stop a failure to
860
- // find out being rendered as a finding must not render its own missing grant as one.
861
- //
862
- // REPLIES ONLY. The row stops at the leaf, so a remote manager cannot publish to the
863
- // liveness REQUEST subjects and therefore cannot forge a probe that appears to come from a
864
- // peer, exactly as the supervisor row cannot.
865
- ...(isSupervisorActor ? [livenessReplyGrant(space, "manager")] : []),
866
- ],
867
- },
868
- sub: {
869
- allow: [
870
- `_INBOX_${pr.connId}.>`,
871
- // The manager-plane liveness SERVE filter (#1577): `live.manager.*.*`, queue-grouped, so a
872
- // credentialed peer's presence probe reaches this instance. A serve subscription on a
873
- // presence-only rail and not a widening of what a remote manager may read: the request body
874
- // is empty and the subject carries only the caller's own principal. The MANAGER plane only —
875
- // this credential cannot serve `delivery`, so each plane still answers for itself.
876
- ...(isSupervisorActor ? [livenessServeFilter(space, "manager")] : []),
877
- ],
878
- },
879
- };
880
- }
881
- /** The human-CLI OPERATOR permission set — the ephemeral key the headless
882
- * client commands mint (`cotal send dm|msg|ask`, `cotal dm`, `personas list --running`, via
883
- * `openTransient`). It does exactly what those do: POST as itself (chat/DM/anycast — self-scoped, can
884
- * never forge another actor), and READ the public roster (presence) + the channel registry to resolve a
885
- * name→id and a channel's delivery class. Much narrower than the old broad `manager`: NO serve-control,
886
- * NO DM/DLV body read, NO chat-history read, NO stream CREATE/DELETE/PURGE, NO ACL write, NO lease, NO
887
- * provisioning. A leaked operator cred can post as itself and read the roster — the same surface as the
888
- * human who ran the command. (The interactive `cotal join` console — chat read + own-DM receive — is a
889
- * separate, fuller surface, deferred: it needs the unprovisioned-console DM self-create fixed first.) */
890
- function operatorPermissions(space, pr) {
891
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
892
- return {
893
- pub: {
894
- allow: [
895
- // Post AS itself only — self-scoped (owner+actor), so a leaked operator cred can never forge a
896
- // message attributable to another principal.
897
- chatSubject(space, pr.owner, pr.actor, ">"), // chat.<o>.<a>.> — multicast any channel as me
898
- unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a> — DM any peer as me
899
- anycastSubject(space, "*", pr.owner, pr.actor), // svc.*.<o>.<a> — anycast any role as me
900
- `$KV.${presenceBucket(space)}.${principalKey(pr.owner, pr.actor).key}`, // own presence key only
901
- "$JS.API.INFO",
902
- // Presence read (name→id resolution + the roster). The transient endpoint reads the bucket once
903
- // with a batched Direct Get, whose request subject is the bare stream (#4091); the consumer rows
904
- // serve a watch. No STREAM.MSG.GET.
905
- `$JS.API.STREAM.INFO.${PKV}`,
906
- `$JS.API.DIRECT.GET.${PKV}`,
907
- `$JS.API.CONSUMER.CREATE.${PKV}.>`,
908
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
909
- // Channel registry read — the transient endpoint reads it once (batched Direct Get), multicast
910
- // reads a channel's delivery class, and `channels list` scans it. Read-only (no `$KV.<channel>`
911
- // write — that's the provisioner).
912
- `$JS.API.STREAM.INFO.${CHKV}`,
913
- `$JS.API.DIRECT.GET.${CHKV}`,
914
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
915
- // Keyed KV get rides `DIRECT.GET.<stream>.$KV.<bucket>.<key>` — the key is in the SUBJECT, so
916
- // the grant needs the trailing `.>` (unlike STREAM.MSG.GET, which carries it in the payload).
917
- `$JS.API.DIRECT.GET.${CHKV}.>`,
918
- `$JS.API.CONSUMER.CREATE.${CHKV}.>`,
919
- `$JS.API.CONSUMER.INFO.${CHKV}.>`,
920
- "$JS.FC.>", // ordered-consumer flow control
921
- ],
922
- },
923
- // Own reply inbox only (presence/channel watch ordered-consumer delivery + any request replies land
924
- // here). NO chat/inst/dlv native sub — the operator posts and reads the roster, it receives no feed.
925
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
926
- };
927
- }
928
- /** Connect-only PROBE — the liveness/auth preflight (`preflight.ts preflightTarget`, minted on
929
- * ~every CLI command that resolves a mesh). `probeConnect` opens a connection to prove the broker is up
930
- * and the creds are accepted, then closes it — it performs NO pub/sub. So the tightest possible grant:
931
- * deny ALL publish, subscribe only to the own reply inbox. A leaked probe cred can open a socket and do
932
- * nothing else. (Was the broad `manager` cred — minted on nearly every command, the worst over-grant.) */
933
- function probePermissions(pr) {
934
- return { pub: { deny: [">"] }, sub: { allow: [`_INBOX_${pr.connId}.>`] } };
935
- }
936
- /** CHANNEL-WRITER — edits the channel registry ONLY: `cotal channels set/default` and the
937
- * `spawn -f` new-channel seed (`seedChannelRegistry`). It VALUE-writes `$KV.<channelBucket>` (a channel's
938
- * config key) and read-before-writes it. NO stream data, NO other bucket, NO chat/DM — a leaked
939
- * channel-writer can only rewrite channel config, never post, read a body, or tear a stream down. */
940
- function channelWriterPermissions(space, pr) {
941
- const CHKV = `KV_${channelBucket(space)}`;
942
- return {
943
- pub: {
944
- allow: [
945
- "$JS.API.INFO",
946
- `$KV.${channelBucket(space)}.>`, // create/update/delete a channel config key
947
- `$JS.API.STREAM.INFO.${CHKV}`, // kvm.open/create existence check
948
- `$JS.API.STREAM.CREATE.${CHKV}`, // kvm.create is create-if-matching (bucket already exists post-up)
949
- // read-before-write: kvm.open rides STREAM.MSG.GET; kvm.create (direct=true) rides keyed DIRECT.GET.
950
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
951
- `$JS.API.DIRECT.GET.${CHKV}.>`,
952
- ],
953
- },
954
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
955
- };
956
- }
957
- /** CHANNEL-PURGER — the `cotal web` dashboard's ONLY write path: delete a channel
958
- * (`clearChannel` = filtered `STREAM.PURGE.CHAT` to drop the channel's messages + a `$KV.<channelBucket>`
959
- * key delete). Pre-minted once by `web` so the account signing seed falls out of scope; the dashboard's
960
- * READ side runs on the separate read-only `admin` cred. = channel-writer + the scoped CHAT purge. */
961
- function channelPurgerPermissions(space, pr) {
962
- const CHKV = `KV_${channelBucket(space)}`;
963
- // `clearChannel` only kvm.OPENs the (already-created) bucket, key-deletes, and purges — it never
964
- // kvm.creates, so — unlike channel-writer's set/default back-compat path — this cred gets NO
965
- // `STREAM.CREATE`. Compose the shared channel-KV read + delete verbs + the scoped CHAT purge explicitly.
966
- return {
967
- pub: {
968
- allow: [
969
- "$JS.API.INFO",
970
- `$KV.${channelBucket(space)}.>`, // delete the channel's registry key
971
- `$JS.API.STREAM.INFO.${CHKV}`, // kvm.open existence check
972
- `$JS.API.STREAM.MSG.GET.${CHKV}`, // read-before-delete
973
- `$JS.API.DIRECT.GET.${CHKV}.>`,
974
- `$JS.API.STREAM.PURGE.${chatStream(space)}`, // drop the channel's chat messages
975
- ],
976
- },
977
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
978
- };
979
- }
980
- /** TEARDOWN — `cotal down -f` space teardown. The space-wide cred that keeps `STREAM.DELETE` (the
981
- * tamper verb). `down -f` is multi-step: `connectProbe` (presence-watch + channel-registry read)
982
- * → invoke the manager's `ps` + any-mode `despawn` over the ep rails to politely stop the managed
983
- * agents → `readMembership` (the membership-feed read that keeps an owned channel another member
984
- * still uses) → `deleteChannels`
985
- * (channel-registry key delete + CHAT purge) → `deleteSpace` (STREAM.DELETE every owned stream/bucket).
986
- * So it reads state, CALLS admin control, deletes channels, and deletes streams — but NEVER reads a
987
- * DM/DLV body, posts chat, or forges. Isolated here so no standing operator/provisioner/supervisor cred
988
- * can delete a stream; a leaked teardown can wipe a space you own + stop its agents (that IS its job),
989
- * nothing else. Minted ephemerally per teardown from the local trust material (same-checkout `down -f`). */
990
- function teardownPermissions(space, pr, transferStreams) {
991
- // The ep-rail mirror of the admin deploy tier: teardown reads `ps` and stops owned agents
992
- // it did not spawn (any-mode despawn) - the admin instrument set. Lifecycle-keyed, so a uid is
993
- // required at mint (fail-loud).
994
- const ep = instrumentEpRows(space, pr, "admin");
995
- const CHAT = chatStream(space);
996
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
997
- const MSHIP = `KV_${membershipBucket(space)}`;
998
- const RECORDS = `KV_${recordsBucket(space)}`;
999
- // The deletion path and the exact per-stream grants use one target list. Reject any caller-
1000
- // supplied transfer name that is not this space's transfer bucket before minting the grant.
1001
- for (const name of transferStreams)
1002
- if (!isTransferStream(space, name))
1003
- throw new Error(`permissionsFor: teardown transferStreams names ${JSON.stringify(name)}, not one of ${space}'s transfer streams`);
1004
- const del = spaceDeletionStreams(space, transferStreams)
1005
- .flatMap((s) => [`$JS.API.STREAM.INFO.${s}`, `$JS.API.STREAM.DELETE.${s}`]);
1006
- return {
1007
- pub: {
1008
- allow: [
1009
- "$JS.API.INFO",
1010
- BROKER_USER_INFO_SUBJECT, // confirm the current teardown connection's account before native impact reads
1011
- // deleteSpace() enumerates the transfer streams (one per manager instance that received a
1012
- // carried resume) by name shape; their names are not derivable from the space alone.
1013
- "$JS.API.STREAM.NAMES",
1014
- // connectProbe read: presence watch (name→id + roster) + channel registry read.
1015
- `$JS.API.CONSUMER.CREATE.${PKV}.>`,
1016
- `$JS.API.CONSUMER.INFO.${PKV}.>`,
1017
- `$JS.API.STREAM.MSG.GET.${CHKV}`,
1018
- `$JS.API.DIRECT.GET.${CHKV}.>`,
1019
- `$JS.API.CONSUMER.CREATE.${CHKV}.>`,
1020
- `$JS.API.CONSUMER.INFO.${CHKV}.>`,
1021
- // readMembership's one-pass scan of the feed (its STREAM.INFO is in `del`). No `$KV` publish:
1022
- // only `membership-rw` writes the feed.
1023
- // Batched snapshots read the same feed as the watch below, without a consumer.
1024
- `$JS.API.DIRECT.GET.${MSHIP}`,
1025
- `$JS.API.CONSUMER.CREATE.${MSHIP}.>`,
1026
- `$JS.API.CONSUMER.INFO.${MSHIP}.>`,
1027
- // Space deletion names the workflow runs it removes by their status records: a non-fencing
1028
- // direct get confined to run status keys (§13.9), on a stream this grant may already delete.
1029
- `$JS.API.DIRECT.GET.${RECORDS}.$KV.${recordsBucket(space)}.run.*.*.status`,
1030
- "$JS.FC.>", // ordered-consumer flow control
1031
- // Stop the managed agents over the v0.4 ep rails only (ps + any-mode despawn) — the admin
1032
- // instrument set. The manager `ctl` rail is deleted.
1033
- ...ep.pub,
1034
- ...del,
1035
- // deleteChannels/clearChannel: purge the channel's chat messages + delete its registry key.
1036
- `$JS.API.STREAM.PURGE.${CHAT}`,
1037
- `$KV.${channelBucket(space)}.>`,
1038
- ],
1039
- },
1040
- // Own inbox (connectProbe presence-watch delivery + JS API responses) + the ep reply rail (the
1041
- // ps + any-mode despawn calls reply there). The `ctl.admin.<id>.reply.>` subtree is gone.
1042
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
1043
- };
1044
- }
1045
- /** MEMBERSHIP-STORE-RECREATE — explicit conversion of the derived membership feed from File to
1046
- * Memory. The credential can inspect and delete exactly that one stream. It cannot create the
1047
- * replacement, read membership values, or touch another stream; the ordinary short-lived
1048
- * provisioner creates and verifies the empty Memory replacement after deletion. */
1049
- function membershipStoreRecreatePermissions(space, pr) {
1050
- const stream = `KV_${membershipBucket(space)}`;
1051
- return {
1052
- pub: {
1053
- allow: [
1054
- "$JS.API.INFO",
1055
- `$JS.API.STREAM.INFO.${stream}`,
1056
- `$JS.API.STREAM.DELETE.${stream}`,
1057
- ],
1058
- },
1059
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1060
- };
1061
- }
1062
- /** ISSUED-STORE-RECREATE — `cotal up --recreate-issued-stores`, and an embedder's call of
1063
- * `removeIssuedStoresBeforeRetention`: back up, then delete, the two issued-authority stores of ONE
1064
- * space that predate bounded retention. Exactly `STREAM.INFO`, `STREAM.SNAPSHOT` and
1065
- * `STREAM.DELETE` on those two streams, the snapshot's delivery inside its own inbox, and the
1066
- * snapshot ACK subjects of those two streams ({@link snapshotAckGrant}). Nothing reads a row,
1067
- * writes a store or reaches another stream. */
1068
- function issuedStoreRecreatePermissions(space, pr) {
1069
- return {
1070
- pub: {
1071
- allow: [
1072
- "$JS.API.INFO",
1073
- ...issuedStoreStreamNames(space).flatMap((s) => [`$JS.API.STREAM.INFO.${s}`, `$JS.API.STREAM.SNAPSHOT.${s}`, `$JS.API.STREAM.DELETE.${s}`, snapshotAckGrant(s)]),
1074
- ],
1075
- },
1076
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1077
- };
1078
- }
1079
- /** CONTROL-CALLER (ep rails only) — the operator's lifecycle commands
1080
- * (`cotal ps/start/stop/attach`, `manager/commands.ts`). It invokes the manager's v0.4 service
1081
- * endpoint and reads the bounded reply on the ep reply rail. That is ALL — no `$JS`, no `$KV`,
1082
- * no chat/DM: it forges nothing, reads no body.
1083
- *
1084
- * The tiers stay SPLIT because the BROKER grant is load-bearing: an any-mode
1085
- * despawn/attach row *is* cross-agent reach — the manager maps mode `any` to its admin
1086
- * authorization path, so which ROWS an instrument holds is the tier boundary. Therefore:
1087
- * • `control-caller-privileged` (ps/start) holds the manager reads + untargeted `spawn` +
1088
- * `define-persona` — structurally barred from cross-agent ops (no any-mode row). This is the
1089
- * high-frequency path; it never needs admin reach.
1090
- * • `control-caller-admin` (stop/attach) adds the any-mode despawn/attach rows + the
1091
- * `manager.admin` family — it genuinely needs cross-agent reach. Its containment is the
1092
- * broker gating the any-mode rows + the cred being ephemeral (mint → one request →
1093
- * disconnect, from the local signing seed); on a user mesh the manager's serve-time ledger
1094
- * re-check sits on top. */
1095
- function controlCallerPermissions(space, pr, epTier, opts = {}) {
1096
- // The manager `ctl` rail is gone — an operator instrument holds ONLY its v0.4 ep rows (the
1097
- // tier-matched request set, the reply rail, describe, the one epc fetch). The `epTier` selects
1098
- // privileged (ps/start reads) vs admin (any-mode stop/attach) exactly as the ctl tier did.
1099
- //
1100
- // `--on <instanceId>`: these instruments are ONE-SHOT, minted per control call, and the
1101
- // resolve that pins the instance happens BEFORE the mint. So the caller can hand the exact
1102
- // instance id down and get the exact `ep.inst.<endpoint>.<iid>.<command>` row for THIS invocation
1103
- // and nothing else — the least-privilege issuance, with no standing wildcard anywhere. The
1104
- // `extra` seam is the same one the deployer's owner-equality `launch` row already rides, and the
1105
- // emitter's `if (cap.instanceId)` branch validates the token, so a malformed id fails loud at
1106
- // mint rather than widening a subject.
1107
- const ep = instrumentEpRows(space, pr, epTier, opts.endpointCapabilities ?? [], opts);
1108
- return {
1109
- // The PRIVILEGED tier (the `cotal ps` instrument) also carries the SCOPED §13.9 records read the
1110
- // class scatter's freeze rides: `freezeExpectedSet` enumerates `svc.<endpoint>.*.spec`
1111
- // and LEADER-reads each frozen slot's svc spec/status before it scatters `ps` on the `all` rail.
1112
- // The admin tier (stop/attach) never scatters, so it gets no records read.
1113
- pub: { allow: epTier === "privileged" ? [...ep.pub, ...scatterFreezeReadRows(space)] : ep.pub },
1114
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
1115
- };
1116
- }
1117
- /** The SCOPED §13.9 records-read rows the class-scatter freeze rides (`cotal ps`): the
1118
- * `svc.*` enumeration consumer + the leader-served per-slot spec/status read of the endpoint's
1119
- * `svc` registry — a READ of exactly the service-registration keys, no write, no other bucket.
1120
- * The keyed Direct Get is subject-PINNED to `svc.>`; the enumeration consumer
1121
- * and the leader `STREAM.MSG.GET` are STREAM-scoped because the requested key rides the PAYLOAD
1122
- * (which a subject grant cannot narrow) — the SAME NAMED RESIDUAL every records reader already
1123
- * accepts (the provisioner, the lifecycle/serve executors): for this EPHEMERAL one-shot instrument's
1124
- * lifetime it can READ (never write) any records-store row — registration metadata, no secrets. */
1125
- function scatterFreezeReadRows(space) {
1126
- const REC = recordsBucket(space);
1127
- return [
1128
- // The `svc.<e>.*.spec` enumeration is a `STREAM.INFO` carrying a `subjects_filter` — ONE
1129
- // read-only metadata verb. It replaced a `kv.keys()` that rode an ordered ephemeral consumer and
1130
- // therefore needed CONSUMER.CREATE/INFO/DELETE on this bucket: three consumer-lifecycle verbs to
1131
- // list keys, on a credential that only ever wanted to read them.
1132
- //
1133
- // MEASURED, not assumed: with the enumeration converted and this row absent, the static/operator
1134
- // `cotal ps` is refused on `$JS.API.STREAM.INFO.KV_<records>` — a path that works today. The
1135
- // conversion and this row land TOGETHER or the operator path regresses.
1136
- `$JS.API.STREAM.INFO.KV_${REC}`,
1137
- // The per-slot spec/status reads (`freezeExpectedSet` + the registration reconcile) are
1138
- // leader-served `STREAM.MSG.GET` — stream-scoped (NAMED RESIDUAL above), plus the subject-pinned
1139
- // keyed Direct Get form for any direct-aware read path (scoped to the `svc.` registry prefix).
1140
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
1141
- `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.>`,
1142
- ];
1143
- }
1144
- /** The v0.4 ep-rail rows of an operator INSTRUMENT credential: the tier-matched
1145
- * {@link operatorInstrumentCapabilities} request rows + the caller's reply rail, the wildcard
1146
- * `describe` form, and the ONE subject-scoped §13.7 contract-store fetch row (the same shape the
1147
- * agent baseline holds). No ctl row exists, so these ARE the instrument. The caller triple pins the instrument's own mint-time lifecycle uid
1148
- * ({@link MintPrincipal.lifecycleUid}) — REQUIRED here: without it the reply rail cannot be pinned
1149
- * and the mint fails loud rather than emit a triple-less (unfenced) caller surface. `extra` lets a
1150
- * profile append its tier-refined additions (the user-mode deployer's owner-equality `launch`). */
1151
- function instrumentEpRows(space, pr, tier, extra = [], opts = {}) {
1152
- if (!pr.lifecycleUid)
1153
- 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`);
1154
- const epCaller = issuedCallerFor({ owner: pr.owner, actor: pr.actor, uid: pr.lifecycleUid }, opts);
1155
- const rows = epCallerGrantRows(space, [...operatorInstrumentCapabilities(tier, pr.owner), ...extra], epCaller);
1156
- return {
1157
- pub: [
1158
- epDescribeAllGrantRow(space, epCaller),
1159
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
1160
- ...(opts.issued ? [acceptedReadGrant(space, opts.issued.acceptedToken)] : []),
1161
- ...rows.pub,
1162
- ],
1163
- sub: rows.sub,
1164
- };
1165
- }
1166
- /** The ep caller a mint pins: the triple, plus the issued generation when the mint is an
1167
- * issuance (SPEC 13.15). One place decides the rail so a credential's request rows, its reply
1168
- * read, and its describe row all land on the same one. */
1169
- function issuedCallerFor(triple, opts) {
1170
- if (!opts.issued)
1171
- return triple;
1172
- assertGeneration(opts.issued.acceptedToken, "acceptedToken");
1173
- return { ...triple, generation: assertGeneration(opts.issued.generation) };
1174
- }
1175
- /** The rows a listing generation adds to a legacy-rail credential (SPEC 13.15, "Listing
1176
- * issuance"): the registry's `endpoints` request publish and its reply subscribe on `ep.v1`, and
1177
- * the per-key read of the generation's accepted row. Exactly these: one caller value emits one
1178
- * rail, so these are the only `ep.v1` rows such a credential holds. */
1179
- export function listingGrantRows(space, caller, listing) {
1180
- if (isIssuedCaller(caller))
1181
- throw new Error("listingGrantRows: an issued caller lists under its own generation");
1182
- assertGeneration(listing.acceptedToken, "acceptedToken");
1183
- const issued = { owner: caller.owner, actor: caller.actor, uid: caller.uid, generation: assertGeneration(listing.generation) };
1184
- return {
1185
- pub: [...epRequestGrantRows(space, REGISTRY_ENDPOINTS_GRANT, issued), acceptedReadGrant(space, listing.acceptedToken)],
1186
- sub: [epCallerReplyFilter(space, issued)],
1187
- };
1188
- }
1189
- /** ENDPOINT-SERVE (v0.4, SPEC §13.9 "Serve grants") — the per-instance serve credential:
1190
- * EXACTLY the instance's registered rails and nothing else. Subscribe: the queue-qualified
1191
- * class rail, the plain scatter rail, and the own-instance rail for the FULL registered
1192
- * command set plus the derived `describe`, and the own epoch-pinned timer-fire subjects;
1193
- * publish: the epoch-pinned egress (reply / `epe` events / `ept` schedule requests / `epr`
1194
- * record-write ingress) plus, from the branded snapshot only, the §13.9 bind rows: the shared
1195
- * `eff_<e>` effects bind iff the surface is journal-class and each owned `pool_<e>_<pool>`
1196
- * bind (bind-only + `$JS.API.INFO`; an ephemeral-only poolless endpoint emits none). No agent
1197
- * baseline of any kind — no chat/DM/anycast/presence/ctl, no broad `$JS.>`. The value MUST be the
1198
- * branded ARTIFACT `authorizeServeGrant` returned, and its mint context binds: same space, and
1199
- * the minted principal is the registered owner. This builds the ROWS; the RELEASE fence is the
1200
- * durable issuance-gate CAS `mintCreds` runs (SPEC §13.1) — a raw/copied/diverging value or a
1201
- * foreign space/principal refuses here, and a stale incarnation loses the gate CAS. */
1202
- function endpointServePermissions(space, pr, opts) {
1203
- if (!opts.endpointServe)
1204
- throw new Error("permissionsFor: endpoint-serve requires opts.endpointServe (the authorized serve artifact)");
1205
- // The fence is INSEPARABLE from serve-row emission: a serve credential's rows are only ever
1206
- // valid when released behind the §13.1 issuance CAS, so this builder refuses to emit them
1207
- // without the gate seam — closing the exported-permissionsFor bypass where a direct signer
1208
- // could obtain unfenced serve rows past the brand/space/owner check. `mintCreds` runs the CAS.
1209
- if (!opts.serveIssuance)
1210
- 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)");
1211
- const snap = assertServeGrantMintable(opts.endpointServe, { space, holderOwner: pr.owner });
1212
- // Rail subscribe rows cover the EPHEMERAL commands only (journal commands ride epj, never the
1213
- // request rails) + the derived describe; the descriptor surface stays full. The class comes
1214
- // from the brand-verified artifact surface, not the caller.
1215
- const ephemeralCommands = snap.commands.filter((cmd) => opts.endpointServe.surface[cmd].class === "ephemeral");
1216
- const rows = epServeGrantRows(space, {
1217
- endpoint: snap.endpoint, instanceId: snap.instanceId, epoch: snap.epoch, ephemeralCommands,
1218
- });
1219
- // §13.9 bind rows, from the BRANDED snapshot only (journal class is registered truth,
1220
- // pools are the authorizing provisioner's pre-created durables): a journal-class instance
1221
- // binds the shared `eff_<e>` effects durable, a pool-owning one binds each owned
1222
- // `pool_<e>_<pool>` — all bind-only (INFO/MSG.NEXT/ACK, never create/delete), plus the one
1223
- // `$JS.API.INFO` a pull consumer needs. An ephemeral-only poolless endpoint emits NONE of
1224
- // these rows (default-deny both directions).
1225
- const bindRows = [];
1226
- if (snap.journalClass)
1227
- bindRows.push(...effectsBindGrants(space, snap.endpoint));
1228
- for (const pool of snap.pools)
1229
- bindRows.push(...poolOwnerBindGrants(space, snap.endpoint, pool));
1230
- if (bindRows.length > 0)
1231
- bindRows.push("$JS.API.INFO");
1232
- return {
1233
- pub: { allow: [...rows.pub, ...bindRows] },
1234
- sub: { allow: [...rows.sub, `_INBOX_${pr.connId}.>`] },
1235
- };
1236
- }
1237
- /** DEPLOYER — the `cotal spawn -f` manifest-deploy authority. `spawn -f` drives ONE
1238
- * `connectProbe` endpoint that both READS live state (roster/presence watch, channel registry,
1239
- * membership feed, manager-singleton lease) AND invokes the running manager's `launch` + `ps`
1240
- * readiness over the v0.4 ep rails. Those interleave on one connection, so a strict 3-connection
1241
- * split would only refactor `live.ts` for marginal gain; `deployer` is that one coherent,
1242
- * ephemeral deploy cred. It is the SOLE profile that combines reads + admin-control — NOT a template a
1243
- * 4th command should reach for (revisit the connection split before adding a second such caller).
1244
- *
1245
- * Boundaries (all enforced by omission / default-deny): NO self-post (`chat`/`inst`/`svc`), NO `$JS.>`,
1246
- * NO `STREAM.DELETE`/`PURGE`/`UPDATE`, NO DM/DLV/TASK `CONSUMER.CREATE` (no body-read surface), NO `$KV`
1247
- * writes (channel seeding rides a SEPARATE `channel-writer` cred). It holds the admin INSTRUMENT ep
1248
- * set (any-mode despawn/attach + the manager.admin family + reads) because manifest launch/ps
1249
- * genuinely need cross-agent reach — and that IS real power: the manager's any-mode authz is
1250
- * subject-gated (the any-mode ep row is mintable only under operator policy), so holding it lets it
1251
- * stop/attach/launch ANY agent. The BROKER gating that row is the boundary. Containment is therefore
1252
- * the LIFETIME, not a manager re-check: minted from LOCAL same-checkout auth for one `spawn -f`,
1253
- * memory-only, dropped after deploy. If it is ever persisted, handed to user-supplied `--creds`, or
1254
- * reused as a general "read + admin" cred, revisit. */
1255
- function deployerPermissions(space, pr, epTier = "admin", opts = {}) {
1256
- // The v0.4 ep rows of the deploy authority: static (admin) deploys carry the admin instrument
1257
- // set; the user-mode deployer VIEW (privileged) carries the privileged set PLUS an untargeted
1258
- // `launch` row — its launch stays owner-equality-authorized (the manager's ledger-derived admin
1259
- // flag is false for a spawn-scoped deployer), exactly the v0.3 user-mode privileged-tier launch.
1260
- // `--on`: the per-invocation pin APPENDS to this profile's standing set, never replaces it -
1261
- // the privileged deployer view keeps its owner-equality `launch` row and additionally gets the one
1262
- // exact `ep.inst.<endpoint>.<iid>.<command>` row for the instance this deploy resolved.
1263
- const pinned = opts.endpointCapabilities ?? [];
1264
- const ep = epTier === "admin"
1265
- ? instrumentEpRows(space, pr, "admin", pinned, opts)
1266
- : instrumentEpRows(space, pr, "privileged", [{ endpoint: BASELINE_LIFECYCLE_ENDPOINT, command: "launch" }, ...pinned], opts);
1267
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
1268
- const MSHIP = `KV_${membershipBucket(space)}`, MGRKV = `KV_${managerBucket(space)}`;
1269
- const DLVKV = `KV_${deliveryBucket(space)}`;
1270
- // Read verbs for a KV bucket SCANNED/WATCHED via an ordered consumer (presence, channel registry, and
1271
- // the membership feed — `readMembership` enumerates keys via `kv.keys()`): existence + kv.get (both
1272
- // STREAM.MSG.GET and keyed DIRECT.GET forms) + the ordered consumer. NO `$KV.<bucket>` publish → no write.
1273
- const kvScan = (bucket) => [
1274
- `$JS.API.STREAM.INFO.${bucket}`,
1275
- `$JS.API.STREAM.MSG.GET.${bucket}`,
1276
- `$JS.API.DIRECT.GET.${bucket}.>`,
1277
- `$JS.API.CONSUMER.CREATE.${bucket}.>`,
1278
- `$JS.API.CONSUMER.INFO.${bucket}.>`,
1279
- ];
1280
- // A KV bucket read by a KEYED point-get only (`readManagerLease` = kvm.open + `kv.get(LEASE_KEY)`, no
1281
- // scan/watch): existence + kv.get, but NO ordered-consumer verbs (nothing enumerates or watches it).
1282
- const kvPointRead = (bucket) => [
1283
- `$JS.API.STREAM.INFO.${bucket}`,
1284
- `$JS.API.STREAM.MSG.GET.${bucket}`,
1285
- `$JS.API.DIRECT.GET.${bucket}.>`,
1286
- ];
1287
- return {
1288
- pub: {
1289
- allow: [
1290
- "$JS.API.INFO",
1291
- ...kvScan(PKV), // presence watch — roster + name→id
1292
- ...kvScan(CHKV), // channel registry read (readChannelRegistry + classifyChannels)
1293
- ...kvScan(MSHIP), // membership FEED read (readMembership → detectUnmanagedActors) — the membership_ bucket
1294
- ...kvPointRead(MGRKV), // manager-singleton lease keyed read (waitManagerReady) — point-get, NO write, NO watch
1295
- ...kvPointRead(DLVKV), // delivery-lease keyed read (preserve-state quiescence proof) — point-get, NO write, NO watch
1296
- "$JS.FC.>", // ordered-consumer flow control
1297
- // Launch + ps readiness ride the v0.4 ep rows only (the manager `ctl` rail is gone).
1298
- // Static deploys carry the admin instrument set; the user-mode deployer VIEW carries the
1299
- // privileged set + an owner-equality `launch` row (the manager's ledger-derived admin flag
1300
- // is false for a spawn-scoped deployer, so its launch stays owner-equality-authorized).
1301
- ...ep.pub,
1302
- ],
1303
- },
1304
- // Own inbox (presence/registry watch delivery + JS API responses) + the ep reply rail.
1305
- sub: { allow: [`_INBOX_${pr.connId}.>`, ...ep.sub] },
1306
- };
1307
- }
1308
- /** The ephemeral PURGER permission set — minted per-purge inside the daemon's
1309
- * `opPurge` and `cotal history clear`. Isolates the DESTRUCTIVE history-purge grant
1310
- * (`STREAM.PURGE.CHAT` + `STREAM.PURGE.DM`) off the always-on supervisor: `--dms` purges the DM stream,
1311
- * exactly the grant the supervisor must not hold. It PURGES but never READS — no DM/chat consumer, no
1312
- * `MSG.GET` — so a leaked purger can drop history but cannot read a body. Short-lived (one purge call). */
1313
- function purgerPermissions(space, pr) {
1314
- const CHAT = chatStream(space), DM = dmStream(space);
1315
- return {
1316
- pub: {
1317
- allow: [
1318
- "$JS.API.INFO", // jetstreamManager bootstrap; STREAM.PURGE needs no prior STREAM.INFO
1319
- `$JS.API.STREAM.PURGE.${CHAT}`, // clearSpaceHistory chat purge
1320
- `$JS.API.STREAM.PURGE.${DM}`, // clearSpaceHistory includeDms — the isolated DM-purge grant
1321
- ],
1322
- // NOTE: this profile does NOT cover `clearChannel` (web/`down -f` channel-delete) — that also does a
1323
- // `$KV.<channelBucket>.<ch>` registry delete this cred lacks, which `channel-purger` and `teardown` hold.
1324
- },
1325
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1326
- };
1327
- }
1328
- /** The ephemeral PROVISIONER permission set — the onboarding authority,
1329
- * carved off the long-lived manager. Minted short-lived for per-spawn provisioning (pre-create each
1330
- * agent's bind-only DM/DLV/TASK durables + record its read ACL via `commitAcl`) — the daemon opens it per
1331
- * spawn (`manager.ts withProvisioner`). It is ALSO the cred that creates the space's streams + KV buckets
1332
- * and seeds the channel registry via `setupSpaceStreams` (exercised by the manager-split smoke) — and
1333
- * `cotal up`'s ephemeral setup cred (`up.ts authSetup`) now mints THIS profile, not the broad `manager`.
1334
- * NEVER minted for an agent — `cotal mint` whitelists
1335
- * agent/observer/admin only, like `manager`/`delivery`.
1336
- *
1337
- * This profile HOLDS the DM/DLV `CONSUMER.CREATE` push-consumer surface — the irreducible onboarding
1338
- * power (the create-time `deliver_subject` of a push consumer is not ACL-constrained, so whoever can
1339
- * create a DM/DLV consumer can stream the bodies). That is exactly why it is split OFF the always-on
1340
- * supervisor and made EPHEMERAL: the daemon opens a provisioner connection per spawn and drains it
1341
- * immediately, so the surface exists only for the provisioning window, not as a standing target. The
1342
- * cred is MEMORY-ONLY (never written to `.cotal`) and carries a short profile-default `exp`.
1343
- *
1344
- * `$JS` is an ENUMERATED allow-list, never `$JS.>`: STREAM.CREATE + INFO for the space streams/buckets,
1345
- * DM/DLV/TASK consumer CREATE/DURABLE.CREATE/INFO — and deliberately NO `MSG.NEXT`/`MSG.GET`/`ACK` on
1346
- * DM/DLV (it creates the bind-only mailbox but never reads it), and NO STREAM.DELETE/PURGE/MSG.DELETE
1347
- * (it provisions, it does not tear down). STREAM.UPDATE is held on EXACTLY thirteen streams and no others:
1348
- * the three TTL'd KV buckets (presence + the two leases, #286: an existing bucket's `max_age` cannot be
1349
- * fixed by `kvm.create`, so reconciling a pre-TTL deployment requires updating it), the four hardened
1350
- * authority stores (records, issued, accepted, admission), each updated once at creation, and the
1351
- * membership KV and artifact Object Store, whose legacy `max_bytes` values setup reconciles to -1 (the
1352
- * reservation a positive cap holds against the broker's `max_file_store` is what stopped a tenth space
1353
- * from being provisioned; `Objm.create` cannot fix an existing bucket's cap either), and the CHAT,
1354
- * INBOX, DLV and DM streams, whose history limits `cotal history limit` writes (`setHistoryLimit`).
1355
- * Stated positively on purpose: this docblock previously read "NO …/UPDATE", which was already untrue of
1356
- * the records stream and became untrue of the buckets, and a comment that denies a credential's real
1357
- * power is worse than none — it is the document a reader trusts instead of checking. KV value-writes are
1358
- * scoped to exactly the two
1359
- * registries provisioning touches: the read-ACL bucket (`commitAcl`) and the channel registry (seed). */
1360
- function provisionerPermissions(space, pr) {
1361
- const CHAT = chatStream(space), DM = dmStream(space), TASK = taskStream(space);
1362
- const INBOX = inboxStream(space), DLV = dlvStream(space);
1363
- // Every non-endpoint KV backing stream the provisioner pre-creates. Endpoint control streams and
1364
- // their records/auth/session buckets come from endpointPlaneStreamNames below, the same downstream
1365
- // ownership list consumed by inventory and teardown. The provisioner holds create-or-verify only on
1366
- // those authority stores; lifecycle/session writes ride their narrower executor credentials.
1367
- const buckets = [
1368
- presenceBucket, channelBucket, membersBucket, aclBucket, membershipBucket, anycastBucket, deliveryBucket, managerBucket,
1369
- ].map((b) => `KV_${b(space)}`);
1370
- // STREAM.CREATE + INFO for each (idempotent setup at `cotal up`; CREATE is create-if-matching, INFO covers
1371
- // the client's existence checks). NO DELETE/PURGE — provisioning never tears a stream down.
1372
- // The §13.7 CONTRACT store (EPC) joins the list for the static manager's start-time
1373
- // `ensureContractStore`: create-or-verify only — the provisioner holds no
1374
- // artifact-publish grant on it (publication rides the scoped endpoint-serve executor).
1375
- // The seven §13.12 ENDPOINT streams join the list: spawn-as-action makes the manager
1376
- // the first EPF (goal facts) + EPE (progress) writer, and nothing provisioned the endpoint streams
1377
- // before (no manager code wrote to them), so `createEndpointStreams` now runs at the manager's
1378
- // start-time ensure over this provisioner. Create-or-verify only (idempotent, fail-loud on drift);
1379
- // the provisioner holds no value-write on any of them (goal facts ride the scoped goal-writer cred).
1380
- // WFJ and the EPC/records/auth/session stores join them through endpointPlaneStreamNames because
1381
- // createEndpointStreams owns all twelve resources. Create-or-verify only; the provisioner appends
1382
- // nothing (writes ride the narrower runtime and authority credentials).
1383
- // The artifact Object Store joins the list: `setupSpaceStreams` creates it, and under auth mode the
1384
- // provisioner is the cred doing that creating. Its backing stream is `OBJ_<bucket>` - named
1385
- // explicitly, because `$O.<bucket>.>` is outside the `cotal.<space>.>` grammar and no space-prefix
1386
- // grant reaches it. CREATE + INFO here, plus the ONE STREAM.UPDATE below (the legacy-cap reconcile):
1387
- // the provisioner never publishes an object, never creates a consumer on it, and never deletes it.
1388
- // That confinement is load-bearing rather than tidy - the
1389
- // object-store client reads by creating an ephemeral PUSH consumer with a caller-chosen
1390
- // `deliver_subject`, so a CONSUMER.CREATE here would be an exporter of every artifact in the space.
1391
- const OBJ = objectStoreStream(artifactBucket(space));
1392
- const streamSetup = [CHAT, DM, TASK, INBOX, DLV, eventPayloadStream(space), OBJ, ...endpointPlaneStreamNames(space), ...buckets].flatMap((s) => [
1393
- `$JS.API.STREAM.CREATE.${s}`,
1394
- `$JS.API.STREAM.INFO.${s}`,
1395
- ]);
1396
- // #286: STREAM.UPDATE on EXACTLY the three TTL'd KV streams (presence + the two leases). `kvm.create`
1397
- // never updates an existing bucket's config, so a bucket created by a cotal that predates the `max_age`
1398
- // TTL keeps NO expiry forever — dead presence records (and stale leases) never age out. `setupSpaceStreams`
1399
- // reconciles their `max_age` via STREAM.UPDATE at every `cotal up`, which needs this grant. Scoped to these
1400
- // three streams here. The durable task stream and the channel/members/acl registries are never
1401
- // updated (the history limits of the four message streams are the exception, below), and there is
1402
- // still NO DELETE/PURGE. The supervisor profile keeps its full UPDATE
1403
- // denial; this widening is provisioning-only.
1404
- // Derived from the SAME inventory that creates and reconciles them, not a third hand-kept copy.
1405
- // Review found this list was the last independent one: a fourth TTL'd bucket added to `ttlBuckets`
1406
- // would be created and reconciled correctly and then die on a permissions violation here, because
1407
- // the grant never learned about it. Same defect one seam out — a bucket the code knows to maintain
1408
- // and the credential is not allowed to.
1409
- const ttlStreams = ttlBuckets(space).map(([bucket]) => `KV_${bucket}`);
1410
- // ...plus the membership KV and artifact Object Store. Both create at `max_bytes: -1` so they
1411
- // reserve nothing against the broker's `max_file_store`, and both reconcile only their own stock
1412
- // legacy caps so an EXISTING mesh releases those reservations too. The create clients never update
1413
- // an existing bucket's config, so each reconcile is a STREAM.UPDATE and needs this grant — without
1414
- // it the provisioner dies on a permissions violation on the first `cotal up` after the upgrade.
1415
- // Still CREATE/INFO/UPDATE only:
1416
- // no publish, no CONSUMER.CREATE (a push consumer's caller-chosen `deliver_subject` would export
1417
- // every artifact in the space), no DELETE/PURGE.
1418
- // ...plus the CHAT, INBOX, DLV and DM streams: `cotal history limit` sets their history limits
1419
- // (SPEC §8). STREAM.UPDATE is a whole-config write, so the grant reaches every setting of them;
1420
- // `setHistoryLimit` changes only `max_age` and `max_msgs_per_subject` and refuses a read back that is
1421
- // not canonical apart from those two. TASK stays create-only.
1422
- const streamReconcile = [...ttlStreams, `KV_${membershipBucket(space)}`, OBJ, CHAT, INBOX, DLV, DM]
1423
- .map((s) => `$JS.API.STREAM.UPDATE.${s}`);
1424
- // #404: one EXACT reserved key on each TTL bucket is the post-update enforcement canary. The
1425
- // provisioner still cannot write presence identities or lease keys; it can only write this fixed
1426
- // maintenance key, which expires through the policy the reconcile is proving.
1427
- const ttlCanaries = ttlBuckets(space).map(([bucket]) => `$KV.${bucket}.${TTL_RECONCILE_CANARY_KEY}`);
1428
- // DM/DLV/TASK durable pre-create (bind-only mailboxes): both the new-API CREATE and legacy DURABLE.CREATE
1429
- // forms (the client's consumer-add path varies by version), plus INFO (the add returns ConsumerInfo).
1430
- // NO MSG.NEXT/MSG.GET/ACK — the provisioner creates the consumer but MUST NOT read its body.
1431
- const consumerCreate = [DM, DLV, TASK].flatMap((s) => [
1432
- `$JS.API.CONSUMER.CREATE.${s}.>`,
1433
- `$JS.API.CONSUMER.DURABLE.CREATE.${s}.>`,
1434
- `$JS.API.CONSUMER.INFO.${s}.>`,
1435
- ]);
1436
- return {
1437
- pub: {
1438
- allow: [
1439
- "$JS.API.INFO",
1440
- // Current-connection identity only; the broker maps the account and requesting user.
1441
- // No subject containing another account/user and no system credential is granted.
1442
- BROKER_USER_INFO_SUBJECT,
1443
- ...streamSetup,
1444
- ...streamReconcile,
1445
- ...ttlCanaries,
1446
- ...consumerCreate,
1447
- // KV value-writes — exactly the two registries provisioning writes: the agent read-ACL registry
1448
- // (`commitAcl` at provision) and the channel registry (seed defaults at `cotal up`, channel admin).
1449
- // NO presence/members/membership/delivery writes (the agent's own key, the delivery cred, and the
1450
- // membership-rw cred own those).
1451
- `$KV.${aclBucket(space)}.>`,
1452
- `$KV.${channelBucket(space)}.>`,
1453
- // ...and READ both: commitAcl read-before-writes the ACL (`kvm.open`, direct=false ⇒ STREAM.MSG.GET);
1454
- // the channel seed read-before-writes defaults (`kvm.create`, direct=true ⇒ DIRECT.GET). Grant both
1455
- // read verbs on both buckets to cover the open/create-path variance — reads of registries it already
1456
- // writes, no escalation. Without these the read-before-write rejects and provisioning/seed throws.
1457
- `$JS.API.STREAM.MSG.GET.KV_${aclBucket(space)}`,
1458
- `$JS.API.DIRECT.GET.KV_${aclBucket(space)}.>`, // keyed get: `.>` (the key rides the subject)
1459
- `$JS.API.STREAM.MSG.GET.KV_${channelBucket(space)}`,
1460
- `$JS.API.DIRECT.GET.KV_${channelBucket(space)}.>`, // keyed get: `.>` (the key rides the subject)
1461
- // The static-manager start path: `ensureAuthorityStores` UPDATEs the records store's
1462
- // deny-flags exactly once at fresh creation (create → update → verify), and the boot
1463
- // reconciliation sweep enumerates the manager's slot rows (`keys()` → an ordered consumer)
1464
- // then reads each slot BODY (phase/uid/actor) to plan resume — the reads ride the
1465
- // stream-scoped MSG.GET residual named below (records lifecycle metadata, no secrets).
1466
- // The issued, accepted and admission stores (SPEC 13.15, 14.8) take the same one-time
1467
- // hardening UPDATE at fresh creation as the records store: their rows are create-only and
1468
- // their markers permanent, and a holder's own key row would otherwise replace them as a
1469
- // value write. One list in core names the hardened stores for every seam that creates them.
1470
- ...hardenedAuthorityStreamNames(space).map((s) => `$JS.API.STREAM.UPDATE.${s}`),
1471
- `$JS.API.CONSUMER.CREATE.KV_${recordsBucket(space)}.>`,
1472
- `$JS.API.CONSUMER.INFO.KV_${recordsBucket(space)}.>`,
1473
- `$JS.API.CONSUMER.DELETE.KV_${recordsBucket(space)}.>`,
1474
- // ...and reads the slot-mapping rows so the sweep can plan resume actions. The KV client
1475
- // reads a lazily-bound bucket via leader-served `STREAM.MSG.GET` — stream-scoped, NOT
1476
- // key-scoped (the requested key rides the PAYLOAD). NAMED RESIDUAL: for its one-shot
1477
- // lifetime the provisioner can READ (never write) any records-store row — lifecycle
1478
- // metadata, no secrets. The keyed Direct Get grant stays for direct-aware read paths.
1479
- `$JS.API.STREAM.MSG.GET.KV_${recordsBucket(space)}`,
1480
- `$JS.API.DIRECT.GET.KV_${recordsBucket(space)}.$KV.${recordsBucket(space)}.${STATIC_SLOT_PREFIX}.>`,
1481
- ],
1482
- },
1483
- // Replies only: every stream/consumer/KV-create PubAck and JS API response lands on the per-id inbox.
1484
- // NO chat/inst/dlv/ctl subscription — the provisioner never serves control nor reads any feed.
1485
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1486
- };
1487
- }
1488
- /** The ISSUER permission set (SPEC 13.15): value-writes on the evidence store (evidence, attempt,
1489
- * source index: create-only and CAS rows, keyed by generation) and on the accepted-row store
1490
- * (create-only, keyed by the client's token); `STREAM.INFO` on both, the bind-time shape check;
1491
- * the leader-served point read on the evidence store; and the ordered `keys()` walk a source
1492
- * retirement enumerates the reverse index with.
1493
- * NAMED RESIDUAL (the contract's section 8): this profile holds a write and a raw read on ONE
1494
- * stream, the pairing no peer-held profile may hold, so it is never issuable to a peer. */
1495
- function issuerPermissions(space, pr) {
1496
- const ISSUED = `KV_${issuedBucket(space)}`;
1497
- return {
1498
- pub: {
1499
- allow: [
1500
- "$JS.API.INFO",
1501
- `$KV.${issuedBucket(space)}.>`,
1502
- `$KV.${acceptedBucket(space)}.>`,
1503
- // A user-auth connection's renewal finds the accepted row its nonce names (SPEC 13.15).
1504
- `$JS.API.DIRECT.GET.KV_${acceptedBucket(space)}.$KV.${acceptedBucket(space)}.>`,
1505
- `$JS.API.STREAM.INFO.${ISSUED}`,
1506
- `$JS.API.STREAM.INFO.KV_${acceptedBucket(space)}`,
1507
- `$JS.API.STREAM.MSG.GET.${ISSUED}`,
1508
- // Source liveness: the leader-served point read of a static incarnation's issuance gate on
1509
- // the auth store (body-selected, stream-wide: the same named residual every records
1510
- // reader accepts). No auth-store WRITE of any shape.
1511
- `$JS.API.STREAM.MSG.GET.KV_${epAuthBucket(space)}`,
1512
- `$JS.API.CONSUMER.CREATE.${ISSUED}.>`,
1513
- `$JS.API.CONSUMER.INFO.${ISSUED}.>`,
1514
- `$JS.API.CONSUMER.DELETE.${ISSUED}.>`,
1515
- "$JS.FC.>",
1516
- ],
1517
- },
1518
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1519
- };
1520
- }
1521
- /** The REGISTRY READER permission set (SPEC 13.20). The evidence store's `STREAM.MSG.GET` is
1522
- * stream-scoped because the key rides the request body: NAMED RESIDUAL, the holder can read every
1523
- * recorded ceiling in the space, so this credential is never a peer's. The records reads are the
1524
- * key list and the per-key `svc` spec/status Direct Get, no stream-wide read; contract artifacts
1525
- * ride the agent's subject-scoped fetch row. No write of any shape. */
1526
- function registryReaderPermissions(space, pr) {
1527
- const ISSUED = `KV_${issuedBucket(space)}`;
1528
- const REC = recordsBucket(space);
1529
- return {
1530
- pub: {
1531
- allow: [
1532
- `$JS.API.STREAM.INFO.${ISSUED}`,
1533
- `$JS.API.STREAM.MSG.GET.${ISSUED}`,
1534
- `$JS.API.STREAM.INFO.KV_${REC}`,
1535
- `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.*.*.spec`,
1536
- `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.svc.*.*.status`,
1537
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
1538
- ],
1539
- },
1540
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1541
- };
1542
- }
1543
- /** The RUN ADMITTER permission set (SPEC 14.8): exactly ONE run's admission record and
1544
- * revocation marker on the admission store (both create-only), plus the leader-served read the
1545
- * create-before-read and the marker's own re-read ride. No other run's keys, no other store. */
1546
- function runAdmitterPermissions(space, pr, pin) {
1547
- const bucket = admissionBucket(space);
1548
- return {
1549
- pub: {
1550
- allow: [
1551
- "$JS.API.INFO",
1552
- `$KV.${bucket}.${admissionKey(pin.endpoint, pin.runId)}`,
1553
- `$KV.${bucket}.${revocationKey(pin.endpoint, pin.runId)}`,
1554
- ...(pin.submission ? [`$KV.${bucket}.${runSubmissionKey(pin.endpoint, pin.submission.caller, pin.submission.id)}`] : []),
1555
- `$JS.API.STREAM.MSG.GET.KV_${bucket}`,
1556
- ],
1557
- },
1558
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1559
- };
1560
- }
1561
- /** The ephemeral, LIFECYCLE-PINNED §13.1 state-write permission set for the STATIC manager's
1562
- * lifecycle executor. One credential per lifecycle OPERATION (activation, terminal,
1563
- * renewal ledger append): every grant names exactly ONE incarnation's keys — the alias head,
1564
- * the uid reservation, the manager slot row, the issuance gate, and the `cred.<uid>.>` ledger
1565
- * family — so a leaked executor cred can move one incarnation's state machine and nothing else.
1566
- *
1567
- * Reads: records reads ride the keyed Direct Get form (the key is ON the subject, so the read
1568
- * grant stays key-pinned); the auth store is leader-served (`allow_direct=false`), so its reads
1569
- * are body-selected `STREAM.MSG.GET` — stream-scoped, NOT key-scoped (the requested key rides
1570
- * the PAYLOAD, which a subject grant cannot see). NAMED RESIDUAL: for its one-shot lifetime the
1571
- * executor can READ (never write) other rows in the auth store. */
1572
- function lifecycleExecutorPermissions(space, pr, pin) {
1573
- const REC = recordsBucket(space), AUTH = epAuthBucket(space);
1574
- // ALL keys DERIVED here from the pin coordinates — the slot key is `staticSlotKey(owner, alias)`,
1575
- // NOT a caller-supplied literal, so a mis-constructed pin can only ever name ONE coherent
1576
- // incarnation's rows (guard the core: the profile enforces the "one incarnation" promise, it
1577
- // does not merely assert it). The builders throw on any non-KV-safe segment.
1578
- const recordKeys = [
1579
- lifecycleHeadKey(pin.owner, pin.actor), uidReservationKey(pin.lifecycleUid), staticSlotKey(pin.owner, pin.alias),
1580
- recordSpecKey(RECORD_KINDS.lifecycle, [pin.owner, pin.actor, pin.lifecycleUid]),
1581
- ];
1582
- return {
1583
- pub: {
1584
- allow: [
1585
- "$JS.API.INFO",
1586
- // Records-store CAS writes — the value-publish carries the key on the subject, so each
1587
- // grant names exactly one of this incarnation's keys.
1588
- ...recordKeys.map((k) => `$KV.${REC}.${k}`),
1589
- // Auth-store CAS writes — this incarnation's gate + its cred-ledger family (renewals
1590
- // append rows here; the terminal's revoke CASes them).
1591
- `$KV.${AUTH}.${issuanceGateKey(pin.lifecycleUid)}`,
1592
- `$KV.${AUTH}.cred.${pin.lifecycleUid}.>`,
1593
- // Keyed Direct Get reads of the same records keys (key-pinned) for direct-aware read
1594
- // paths, PLUS the leader-served `STREAM.MSG.GET` the lazily-bound KV client actually
1595
- // uses — stream-scoped, NOT key-scoped (the requested key rides the PAYLOAD, which a
1596
- // subject grant cannot see). NAMED RESIDUAL: for its one-shot lifetime the executor can
1597
- // READ (never write) other rows in BOTH authority stores — lifecycle metadata, no
1598
- // secrets; every WRITE stays key-pinned above.
1599
- ...recordKeys.map((k) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${k}`),
1600
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
1601
- `$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
1602
- ],
1603
- },
1604
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1605
- };
1606
- }
1607
- /** The SELF-MEDIATED goal-writer profile (spawn-as-action): exactly
1608
- * {@link goalWriterGrants} for ITS endpoint — the goal bind + terminal facts, the goal-record KV
1609
- * writes, and the leader-served fencing reads — plus the connection-scoped reply inbox. Disjoint
1610
- * from the endpoint's serve credential: a serve connection carries none of these rows, so it
1611
- * is broker-denied every goal write. */
1612
- function goalWriterPermissions(space, pr, pin) {
1613
- const g = goalWriterGrants(space, pin.endpoint, pr.connId);
1614
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
1615
- }
1616
- /** The console/CLI per-session CALLER rows: RAILS-ONLY for ONE §13.6 session — pub the
1617
- * session's epoch-pinned `in` rail, sub its `out` rail plus the caller's own reply inbox, and
1618
- * NOTHING else. Deliberately NO KV, NO JetStream API, NO store: the caller drives the terminal over
1619
- * the two core-only eps subjects and never reads the session ledger, so there is no subject-blind
1620
- * store read to widen (SPEC §13.9). The endpoint+sessionId+epoch pin the EXACT pair, so a cred for
1621
- * session A authorizes nothing of session B (no wildcard). `epsSubject` validates every token, so a
1622
- * malformed coordinate refuses at the mint rather than emitting a broadened subject. */
1623
- function sessionCallerPermissions(space, pr, pin) {
1624
- if (!pin)
1625
- throw new Error('permissionsFor: "session-caller" requires opts.sessionCaller ({endpoint, sessionId, epoch}) - the ONE session\'s rails this cred may use');
1626
- return {
1627
- pub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "in")] },
1628
- sub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "out"), `_INBOX_${pr.connId}.>`] },
1629
- };
1630
- }
1631
- /** The own-DM reader rows (#4189): CONSUMER.INFO and MSG.NEXT on the principal's own
1632
- * lifecycle-keyed `dm_` durable, its `$JS.ACK` subtree, and the connection inbox. Nothing else:
1633
- * no publish of any message, no CONSUMER.CREATE (the durable is provisioned, never created), no
1634
- * `$JS.API.INFO`, no STREAM.INFO, no presence, channel, CHAT or `dlv_` row. It is exactly what
1635
- * `EndpointOptions.dmOnly` sends. */
1636
- function dmReaderPermissions(space, pr) {
1637
- if (!pr.lifecycleUid)
1638
- throw new Error('permissionsFor(dm-reader): a lifecycleUid is required - the dm_ durable name is lifecycle-keyed (SPEC 13.1)');
1639
- const DM = dmStream(space), dmD = dmDurable(pr.owner, pr.actor, assertLifecycleToken(pr.lifecycleUid));
1640
- return {
1641
- pub: { allow: [`$JS.API.CONSUMER.INFO.${DM}.${dmD}`, `$JS.API.CONSUMER.MSG.NEXT.${DM}.${dmD}`, `$JS.ACK.${DM}.${dmD}.>`] },
1642
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1643
- };
1644
- }
1645
- /** The manager's per-session SERVING rows: the EXACT mirror of
1646
- * {@link sessionCallerPermissions} with the directions swapped — sub the ONE session's epoch-pinned
1647
- * `in` rail (caller→serving), pub its `out` rail (serving→caller), plus the connection-scoped reply
1648
- * inbox, and NOTHING else. Same asymmetry §13.6 states: "the caller publishes `in` and subscribes
1649
- * `out`; the serving instance the reverse".
1650
- *
1651
- * Deliberately NO KV and NO JetStream API — not even the session ledger. The serving side drives
1652
- * bytes; the ledger is the standing `session-ledger` credential's, on a different connection. That
1653
- * separation is what lets this credential be one-shot and die with its session while the durable
1654
- * revocation authority outlives it (§13.6).
1655
- *
1656
- * This REPLACES a standing writer that held `eps.<endpoint>.*.<epoch>.{in,out}` and so could read
1657
- * and write every live session's bytes at its epoch. The pin makes a credential for session A
1658
- * authorize nothing of session B, and `epsSubject` validates every token, so a malformed
1659
- * coordinate refuses at the mint rather than emitting a broadened subject. */
1660
- function sessionServingPermissions(space, pr, pin) {
1661
- if (!pin)
1662
- throw new Error('permissionsFor: "session-serving" requires opts.sessionServing ({endpoint, sessionId, epoch}) - the ONE session\'s rails this cred may serve');
1663
- return {
1664
- pub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "out")] },
1665
- sub: { allow: [epsSubject(space, pin.endpoint, pin.sessionId, pin.epoch, "in"), `_INBOX_${pr.connId}.>`] },
1666
- };
1667
- }
1668
- /** The manager's SESSION-LEDGER rows: the DEDICATED sessions-bucket rows and nothing
1669
- * else — no session rail of any shape. Needs no pin: the grant carries no endpoint, epoch, or
1670
- * session component, because §13.6's durable revocation authority is per-space, not per-session
1671
- * (it must still be able to resolve and revoke a row after the endpoint that served it is gone).
1672
- * {@link sessionLedgerGrants} carries the row rationale, the §13.9 subject-blindness confinement,
1673
- * and the named `session.*` breadth residual. */
1674
- function sessionLedgerPermissions(space, pr) {
1675
- const g = sessionLedgerGrants(space, pr.connId);
1676
- return { pub: { allow: g.publish }, sub: { allow: g.subscribe } };
1677
- }
1678
- /** The ephemeral, ENDPOINT-INSTANCE-PINNED endpoint-serve executor permission set:
1679
- * the manager mints this per registration/serve-mint op and drives the endpoint
1680
- * registration barrier's `epgate` CAS + the mint fence's `epcred` stage/revoke THROUGH it — never
1681
- * its standing seed/supervisor connection. Every
1682
- * WRITE is key-pinned to exactly ONE (endpoint, instanceId): the gate `epgate.<ep>.<iid>`, its
1683
- * serving ledger family `epcred.<ep>.<iid>.>`, and the registration's two records keys (the
1684
- * instance's `svc` spec + the endpoint's governance head — `registerServiceInstance` drives the
1685
- * slot-take/promote over this same connection). A leaked/mis-constructed executor can move exactly
1686
- * one endpoint instance's serve state and nothing else. The auth store is `allow_direct=false`, so
1687
- * reads are leader-served `STREAM.MSG.GET` (stream-scoped, NOT key-scoped — the key rides the
1688
- * payload); enumeration of the epcred family rides an ordered `keys()` consumer. NAMED RESIDUAL:
1689
- * for its one-shot lifetime the executor can READ (never write) other auth rows — endpoint/
1690
- * credential metadata, no bearer bytes; every WRITE stays key-pinned. */
1691
- function endpointServeExecutorPermissions(space, pr, pin) {
1692
- const AUTH = epAuthBucket(space), REC = recordsBucket(space);
1693
- // DERIVED from (endpoint, instanceId) via the core builders — never a caller literal.
1694
- const gateKey = epgateKey(pin.endpoint, pin.instanceId);
1695
- const credPrefix = epcredFamilyPrefix(pin.endpoint, pin.instanceId);
1696
- const repairKey = eprepairKey(pin.endpoint, pin.instanceId);
1697
- // The registration writes this ONE instance's spec key plus the endpoint's governance head
1698
- // (`registerServiceInstance` PHASE 1/3b: the slot-take + promote ride the SAME executor), and this
1699
- // instance's own svc STATUS key (the manager writes its CONVERGED `ready` status so it
1700
- // is a §13.5 scatter member — `freezeExpectedSet` requires a status caught up to the current
1701
- // registration; the write is epoch-fenced by `writeServiceStatus`).
1702
- const recordKeys = [
1703
- recordSpecKey(RECORD_KINDS.svc, [pin.endpoint, assertLifecycleToken(pin.instanceId, "instanceId")]),
1704
- recordStatusKey(RECORD_KINDS.svc, [pin.endpoint, assertLifecycleToken(pin.instanceId, "instanceId")]),
1705
- recordAtomicKey(GOVERN_HEAD, [pin.endpoint]),
1706
- ];
1707
- return {
1708
- pub: {
1709
- allow: [
1710
- "$JS.API.INFO",
1711
- // The key-pinned WRITE grants: the gate (provision create + barrier freeze/reopen CAS),
1712
- // the serving ledger family (mint-fence stage + barrier revoke), and the registration's
1713
- // two records-store keys (spec CAS + governance slot/promote). The value-publish carries
1714
- // the key on the subject, so each grant names exactly this instance's keys.
1715
- `$KV.${AUTH}.${gateKey}`,
1716
- `$KV.${AUTH}.${repairKey}`,
1717
- `$KV.${AUTH}.${credPrefix}.>`,
1718
- ...recordKeys.map((k) => `$KV.${REC}.${k}`),
1719
- // §13.7 contract-artifact publication: the registration publishes the
1720
- // endpoint's cluster document, closure manifests, and schema roots to the EPC store so
1721
- // callers can fetch-verify-compile the registered digests. A digest subject is a SINGLE
1722
- // hex token (`epc.<64hex>`), so the grant is the single-token `epc.*` form (matching
1723
- // `contractPublisherGrants`), never the multi-token `epc.>`. Digest subjects cannot be
1724
- // key-pinned pre-mint; the store's SHAPE is the defense (ensureContractStore): a digest
1725
- // subject holds exactly one broker-immutable message (max_msgs_per_subject:1 +
1726
- // discard-new-per-subject REJECTS a second publish regardless of the create-only header, so
1727
- // a grant-holder CANNOT append a shadow over a published artifact), deny_delete/deny_purge
1728
- // keep that message, and content addressing (verify-on-read, create-only-winner fallback)
1729
- // makes a wrong-subject write unservable. NAMED RESIDUAL: for its one-shot lifetime the
1730
- // executor can publish NEW digest-addressed artifacts at previously-unused subjects (a
1731
- // bounded storage flood; unreferenced artifacts carry no authority) — it can NOT overwrite,
1732
- // shadow, or replace an existing one.
1733
- `${spacePrefix(space)}.epc.*`,
1734
- // The lost-CAS verify-read `publishContractArtifact` runs when a re-publish (every re-up /
1735
- // restart against an existing store) loses the create-only CAS: it fetches the recorded
1736
- // artifact to confirm the idempotent no-op. BOTH Direct Get forms — the subject-scoped
1737
- // `last_by_subj` (the fast path) and the bare stream form (the create-only-winner
1738
- // `next_by_subj` fallback) — so the publish path never dies on a broker denial regardless
1739
- // of stream config. Without this the manager exits on its SECOND boot (the tester's
1740
- // upgrade-path regression). Reads public content-addressed artifacts only.
1741
- `$JS.API.DIRECT.GET.${epcStreamName(space)}.${spacePrefix(space)}.epc.>`,
1742
- `$JS.API.DIRECT.GET.${epcStreamName(space)}`,
1743
- // Leader-served reads (the auth store is allow_direct=false): stream-scoped MSG.GET (the
1744
- // barrier/fence read the gate + each epcred row), plus the ordered consumer the epcred
1745
- // `keys()` enumeration binds. The records store IS direct-servable, so its reads add the
1746
- // key-pinned DIRECT.GET forms beside the leader-served fallback. NAMED RESIDUAL: reads
1747
- // any row in both stores for its one-shot lifetime (metadata, no bearer bytes).
1748
- `$JS.API.STREAM.MSG.GET.KV_${AUTH}`,
1749
- `$JS.API.CONSUMER.CREATE.KV_${AUTH}.>`,
1750
- `$JS.API.CONSUMER.INFO.KV_${AUTH}.>`,
1751
- `$JS.API.CONSUMER.DELETE.KV_${AUTH}.>`,
1752
- // Ordered value scans acknowledge flow control only for this authorized auth stream.
1753
- `$JS.FC.KV_${AUTH}.>`,
1754
- ...recordKeys.map((k) => `$JS.API.DIRECT.GET.KV_${REC}.$KV.${REC}.${k}`),
1755
- `$JS.API.STREAM.MSG.GET.KV_${REC}`,
1756
- ],
1757
- },
1758
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1759
- };
1760
- }
1761
- /** The ephemeral, TARGET-PINNED DEPROVISIONER permission set — the teardown counterpart
1762
- * to {@link provisionerPermissions}, minted per departed agent inside the manager's `deprovision` tail
1763
- * (`withProvisioner`-style: a fresh scoped cred per teardown is cheap). It deletes exactly the
1764
- * dev/static principal footprint the provisioner created for ONE agent: that agent's two bind-only
1765
- * durables (`dm_local-<actor>`, `dlv_local-<actor>`) and its read-ACL row — pinned BY NAME to the target
1766
- * actor under {@link DEV_OWNER}, so a leaked deprovisioner cred can tear down that one already-dead
1767
- * agent and NOTHING else.
1768
- *
1769
- * Deliberately NOT granted (least-privilege / correctness): the role-SHARED `svc_<role>` TASK durable
1770
- * (one consumer for ALL agents of a role — deleting it on one agent's exit would break its siblings; it
1771
- * lives until space teardown), any peer's `dm_`/`dlv_`/ACL (the grants are target-name-pinned, never
1772
- * `.>`), any MSG.NEXT/MSG.GET/ACK (it deletes mailboxes, never reads a body), and any STREAM
1773
- * DELETE/PURGE (it removes per-agent consumers, never a stream). The `chathist_<id>` history consumers
1774
- * need no grant here — they are ephemeral (`mem_storage`, 30s inactive threshold) and agent-deleted
1775
- * after each read, so they self-clean on the agent's disconnect.
1776
- *
1777
- * Blast radius of a leaked cred (minted for target T): it can delete T's `dm_local-<T>`/`dlv_local-<T>`
1778
- * durables + purge T's ACL row — a denial-of-DELIVERY for T (broken DM/DLV bind + the reader DEFERs on
1779
- * the absent ACL) if fired while T is still alive. It CANNOT read T's bodies, impersonate T, reach any peer, or
1780
- * delete a stream — and it is ephemeral (one per-exit teardown, minted then dropped). Contained and
1781
- * recoverable (re-provision T). */
1782
- function deprovisionerPermissions(space, pr, deprovisionTarget) {
1783
- const DM = dmStream(space), DLV = dlvStream(space);
1784
- const t = deprovisionTargetPrincipal(deprovisionTarget);
1785
- const target = principalKey(t.owner, t.actor);
1786
- return {
1787
- pub: {
1788
- allow: [
1789
- "$JS.API.INFO", // jetstreamManager bootstrap
1790
- // Delete the target LIFECYCLE's two bind-only durables BY EXACT NAME — no `.>`, no cross-agent
1791
- // reach, and no reach into a same-alias successor: its names carry a different uid, so a
1792
- // replayed teardown is broker-DENIED there (SPEC 13.1 / Appendix "deprovisioner").
1793
- `$JS.API.CONSUMER.DELETE.${DM}.${dmDurable(t.owner, t.actor, t.lifecycleUid)}`,
1794
- `$JS.API.CONSUMER.DELETE.${DLV}.${dlvDurable(t.owner, t.actor, t.lifecycleUid)}`,
1795
- `$JS.API.CONSUMER.INFO.${DM}.${dmDurable(t.owner, t.actor, t.lifecycleUid)}`,
1796
- `$JS.API.CONSUMER.INFO.${DLV}.${dlvDurable(t.owner, t.actor, t.lifecycleUid)}`,
1797
- // Purge the target lifecycle's read-ACL row (own-target exact key only — the reader then treats
1798
- // it as an unknown owner). `kvm.open` binds the pre-created bucket; the purge rides
1799
- // `$KV.<aclBucket>.<key>`.
1800
- `$JS.API.STREAM.INFO.KV_${aclBucket(space)}`,
1801
- `$JS.API.DIRECT.GET.KV_${aclBucket(space)}.$KV.${aclBucket(space)}.${aclKey(target.key, t.lifecycleUid)}`,
1802
- `$KV.${aclBucket(space)}.${aclKey(target.key, t.lifecycleUid)}`,
1803
- // Purge the target lifecycle's durable membership rows, one exact key per named concrete
1804
- // channel or family (a family's `>` is `=` in the key, so no grant here is a wildcard). The key
1805
- // embeds the uid, so a successor's row is unreachable by name.
1806
- ...(t.memberChannels.length > 0 ? [`$JS.API.STREAM.INFO.KV_${membersBucket(space)}`] : []),
1807
- ...t.memberChannels.map((ch) => `$JS.API.DIRECT.GET.KV_${membersBucket(space)}.$KV.${membersBucket(space)}.${memberKey(ch, target.key, t.lifecycleUid)}`),
1808
- ...t.memberChannels.map((ch) => `$KV.${membersBucket(space)}.${memberKey(ch, target.key, t.lifecycleUid)}`),
1809
- ],
1810
- },
1811
- // Replies only: the CONSUMER.DELETE PubAcks + KV purge ack land on the per-connection inbox. NO chat/DM/ctl
1812
- // subscription — the deprovisioner serves nothing and reads no feed.
1813
- sub: { allow: [`_INBOX_${pr.connId}.>`] },
1814
- };
1815
- }
1816
- /** The scoped `delivery` daemon permission set (server-side Plane-3 infra; NEVER allow-all, never
1817
- * minted for an agent — `cotal mint` excludes it, like `manager`). Least-privilege: exactly what the
1818
- * fan-out writer + trusted reader + activation catch-up + membership/ACL reads + members-KV writes +
1819
- * the lease + the `ctl.delivery` control service touch. `sub.allow` is the per-identity inbox (all JS
1820
- * pull delivery / KV-watch / request replies land there) PLUS the `ctl.delivery` control subtree it
1821
- * serves; ALL stream/KV reads ride the JS API (publishes), so there is NO native `chat`/`dinbox`/`dlv`
1822
- * subscription — a leaked cred can't natively sniff the mixed pre-auth store. Honest blast radius
1823
- * (delivery-daemon.mdx): it can write any owner's `dlv` (the post-auth store agents trust); the future
1824
- * fan-out/reader cred split bounds that. */
1825
- function deliveryPermissions(space, pr) {
1826
- const p = spacePrefix(space);
1827
- const CHAT = chatStream(space), INBOX = inboxStream(space), DLV = dlvStream(space);
1828
- const PKV = `KV_${presenceBucket(space)}`, CHKV = `KV_${channelBucket(space)}`;
1829
- const MKV = `KV_${membersBucket(space)}`, AKV = `KV_${aclBucket(space)}`, DKV = `KV_${deliveryBucket(space)}`;
1830
- const TASK = taskStream(space), AKVR = `KV_${anycastBucket(space)}`;
1831
- const kvRead = (bucket) => [
1832
- `$JS.API.STREAM.INFO.${bucket}`,
1833
- `$JS.API.STREAM.MSG.GET.${bucket}`, // kv.get
1834
- `$JS.API.CONSUMER.CREATE.${bucket}.>`, // kv.watch ordered consumer
1835
- `$JS.API.CONSUMER.INFO.${bucket}.>`,
1836
- `$JS.API.CONSUMER.DELETE.${bucket}.>`,
1837
- ];
1838
- const pub = [
1839
- "$JS.API.INFO",
1840
- `$JS.API.STREAM.INFO.${CHAT}`, `$JS.API.STREAM.INFO.${INBOX}`, `$JS.API.STREAM.INFO.${DLV}`,
1841
- // Fan-out durable + activation-catch-up ephemerals live on CHAT — the daemon legitimately reads ALL
1842
- // chat (the fan-out consumes the whole stream), so a stream-wide CHAT consumer grant is no
1843
- // escalation. The catch-up ephemeral names (`cu_<owner>_<gen>`) are dynamic, so they can't be
1844
- // name-pinned; CHAT-wide is correct here.
1845
- //
1846
- // BOTH forms, and the bare one is not redundant: a create carrying `filter_subjects` cannot encode
1847
- // its filter in the subject, so the client publishes to the BARE `…CREATE.<CHAT>` while a named
1848
- // consumer goes to the `.>` form. The mediated history read (`readHistory`) builds exactly that
1849
- // multi-filter ephemeral, and with only the `.>` grant it fails with a Permissions Violation on the
1850
- // bare subject — measured, not predicted. The observer profile already carries both for the same
1851
- // reason. Grants the daemon nothing new in substance: it may already create any named consumer on
1852
- // this stream and already reads all of it.
1853
- `$JS.API.CONSUMER.CREATE.${CHAT}`,
1854
- `$JS.API.CONSUMER.CREATE.${CHAT}.>`,
1855
- `$JS.API.CONSUMER.DURABLE.CREATE.${CHAT}.>`,
1856
- `$JS.API.CONSUMER.INFO.${CHAT}.>`,
1857
- `$JS.API.CONSUMER.MSG.NEXT.${CHAT}.>`,
1858
- `$JS.API.CONSUMER.DELETE.${CHAT}.>`,
1859
- `$JS.ACK.${CHAT}.>`,
1860
- // Trusted reader on INBOX — NAME-PINNED to the single `reader` durable (the meaningful confinement:
1861
- // no arbitrary INBOX consumer create against the mixed pre-auth store).
1862
- `$JS.API.CONSUMER.CREATE.${INBOX}.${INBOX_READER_DURABLE}.>`,
1863
- `$JS.API.CONSUMER.DURABLE.CREATE.${INBOX}.${INBOX_READER_DURABLE}`,
1864
- `$JS.API.CONSUMER.INFO.${INBOX}.${INBOX_READER_DURABLE}`,
1865
- `$JS.API.CONSUMER.MSG.NEXT.${INBOX}.${INBOX_READER_DURABLE}`,
1866
- `$JS.API.CONSUMER.DELETE.${INBOX}.${INBOX_READER_DURABLE}`,
1867
- `$JS.ACK.${INBOX}.${INBOX_READER_DURABLE}.>`,
1868
- // The reader removes an entry addressed to a retired lifecycle (its ACL row is tombstoned), so the
1869
- // store does not keep what no reader can ever deliver. Nothing new in substance: the reader can
1870
- // already ack any INBOX entry away.
1871
- `$JS.API.STREAM.MSG.DELETE.${INBOX}`,
1872
- "$JS.FC.>", // ordered-consumer flow control
1873
- // Reads: presence (@mention resolve) + channel registry (delivery class) + members + ACL (re-auth).
1874
- ...kvRead(PKV), ...kvRead(CHKV), ...kvRead(MKV), ...kvRead(AKV),
1875
- // Members-KV WRITE — the daemon is the durable-membership authority (join/leave/activate/catch-up).
1876
- `$KV.${membersBucket(space)}.>`,
1877
- // Delivery lease/readiness KV: read the bucket (renew CAS) + write ONLY lease keys. The
1878
- // CONSUMER.* rows are kv.watch's ordered consumer for the lease-loss watch (#1596) — the same
1879
- // read axis the other kvRead buckets carry, on the bucket this cred already reads point-wise:
1880
- // a watch is a READ of the row's changes, never a write. CONSUMER.DELETE rides with it for the
1881
- // same reason it does on every watched bucket: an ordered consumer rebuilds by deleting its
1882
- // predecessor, and a refused delete strands consumers on every rebuild (measured on the
1883
- // presence bucket; the comment there carries the full story).
1884
- `$JS.API.STREAM.INFO.${DKV}`, `$JS.API.STREAM.MSG.GET.${DKV}`,
1885
- `$JS.API.CONSUMER.CREATE.${DKV}.>`,
1886
- `$JS.API.CONSUMER.INFO.${DKV}.>`,
1887
- `$JS.API.CONSUMER.DELETE.${DKV}.>`,
1888
- `$KV.${deliveryBucket(space)}.lease.*`,
1889
- // The timer writer (SPEC 13.2): the daemon hosts the pump that turns `.schedule` requests into
1890
- // the authoritative `.armed` publishes — without it no workflow pause on the space ever
1891
- // expires. Its consumer rows are the shared timer-writer grant set; both create forms for the
1892
- // same reason CHAT carries both (the client picks by whether the create embeds a filter). The
1893
- // arm itself needs the fence's two leader reads — the `.armed` head on EPT and the checkpoint
1894
- // status on the records KV — and exactly ONE publish: the `.armed` subject. Never `.fire`
1895
- // (the broker's own schedule delivery) and never `.schedule` (it consumes those).
1896
- ...timerWriterGrants(space),
1897
- `$JS.API.CONSUMER.DURABLE.CREATE.${eptReqStreamName(space)}.${timerWriterDurable(space)}`,
1898
- `$JS.API.STREAM.INFO.${eptReqStreamName(space)}`,
1899
- `$JS.API.STREAM.INFO.${eptStreamName(space)}`,
1900
- `$JS.API.STREAM.MSG.GET.${eptStreamName(space)}`,
1901
- `$JS.API.STREAM.INFO.KV_${recordsBucket(space)}`,
1902
- `$JS.API.STREAM.MSG.GET.KV_${recordsBucket(space)}`,
1903
- `${p}.ept.*.*.*.*.armed`,
1904
- // Plane-3 data writes: dinbox (fan-out target) + dlv (post-auth handoff) for ANY lifecycle — the
1905
- // identity slots widen to `.*.*.*` (owner+actor+lifecycleUid: dinbox/dlv are per-LIFECYCLE now,
1906
- // SPEC 13.1; NATS subject arity is exact, so the old two-token form is broker-denied on every
1907
- // three-token write).
1908
- `${p}.dinbox.*.*.*`, `${p}.dlv.*.*.*`,
1909
- // ctl.delivery control REPLIES ONLY (requests arrive on the sub below; the daemon only ever
1910
- // m.respond()s to a requester's reply subject `ctl.delivery.<owner>.<actor>.reply.<n>`). Scoped to
1911
- // the `.reply.>` leaf so the daemon can't publish to the request subjects themselves — tighter than a
1912
- // blanket `ctl.delivery.>` (fact-check precision, review panel). The caller slots widened to `.*.*`.
1913
- `${p}.ctl.delivery.*.*.reply.>`,
1914
- // The privileged delivery-admin rail: same replies-only shape. Requests reach the
1915
- // daemon on the sub below; only the supervisor cred can PUBLISH them (nats-server is the boundary).
1916
- `${p}.ctl.delivery-admin.*.*.reply.>`,
1917
- // LIVENESS REPLIES for the DELIVERY plane (#1577) — same replies-only shape as the two control
1918
- // rails above. The daemon is the only process that can grade its own responder honestly: it
1919
- // knows its own incarnation, so a predecessor's `ready:true` corpse in the lease classifies as
1920
- // stale rather than as its own health. Bounded to the `.reply.` leaf, so it cannot publish to
1921
- // the request subjects and forge a probe from a peer.
1922
- livenessReplyGrant(space, "delivery"),
1923
- // Anycast request status (SPEC §8.1). The daemon reads a request at the seq a take, status or
1924
- // cancel names, and deletes one its sender cancelled while it waited: a read of every request
1925
- // body in the space and a delete of any of them, both bounded by the take record. It owns the
1926
- // records bucket, creating it on a mesh that predates it, and lists it for the maintenance pass.
1927
- // It DMs a request's sender from its own principal only, and answers takes on their bounded
1928
- // reply leaf.
1929
- `$JS.API.STREAM.INFO.${TASK}`,
1930
- `$JS.API.STREAM.MSG.GET.${TASK}`,
1931
- `$JS.API.STREAM.MSG.DELETE.${TASK}`,
1932
- `$JS.API.STREAM.CREATE.${AKVR}`,
1933
- ...kvRead(AKVR),
1934
- `$JS.API.DIRECT.GET.${AKVR}.>`,
1935
- `$KV.${anycastBucket(space)}.>`,
1936
- unicastSubject(space, "*", "*", pr.owner, pr.actor), // inst.*.*.<o>.<a>: a notice to a sender, as itself
1937
- takeReplyGrant(space),
1938
- ];
1939
- const sub = [
1940
- `_INBOX_${pr.connId}.>`,
1941
- takeServeFilter(space), // serve anycast takes (queue-grouped; role + owner+actor caller slots)
1942
- `${p}.ctl.delivery.*.*`, // serve the delivery control service (queue-grouped; owner+actor caller slots)
1943
- `${p}.ctl.delivery-admin.*.*`, // serve the privileged admin rail (reloadCreds; eviction executor next)
1944
- // Serve the delivery plane's liveness probe (#1577), queue-grouped. Presence-only: the handler
1945
- // reduces the lease row to one enum before replying, so this subscription lets the daemon ANSWER
1946
- // a peer without any peer gaining a read of the lease.
1947
- livenessServeFilter(space, "delivery"),
1948
- ];
1949
- return { pub: { allow: pub }, sub: { allow: sub } };
1950
- }
1951
- /** The scoped DATA-account `membership-rw` permission set (the graph feed's conn B; NEVER allow-all,
1952
- * never minted for an agent — `cotal mint` excludes it, like `manager`/`delivery`). Least-privilege:
1953
- * READ the members registry (the durable arm of the merge) + READ/WRITE the one derived membership
1954
- * bucket, and nothing else. It holds NO chat/DM/anycast/ctl grant and never touches `$SYS` (account
1955
- * isolation keeps the system-account CONNZ read on the SEPARATE conn-A cred). A leaked conn-B cred can
1956
- * read durable-membership records and forge the feed — bounded to "dashboard integrity" by the
1957
- * display-only invariant; it reads no message bodies and admins nothing. */
1958
- function membershipRwPermissions(space, pr) {
1959
- const MKV = `KV_${membersBucket(space)}`; // durable arm — read
1960
- const MEMKV = `KV_${membershipBucket(space)}`; // derived feed — read (diff/prune) + write
1961
- const kvRead = (bucket) => [
1962
- `$JS.API.STREAM.INFO.${bucket}`,
1963
- `$JS.API.STREAM.MSG.GET.${bucket}`, // kv.get
1964
- `$JS.API.CONSUMER.CREATE.${bucket}.>`, // kv.keys()/kv.watch ordered consumer
1965
- `$JS.API.CONSUMER.INFO.${bucket}.>`,
1966
- `$JS.API.CONSUMER.DELETE.${bucket}.>`,
1967
- ];
1968
- const pub = [
1969
- "$JS.API.INFO",
1970
- ...kvRead(MKV),
1971
- ...kvRead(MEMKV),
1972
- `$KV.${membershipBucket(space)}.>`, // write derived feed (kv.put + kv.delete)
1973
- "$JS.FC.>", // ordered-consumer flow control
1974
- ];
1975
- return { pub: { allow: pub }, sub: { allow: [`_INBOX_${pr.connId}.>`] } };
1976
- }
1977
- /** The scoped SYSTEM-account `membership-observer` permission set (the graph feed's conn A). An EXPLICIT
1978
- * block is MANDATORY: a system-account user with NO permissions block defaults to ALLOW-ALL = full
1979
- * `$SYS` = broker admin (verified — pre-flight spike + docs). Least-privilege allowlist:
1980
- * - **pub:** the account-scoped CONNZ request subject ONLY (not server-wide `PING.CONNZ`, not
1981
- * `REQ.SERVER.*`/`REQ.CLAIMS.*`).
1982
- * - **sub:** the scoped reply inbox (`<MEMBERSHIP_INBOX_PREFIX>.>`) + this ONE account's
1983
- * CONNECT/DISCONNECT events (re-poll triggers) — never `$SYS.ACCOUNT.*.…` (cross-tenant) nor
1984
- * `$SYS.ACCOUNT.<id>.>` (pulls in SUBSZ/JSZ/purge).
1985
- * No `$SYS.>` deny that would shadow the allows (deny-beats-allow). A leaked conn-A cred enumerates THIS
1986
- * account's connections (silent readers + nkeys) and can forge the feed; it reads no bodies, touches no
1987
- * other account, and admins no server. */
1988
- function membershipObserverPermissions(accountId) {
1989
- return {
1990
- pub: { allow: [connzRequestSubject(accountId)] },
1991
- sub: {
1992
- allow: [
1993
- `${MEMBERSHIP_INBOX_PREFIX}.>`,
1994
- accountConnectSubject(accountId),
1995
- accountDisconnectSubject(accountId),
1996
- ],
1997
- },
1998
- };
1999
- }
2000
- /** The KICK-ONLY connection-evictor permission set — a SYSTEM-account user that can do
2001
- * exactly ONE thing: `$SYS.REQ.SERVER.*.KICK` (disconnect a live client by cid). It CANNOT read
2002
- * CONNZ (discovery stays on the separate observer cred — never one broad sys user that both
2003
- * enumerates and kills), touch any other `$SYS` verb, or reach another account's data. A leaked
2004
- * evictor cred can DoS live connections on this broker (KICK is not account-scoped — the honest
2005
- * blast radius), which is why it is a HIGH-POWER standing credential: minted only at `up`,
2006
- * rate-limited + audited by its one caller (the delivery daemon), and its cid/server-id inputs come
2007
- * only from the observer's own CONNZ scan, never a user-facing API. Wildcard `*` over server id
2008
- * because a cluster's server ids aren't known at mint time; the scan pins the exact id per KICK. */
2009
- function connectionEvictorPermissions() {
2010
- return {
2011
- pub: { allow: ["$SYS.REQ.SERVER.*.KICK"] },
2012
- // Request/reply KICK replies land on the client's default inbox; no other subscription — it
2013
- // serves nothing and reads no feed.
2014
- sub: { allow: ["_INBOX.>"] },
2015
- };
2016
- }
2017
- export { INSTRUMENT_PROFILES, connectionEvictorPermissions, endpointServePermissions, membershipObserverPermissions };
647
+ export { INSTRUMENT_PROFILES };
648
+ export { connectionEvictorPermissions, endpointServePermissions, membershipObserverPermissions, listingGrantRows } from "./provision-permission-builders.js";
2018
649
  //# sourceMappingURL=provision-permissions.js.map