@kumiai/mls 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/policy.js ADDED
@@ -0,0 +1,191 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { defaultProposalTypes, isDefaultProposal } from 'ts-mls';
3
+ import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
+ function bytesEqual(a, b) {
5
+ if (a.length !== b.length) {
6
+ return false;
7
+ }
8
+ for(let i = 0; i < a.length; i++){
9
+ if (a[i] !== b[i]) {
10
+ return false;
11
+ }
12
+ }
13
+ return true;
14
+ }
15
+ /**
16
+ * Fail-closed admin check: a leaf that resolves to no DID, or a DID absent from
17
+ * the roster, or one holding any role but `admin`, is not an admin. An undefined
18
+ * leaf (external commit with no committer leaf) is never an admin.
19
+ */ function isAdmin(context, leafIndex) {
20
+ if (leafIndex === undefined) {
21
+ return false;
22
+ }
23
+ const did = context.didOfLeaf(leafIndex);
24
+ if (did === undefined) {
25
+ return false;
26
+ }
27
+ return context.baseRoster.roles.get(normalizeDID(did)) === 'admin';
28
+ }
29
+ /**
30
+ * The group-context-extensions rule: an admin may replace the extension list
31
+ * only to move the ledger-head extension to the head this commit's envelope
32
+ * accounts for. A GCE proposal replaces the *entire* list, so the proposed list
33
+ * must positionally equal the current list — same length, same extension types in
34
+ * the same positions, byte-identical data — with the single exception of the
35
+ * ledger_head entry, whose data must equal the expected head. This pins the anchor
36
+ * and every other extension: an admin cannot inject or strip an extension (e.g.
37
+ * external_senders, which grants a non-member the ability to inject proposals)
38
+ * inside an otherwise-valid head move.
39
+ *
40
+ * The head must equal the current head extended by the envelope's entry ids, in
41
+ * envelope order. A head moved to anything else — including moved at all by a
42
+ * commit that enacts nothing — would stop proving which entries the group has
43
+ * enacted, which is the omission hole the head exists to close.
44
+ */ function evaluateGroupContextExtensions(extensions, context) {
45
+ const expected = context.currentExtensions.map((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE ? {
46
+ extensionType: LEDGER_HEAD_EXTENSION_TYPE,
47
+ extensionData: context.expectedHeadExtensionData
48
+ } : ext);
49
+ if (extensions.length !== expected.length) return 'reject';
50
+ for(let i = 0; i < expected.length; i++){
51
+ const got = extensions[i];
52
+ const want = expected[i];
53
+ if (got.extensionType !== want.extensionType) return 'reject';
54
+ // Both sides must be raw bytes to byte-compare. ts-mls's own extensionsEqual
55
+ // is not re-exported, so this hand-rolled compare only handles Uint8Array
56
+ // extensionData; a default-typed (decoded-object) extension — e.g.
57
+ // external_senders or required_capabilities — fails the instanceof guard and
58
+ // is rejected even when it is an honest, unmodified carry-over. That is
59
+ // fail-closed liveness, not a security gap: no group in this repo anchors
60
+ // such an extension today. Revisit this compare if one is introduced.
61
+ if (!(got.extensionData instanceof Uint8Array) || !(want.extensionData instanceof Uint8Array) || !bytesEqual(got.extensionData, want.extensionData)) {
62
+ return 'reject';
63
+ }
64
+ }
65
+ return 'accept';
66
+ }
67
+ /**
68
+ * Apply one proposal's row using the given effective sender. Unknown or custom
69
+ * proposal types fail closed. `external_init` is evaluated at the commit level,
70
+ * never here, so it rejects if it reaches a per-proposal row (a standalone
71
+ * external_init).
72
+ */ function evaluateProposal(proposal, effectiveSender, context) {
73
+ if (!isDefaultProposal(proposal)) {
74
+ return 'reject';
75
+ }
76
+ switch(proposal.proposalType){
77
+ case defaultProposalTypes.add:
78
+ case defaultProposalTypes.psk:
79
+ case defaultProposalTypes.reinit:
80
+ return isAdmin(context, effectiveSender) ? 'accept' : 'reject';
81
+ case defaultProposalTypes.remove:
82
+ {
83
+ // A removed admin must have been demoted in this same envelope: the candidate
84
+ // roster then shows them `member`. Still `admin` here means no demotion rode the
85
+ // commit. Checked before the self-removal shortcut, so an admin cannot self-remove
86
+ // without demoting itself.
87
+ const removedDID = context.didOfLeaf(proposal.remove.removed);
88
+ if (removedDID !== undefined && context.candidateRoster.roles.get(normalizeDID(removedDID)) === 'admin') {
89
+ return 'reject';
90
+ }
91
+ if (isAdmin(context, effectiveSender)) {
92
+ return 'accept';
93
+ }
94
+ return effectiveSender !== undefined && proposal.remove.removed === effectiveSender ? 'accept' : 'reject';
95
+ }
96
+ case defaultProposalTypes.update:
97
+ return 'accept';
98
+ case defaultProposalTypes.group_context_extensions:
99
+ return isAdmin(context, effectiveSender) ? evaluateGroupContextExtensions(proposal.groupContextExtensions.extensions, context) : 'reject';
100
+ default:
101
+ return 'reject';
102
+ }
103
+ }
104
+ /**
105
+ * The whole-commit external-init rule. An external commit joins by proving
106
+ * control of a roster DID's key and removing that DID's stale leaf, so it is
107
+ * accepted only when `externalCommitDID` is a roster member and the commit's
108
+ * proposals are exactly one `external_init` plus one `remove` of the leaf whose
109
+ * DID equals `externalCommitDID` — nothing else.
110
+ */ function evaluateExternalCommit(proposals, context) {
111
+ const did = context.externalCommitDID;
112
+ if (did === undefined || !context.baseRoster.roles.has(normalizeDID(did))) {
113
+ return 'reject';
114
+ }
115
+ if (proposals.length !== 2) {
116
+ return 'reject';
117
+ }
118
+ let sawExternalInit = false;
119
+ let removeTarget;
120
+ for (const { proposal } of proposals){
121
+ if (!isDefaultProposal(proposal)) {
122
+ return 'reject';
123
+ }
124
+ if (proposal.proposalType === defaultProposalTypes.external_init) {
125
+ sawExternalInit = true;
126
+ } else if (proposal.proposalType === defaultProposalTypes.remove) {
127
+ removeTarget = proposal.remove.removed;
128
+ } else {
129
+ return 'reject';
130
+ }
131
+ }
132
+ if (!sawExternalInit || removeTarget === undefined) {
133
+ return 'reject';
134
+ }
135
+ return context.didOfLeaf(removeTarget) === did ? 'accept' : 'reject';
136
+ }
137
+ /**
138
+ * Pure receiving-side commit policy. Given the resolved context, decides whether
139
+ * an incoming commit or standalone proposal is admissible. Never throws.
140
+ *
141
+ * Per proposal the effective sender is the proposal's own `senderLeafIndex` when
142
+ * present, else the committer's — a commit may carry by-reference proposals
143
+ * authored by other members, so checking only the committer would let an admin
144
+ * launder a member's Remove. A commit is accepted only when every proposal
145
+ * passes its row; the first failing proposal rejects the whole commit. A commit
146
+ * with no proposals is a key rotation any member may make. When any proposal is
147
+ * an `external_init`, the whole commit is judged by the external-init rule rather
148
+ * than the per-proposal loop.
149
+ *
150
+ * One rule is not a proposal's own: a commit that enacts ledger entries must carry
151
+ * a group-context-extensions proposal, or it would enact entries without moving the
152
+ * head, and the head would stop covering the ledger.
153
+ */ export function defaultCommitPolicy(incoming, context) {
154
+ if (incoming.kind === 'proposal') {
155
+ const { proposal, senderLeafIndex } = incoming.proposal;
156
+ return evaluateProposal(proposal, senderLeafIndex, context);
157
+ }
158
+ const { proposals, senderLeafIndex } = incoming;
159
+ if (context.commitEnactsEntries && !proposals.some(({ proposal })=>proposal.proposalType === defaultProposalTypes.group_context_extensions)) {
160
+ return 'reject';
161
+ }
162
+ if (proposals.length === 0) {
163
+ return 'accept';
164
+ }
165
+ if (proposals.some(({ proposal })=>proposal.proposalType === defaultProposalTypes.external_init)) {
166
+ return evaluateExternalCommit(proposals, context);
167
+ }
168
+ for (const { proposal, senderLeafIndex: proposalSender } of proposals){
169
+ const effectiveSender = proposalSender ?? senderLeafIndex;
170
+ if (evaluateProposal(proposal, effectiveSender, context) === 'reject') {
171
+ return 'reject';
172
+ }
173
+ }
174
+ return 'accept';
175
+ }
176
+ /**
177
+ * Thrown by the caller's resolver path when the entry bodies an envelope names
178
+ * cannot be resolved from the ledger. Carries the unresolved ids. Defined here
179
+ * because it belongs to the commit-policy resolution boundary, but it is never
180
+ * thrown by {@link defaultCommitPolicy}, which is pure and total.
181
+ */ export class MissingLedgerEntriesError extends Error {
182
+ #ids;
183
+ constructor(ids){
184
+ super(`ledger entries could not be resolved: ${ids.join(', ')}`);
185
+ this.name = 'MissingLedgerEntriesError';
186
+ this.#ids = ids;
187
+ }
188
+ /** The entry ids named by the envelope that could not be resolved. */ get ids() {
189
+ return this.#ids;
190
+ }
191
+ }
@@ -0,0 +1,45 @@
1
+ import type { GroupAnchor } from './anchor.js';
2
+ import { type FoldDrop, type FoldInput, type LedgerReducer } from './fold.js';
3
+ /** The permission a DID holds in the group: full control, or membership only. */
4
+ export type GroupPermission = 'admin' | 'member';
5
+ /** The ledger entry `type` the roster projects. */
6
+ export declare const ROLE_ENTRY_TYPE = "group.role";
7
+ /** A role claim's value: the permission the subject is granted. */
8
+ export type RoleValue = GroupPermission;
9
+ /**
10
+ * Folded roster: every DID that has been granted a permission, keyed by
11
+ * normalized DID. The map is DID-keyed rather than leaf-keyed, so it can hold a
12
+ * role for a DID that has no MLS membership yet.
13
+ */
14
+ export type RosterState = {
15
+ roles: ReadonlyMap<string, GroupPermission>;
16
+ };
17
+ /** Count the admins in a roster state. */
18
+ export declare function adminCount(state: RosterState): number;
19
+ /**
20
+ * Self-referential role reducer. Authority is rooted at the genesis anchor (the
21
+ * creator is the epoch-0 admin) and grows only through admins-so-far: every
22
+ * grant or demotion must be issued by a DID already an admin in the state
23
+ * accumulated from strictly-earlier entries. That state-so-far check is what
24
+ * makes rotation sound — an admin can demote the very admin that promoted them
25
+ * without retroactively voiding their own earlier grants.
26
+ *
27
+ * This reducer knows neither the group it belongs to nor the empty-admin guard.
28
+ * {@link foldRoster} is the safe entry point that adds both; this piece is the
29
+ * composable seed / authority / apply the fold turns on.
30
+ */
31
+ export declare const roleReducer: LedgerReducer<RoleValue, RosterState>;
32
+ /**
33
+ * Fold a group's `group.role` ledger into the current roster.
34
+ *
35
+ * The reducer cannot filter by `groupID` on its own — the anchor carries no
36
+ * group id — so the group is passed explicitly and closed over here: an entry
37
+ * signed for another group is dropped even though its signature verifies, since
38
+ * the signed `groupID` is the only defence against a replayed grant. The
39
+ * empty-admin guard is layered in the same place: an entry that would leave the
40
+ * roster with zero admins is dropped, so the group can never be bricked into a
41
+ * state where nobody can add, remove, promote, or demote. Both drops are routed
42
+ * through `verifyAuthority` so they reach the optional `onDrop` observer that
43
+ * {@link foldLedger} calls; only there does the fold surface a skip.
44
+ */
45
+ export declare function foldRoster(entries: Array<FoldInput<RoleValue>>, anchor: GroupAnchor, groupID: string, onDrop?: (drop: FoldDrop) => void): RosterState;
package/lib/roster.js ADDED
@@ -0,0 +1,72 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { foldLedger } from './fold.js';
3
+ /** The ledger entry `type` the roster projects. */ export const ROLE_ENTRY_TYPE = 'group.role';
4
+ /** Count the admins in a roster state. */ export function adminCount(state) {
5
+ let count = 0;
6
+ for (const permission of state.roles.values()){
7
+ if (permission === 'admin') {
8
+ count += 1;
9
+ }
10
+ }
11
+ return count;
12
+ }
13
+ /**
14
+ * Self-referential role reducer. Authority is rooted at the genesis anchor (the
15
+ * creator is the epoch-0 admin) and grows only through admins-so-far: every
16
+ * grant or demotion must be issued by a DID already an admin in the state
17
+ * accumulated from strictly-earlier entries. That state-so-far check is what
18
+ * makes rotation sound — an admin can demote the very admin that promoted them
19
+ * without retroactively voiding their own earlier grants.
20
+ *
21
+ * This reducer knows neither the group it belongs to nor the empty-admin guard.
22
+ * {@link foldRoster} is the safe entry point that adds both; this piece is the
23
+ * composable seed / authority / apply the fold turns on.
24
+ */ export const roleReducer = {
25
+ type: ROLE_ENTRY_TYPE,
26
+ seed: (anchor)=>({
27
+ roles: new Map([
28
+ [
29
+ normalizeDID(anchor.creatorDID),
30
+ 'admin'
31
+ ]
32
+ ])
33
+ }),
34
+ verifyAuthority: (verified, stateSoFar)=>stateSoFar.roles.get(normalizeDID(verified.issuer)) === 'admin',
35
+ apply: (verified, stateSoFar)=>{
36
+ const roles = new Map(stateSoFar.roles);
37
+ roles.set(normalizeDID(verified.entry.subject), verified.entry.value);
38
+ return {
39
+ roles
40
+ };
41
+ }
42
+ };
43
+ /**
44
+ * Fold a group's `group.role` ledger into the current roster.
45
+ *
46
+ * The reducer cannot filter by `groupID` on its own — the anchor carries no
47
+ * group id — so the group is passed explicitly and closed over here: an entry
48
+ * signed for another group is dropped even though its signature verifies, since
49
+ * the signed `groupID` is the only defence against a replayed grant. The
50
+ * empty-admin guard is layered in the same place: an entry that would leave the
51
+ * roster with zero admins is dropped, so the group can never be bricked into a
52
+ * state where nobody can add, remove, promote, or demote. Both drops are routed
53
+ * through `verifyAuthority` so they reach the optional `onDrop` observer that
54
+ * {@link foldLedger} calls; only there does the fold surface a skip.
55
+ */ export function foldRoster(entries, anchor, groupID, onDrop) {
56
+ const scoped = {
57
+ type: roleReducer.type,
58
+ seed: roleReducer.seed,
59
+ verifyAuthority: (verified, stateSoFar)=>{
60
+ if (verified.entry.groupID !== groupID) {
61
+ return false;
62
+ }
63
+ if (!roleReducer.verifyAuthority(verified, stateSoFar)) {
64
+ return false;
65
+ }
66
+ // Fold-step guard: reject a claim whose would-be next state has no admin.
67
+ return adminCount(roleReducer.apply(verified, stateSoFar)) > 0;
68
+ },
69
+ apply: roleReducer.apply
70
+ };
71
+ return foldLedger(entries, anchor, scoped, onDrop);
72
+ }
package/lib/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { DIDCache, DIDResolver } from '@kokuin/token';
2
2
  import type { Capabilities, CryptoProvider, GroupContextExtension, IncomingMessageCallback, KeyPackage, PrivateKeyPackage } from 'ts-mls';
3
- import type { GroupPermission } from './capability.js';
3
+ import type { VerifiedLedgerEntry } from './ledger.js';
4
4
  export type GroupOptions = {
5
5
  /** Custom CryptoProvider for ts-mls. Defaults to nobleCryptoProvider. */
6
6
  cryptoProvider?: CryptoProvider;
@@ -16,12 +16,35 @@ export type GroupOptions = {
16
16
  capabilities?: Capabilities;
17
17
  /**
18
18
  * Default commit policy for the resulting GroupHandle. Invoked during
19
- * processMessage/decrypt for each incoming commit; return 'reject' to refuse
20
- * a commit (the handle stays at its pre-commit epoch and processMessage
21
- * throws CommitRejectedError). Overridable per call.
19
+ * processMessage for each incoming commit or standalone proposal; return
20
+ * 'reject' to refuse it (the handle stays at its pre-commit epoch and
21
+ * processMessage throws CommitRejectedError). Overridable per call.
22
+ *
23
+ * Providing this REPLACES the anchored defaultCommitPolicy entirely — it does
24
+ * not compose with it. A caller that sets this for any reason (e.g. to
25
+ * observe or add one extra rule) silently disables all default permission
26
+ * enforcement for the resulting handle; only the decode/fold hard-reject
27
+ * still applies. Callers who want to extend rather than replace the default
28
+ * policy must call defaultCommitPolicy themselves from within their own
29
+ * callback.
22
30
  */
23
31
  commitPolicy?: IncomingMessageCallback;
24
- /** Optional DID cache for resolving did:peer:4 issuers in capability chains. Default: in-memory. */
32
+ /**
33
+ * Fetch control-ledger entry bodies the local ledger lacks. Invoked in the
34
+ * commit pre-pass with the content ids an incoming commit's envelope names but
35
+ * the handle does not hold. Returns signed tokens; the pre-pass keeps only a
36
+ * token whose content-addressed digest matches the requested id and whose
37
+ * signature verifies, so the resolver is untrusted. When absent, a commit that
38
+ * names an unheld entry throws MissingLedgerEntriesError.
39
+ */
40
+ resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
41
+ /**
42
+ * Surface the notarized non-`group.role` ledger entries an accepted commit
43
+ * carried, in envelope order. Never read by kumiai — `group.role` entries fold
44
+ * into the roster, everything else is handed to the consumer here.
45
+ */
46
+ onLedgerEntries?: (entries: Array<VerifiedLedgerEntry>) => void;
47
+ /** Optional DID cache for resolving did:peer:4 issuers when verifying ledger entries. Default: in-memory. */
25
48
  cache?: DIDCache;
26
49
  /** Optional resolver for did:peer:4 short forms not in cache. */
27
50
  resolver?: DIDResolver;
@@ -36,14 +59,11 @@ export type GroupSyncScope = {
36
59
  export type Invite = {
37
60
  /** Group ID the invite is for */
38
61
  groupID: string;
39
- /** Delegated membership capability token (stringified) for the invitee */
40
- capabilityToken: string;
41
- /** The full capability chain to validate the invite */
42
- capabilityChain: Array<string>;
43
- /** Permission level being granted */
44
- permission: GroupPermission;
45
62
  /** Inviter's DID */
46
63
  inviterID: string;
64
+ /** The group's whole signed control ledger, in application order, so the joiner
65
+ * folds the same roster as everyone else. The invitee's own role entry is last. */
66
+ ledgerEntries: Array<string>;
47
67
  };
48
68
  export type KeyPackageBundle = {
49
69
  /** MLS key package (binary) */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
5
  "description": "E2EE group identity and membership for Enkaku using MLS",
6
6
  "keywords": [
@@ -25,9 +25,8 @@
25
25
  ],
26
26
  "sideEffects": false,
27
27
  "dependencies": {
28
- "@kokuin/capability": "^0.1.0",
29
28
  "@sozai/runtime": "^0.1.0",
30
- "@kokuin/token": "^0.1.0",
29
+ "@kokuin/token": "^0.2.0",
31
30
  "@noble/ciphers": "^2.1.1",
32
31
  "@noble/curves": "^2.0.1",
33
32
  "@noble/hashes": "^2.0.0",
@@ -1,47 +0,0 @@
1
- import { type CapabilityPayload, type CapabilityToken, type DelegationChainOptions } from '@kokuin/capability';
2
- import { type SigningIdentity } from '@kokuin/token';
3
- export type GroupPermission = 'admin' | 'member' | 'read';
4
- export type GroupCapabilityPayload = CapabilityPayload & {
5
- act: Array<GroupPermission>;
6
- res: Array<string>;
7
- };
8
- /**
9
- * Creates a root admin capability for a group.
10
- * The signer becomes the group creator and root admin (iss === sub).
11
- */
12
- export declare function createGroupCapability(identity: SigningIdentity, groupID: string): Promise<CapabilityToken>;
13
- export type DelegateGroupMembershipParams = {
14
- identity: SigningIdentity;
15
- groupID: string;
16
- recipientDID: string;
17
- permission: GroupPermission;
18
- expiration?: number;
19
- parentCapability?: string;
20
- };
21
- /**
22
- * Creates a delegated membership capability for a group.
23
- * The signer must be an admin with a valid capability chain.
24
- */
25
- export declare function delegateGroupMembership(params: DelegateGroupMembershipParams): Promise<CapabilityToken>;
26
- export type ValidateGroupCapabilityParams = {
27
- tokenData: string;
28
- groupID: string;
29
- delegationChain?: Array<string>;
30
- options?: DelegationChainOptions;
31
- };
32
- /**
33
- * Validates that a capability token grants the specified permission for a group.
34
- *
35
- * Resource matching accepts three forms:
36
- * - `group/<groupID>/*` — full access to a single group (what
37
- * {@link createGroupCapability} and {@link delegateGroupMembership} issue)
38
- * - `group/<groupID>/<suffix>` — scoped access within a single group
39
- * - `*` — **global wildcard**: grants access to EVERY group, and to every
40
- * other resource type in the stack that honours `*`. This is intentionally
41
- * supported so root identities holding a stack-wide capability can operate
42
- * on any group, but its blast radius is total: a leaked, stolen or
43
- * over-delegated `res: ['*']` token compromises all groups at once. Never
44
- * issue `*` to regular members or services — delegate `group/<groupID>/*`
45
- * (or narrower) instead, with an `exp` and a verifiable delegation chain.
46
- */
47
- export declare function validateGroupCapability(params: ValidateGroupCapabilityParams): Promise<CapabilityToken>;
package/lib/capability.js DELETED
@@ -1,79 +0,0 @@
1
- import { assertCapabilityToken, checkDelegationChain, createCapability } from '@kokuin/capability';
2
- import { normalizeDID, verifyToken } from '@kokuin/token';
3
- /**
4
- * Creates a root admin capability for a group.
5
- * The signer becomes the group creator and root admin (iss === sub).
6
- */ export async function createGroupCapability(identity, groupID) {
7
- return await createCapability(identity, {
8
- sub: identity.id,
9
- aud: identity.id,
10
- act: '*',
11
- res: [
12
- `group/${groupID}/*`
13
- ]
14
- });
15
- }
16
- /**
17
- * Creates a delegated membership capability for a group.
18
- * The signer must be an admin with a valid capability chain.
19
- */ export async function delegateGroupMembership(params) {
20
- const { identity, groupID, recipientDID, permission, expiration, parentCapability } = params;
21
- // In Enkaku's capability model, `sub` is the resource owner (stays the same
22
- // through the chain) and `aud` is who can exercise the capability (the recipient).
23
- const payload = {
24
- sub: identity.id,
25
- aud: recipientDID,
26
- act: [
27
- permission
28
- ],
29
- res: [
30
- `group/${groupID}/*`
31
- ]
32
- };
33
- if (expiration != null) {
34
- payload.exp = expiration;
35
- }
36
- return await createCapability(identity, payload, undefined, parentCapability != null ? {
37
- parentCapability
38
- } : undefined);
39
- }
40
- /**
41
- * Validates that a capability token grants the specified permission for a group.
42
- *
43
- * Resource matching accepts three forms:
44
- * - `group/<groupID>/*` — full access to a single group (what
45
- * {@link createGroupCapability} and {@link delegateGroupMembership} issue)
46
- * - `group/<groupID>/<suffix>` — scoped access within a single group
47
- * - `*` — **global wildcard**: grants access to EVERY group, and to every
48
- * other resource type in the stack that honours `*`. This is intentionally
49
- * supported so root identities holding a stack-wide capability can operate
50
- * on any group, but its blast radius is total: a leaked, stolen or
51
- * over-delegated `res: ['*']` token compromises all groups at once. Never
52
- * issue `*` to regular members or services — delegate `group/<groupID>/*`
53
- * (or narrower) instead, with an `exp` and a verifiable delegation chain.
54
- */ export async function validateGroupCapability(params) {
55
- const { tokenData, groupID, delegationChain, options } = params;
56
- const token = await verifyToken(tokenData, {
57
- cache: options?.cache,
58
- resolver: options?.resolver
59
- });
60
- assertCapabilityToken(token);
61
- // Verify the resource matches the group. `res === '*'` is the global
62
- // wildcard intentionally kept for root identities — see the JSDoc above
63
- // for its blast radius before touching this condition.
64
- const expectedResource = `group/${groupID}/`;
65
- const resources = Array.isArray(token.payload.res) ? token.payload.res : [
66
- token.payload.res
67
- ];
68
- const matchesGroup = resources.some((res)=>res === `group/${groupID}/*` || res.startsWith(expectedResource) || res === '*');
69
- if (!matchesGroup) {
70
- throw new Error(`Invalid capability: does not grant access to group ${groupID}`);
71
- }
72
- // Verify delegation chain if provided
73
- if (delegationChain != null && delegationChain.length > 0) {
74
- await checkDelegationChain(token.payload, delegationChain, options);
75
- } else if (normalizeDID(token.payload.iss) !== normalizeDID(token.payload.sub)) {
76
- throw new Error('Invalid capability: delegation chain required for delegated capabilities');
77
- }
78
- return token;
79
- }