@kya-os/checkpoint-shared 1.2.0 → 1.2.1

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/deploy/index.d.mts +380 -0
  2. package/dist/deploy/index.d.ts +380 -0
  3. package/dist/deploy/index.js +221 -0
  4. package/dist/deploy/index.mjs +207 -0
  5. package/dist/gateway/index.d.mts +575 -0
  6. package/dist/gateway/index.d.ts +575 -0
  7. package/dist/gateway/index.js +98 -0
  8. package/dist/gateway/index.mjs +88 -0
  9. package/dist/index.d.mts +1370 -84
  10. package/dist/index.d.ts +1370 -84
  11. package/dist/index.js +2887 -2205
  12. package/dist/index.mjs +2844 -2204
  13. package/dist/mcpi/agentshield-api/index.d.mts +47 -0
  14. package/dist/mcpi/agentshield-api/index.d.ts +47 -0
  15. package/dist/mcpi/agentshield-api/index.js +2 -0
  16. package/dist/mcpi/agentshield-api/index.mjs +1 -0
  17. package/dist/mcpi/approval-grant/index.d.mts +79 -0
  18. package/dist/mcpi/approval-grant/index.d.ts +79 -0
  19. package/dist/mcpi/approval-grant/index.js +157 -0
  20. package/dist/mcpi/approval-grant/index.mjs +150 -0
  21. package/dist/mcpi/dashboard-config/index.d.mts +14075 -0
  22. package/dist/mcpi/dashboard-config/index.d.ts +14075 -0
  23. package/dist/mcpi/dashboard-config/index.js +517 -0
  24. package/dist/mcpi/dashboard-config/index.mjs +492 -0
  25. package/dist/test-fixtures/index.d.mts +17 -8
  26. package/dist/test-fixtures/index.d.ts +17 -8
  27. package/dist/test-fixtures/index.js +73 -7
  28. package/dist/test-fixtures/index.mjs +73 -8
  29. package/dist/tool-protection/index.d.mts +1120 -0
  30. package/dist/tool-protection/index.d.ts +1120 -0
  31. package/dist/tool-protection/index.js +370 -0
  32. package/dist/tool-protection/index.mjs +338 -0
  33. package/package.json +32 -1
@@ -0,0 +1,47 @@
1
+ interface ToolCallContext {
2
+ tool: string;
3
+ args: Record<string, unknown>;
4
+ result?: unknown;
5
+ scopeId: string;
6
+ userIdentifier?: string;
7
+ }
8
+ interface ConsentEventContext {
9
+ eventType: 'consent:page_viewed' | 'consent:approved' | 'consent:delegation_created' | 'consent:credential_required' | 'auth:credential_success' | 'auth:credential_failed' | 'auth:oauth_success' | 'auth:oauth_failed';
10
+ timestamp: number;
11
+ sessionId: string;
12
+ userDid?: string;
13
+ agentDid: string;
14
+ targetTools: string[];
15
+ scopes: string[];
16
+ delegationId?: string;
17
+ projectId: string;
18
+ termsAccepted?: boolean;
19
+ credentialStatus?: 'present' | 'required' | 'obtained';
20
+ oauthIdentity?: {
21
+ provider: string;
22
+ identifier: string;
23
+ };
24
+ }
25
+ type BouncerOutcome = 'success' | 'failed' | 'blocked' | 'error';
26
+ interface DelegationCredential {
27
+ agent_did: string;
28
+ user_did: string;
29
+ user_id?: string;
30
+ user_identifier?: string;
31
+ scopes: string[];
32
+ constraints?: Record<string, unknown>;
33
+ issued_at: number;
34
+ created_at: number;
35
+ credential_jwt?: string;
36
+ authorization: {
37
+ type: 'oauth' | 'oauth2' | 'password' | 'credential' | 'webauthn' | 'siwe' | 'none';
38
+ provider?: string;
39
+ credentialType?: string;
40
+ rpId?: string;
41
+ userVerification?: 'required' | 'preferred' | 'discouraged';
42
+ chainId?: number;
43
+ domain?: string;
44
+ };
45
+ }
46
+
47
+ export type { BouncerOutcome, ConsentEventContext, DelegationCredential, ToolCallContext };
@@ -0,0 +1,47 @@
1
+ interface ToolCallContext {
2
+ tool: string;
3
+ args: Record<string, unknown>;
4
+ result?: unknown;
5
+ scopeId: string;
6
+ userIdentifier?: string;
7
+ }
8
+ interface ConsentEventContext {
9
+ eventType: 'consent:page_viewed' | 'consent:approved' | 'consent:delegation_created' | 'consent:credential_required' | 'auth:credential_success' | 'auth:credential_failed' | 'auth:oauth_success' | 'auth:oauth_failed';
10
+ timestamp: number;
11
+ sessionId: string;
12
+ userDid?: string;
13
+ agentDid: string;
14
+ targetTools: string[];
15
+ scopes: string[];
16
+ delegationId?: string;
17
+ projectId: string;
18
+ termsAccepted?: boolean;
19
+ credentialStatus?: 'present' | 'required' | 'obtained';
20
+ oauthIdentity?: {
21
+ provider: string;
22
+ identifier: string;
23
+ };
24
+ }
25
+ type BouncerOutcome = 'success' | 'failed' | 'blocked' | 'error';
26
+ interface DelegationCredential {
27
+ agent_did: string;
28
+ user_did: string;
29
+ user_id?: string;
30
+ user_identifier?: string;
31
+ scopes: string[];
32
+ constraints?: Record<string, unknown>;
33
+ issued_at: number;
34
+ created_at: number;
35
+ credential_jwt?: string;
36
+ authorization: {
37
+ type: 'oauth' | 'oauth2' | 'password' | 'credential' | 'webauthn' | 'siwe' | 'none';
38
+ provider?: string;
39
+ credentialType?: string;
40
+ rpId?: string;
41
+ userVerification?: 'required' | 'preferred' | 'discouraged';
42
+ chainId?: number;
43
+ domain?: string;
44
+ };
45
+ }
46
+
47
+ export type { BouncerOutcome, ConsentEventContext, DelegationCredential, ToolCallContext };
@@ -0,0 +1,2 @@
1
+ 'use strict';
2
+
@@ -0,0 +1,79 @@
1
+ import { JWK } from 'jose';
2
+
3
+ interface ApprovalNonceStore {
4
+ issue(requestHash: string, ttlSec?: number): string;
5
+ current(requestHash: string): string | null;
6
+ tryConsume(requestHash: string): boolean;
7
+ }
8
+ declare class InMemoryApprovalNonceStore implements ApprovalNonceStore {
9
+ private readonly issued;
10
+ issue(requestHash: string, ttlSec?: number): string;
11
+ current(requestHash: string): string | null;
12
+ tryConsume(requestHash: string): boolean;
13
+ }
14
+
15
+ declare const APPROVAL_GRANT_TYP = "approval-grant+jwt";
16
+ declare const APPROVAL_GRANT_MAX_LIFETIME_SEC = 300;
17
+ interface Ed25519PublicJWK {
18
+ kty: 'OKP';
19
+ crv: 'Ed25519';
20
+ x: string;
21
+ }
22
+ interface ApprovalGrantMeta {
23
+ approvalRequestId: string;
24
+ approverDid: string;
25
+ agentDid: string;
26
+ requestHash: string;
27
+ audience: string;
28
+ decision: 'approve' | 'deny';
29
+ nonce: string;
30
+ created: number;
31
+ expires: number;
32
+ amr?: string[];
33
+ delegationRef?: string;
34
+ }
35
+ interface SignedApprovalGrant {
36
+ jws: string;
37
+ meta: ApprovalGrantMeta;
38
+ }
39
+ interface ApprovalGrantExpectation {
40
+ requestHash: string;
41
+ audience: string;
42
+ nonce: string;
43
+ agentDid: string;
44
+ now?: number;
45
+ maxLifetimeSec?: number;
46
+ }
47
+ type ApproverKeyResolver = (did: string) => Promise<Ed25519PublicJWK | null>;
48
+ interface ApprovalGrantVerification {
49
+ valid: boolean;
50
+ reason?: string;
51
+ approverDid?: string;
52
+ }
53
+ declare function signApprovalGrant(meta: ApprovalGrantMeta, privateKeyJwk: JWK): Promise<SignedApprovalGrant>;
54
+ declare function verifyApprovalGrant(opts: {
55
+ grant: SignedApprovalGrant;
56
+ expected: ApprovalGrantExpectation;
57
+ resolveKey: ApproverKeyResolver;
58
+ }): Promise<ApprovalGrantVerification>;
59
+ interface SignedQuorumResult {
60
+ satisfied: boolean;
61
+ reason?: string;
62
+ }
63
+ declare function verifySignedApprovalQuorum(opts: {
64
+ grants: SignedApprovalGrant[];
65
+ expected: {
66
+ requestHash: string;
67
+ audience: string;
68
+ agentDid: string;
69
+ now?: number;
70
+ };
71
+ quorum: {
72
+ n: number;
73
+ approvers: string[];
74
+ };
75
+ resolveKey: ApproverKeyResolver;
76
+ nonceStore: ApprovalNonceStore;
77
+ }): Promise<SignedQuorumResult>;
78
+
79
+ export { APPROVAL_GRANT_MAX_LIFETIME_SEC, APPROVAL_GRANT_TYP, type ApprovalGrantExpectation, type ApprovalGrantMeta, type ApprovalGrantVerification, type ApprovalNonceStore, type ApproverKeyResolver, type Ed25519PublicJWK, InMemoryApprovalNonceStore, type SignedApprovalGrant, type SignedQuorumResult, signApprovalGrant, verifyApprovalGrant, verifySignedApprovalQuorum };
@@ -0,0 +1,79 @@
1
+ import { JWK } from 'jose';
2
+
3
+ interface ApprovalNonceStore {
4
+ issue(requestHash: string, ttlSec?: number): string;
5
+ current(requestHash: string): string | null;
6
+ tryConsume(requestHash: string): boolean;
7
+ }
8
+ declare class InMemoryApprovalNonceStore implements ApprovalNonceStore {
9
+ private readonly issued;
10
+ issue(requestHash: string, ttlSec?: number): string;
11
+ current(requestHash: string): string | null;
12
+ tryConsume(requestHash: string): boolean;
13
+ }
14
+
15
+ declare const APPROVAL_GRANT_TYP = "approval-grant+jwt";
16
+ declare const APPROVAL_GRANT_MAX_LIFETIME_SEC = 300;
17
+ interface Ed25519PublicJWK {
18
+ kty: 'OKP';
19
+ crv: 'Ed25519';
20
+ x: string;
21
+ }
22
+ interface ApprovalGrantMeta {
23
+ approvalRequestId: string;
24
+ approverDid: string;
25
+ agentDid: string;
26
+ requestHash: string;
27
+ audience: string;
28
+ decision: 'approve' | 'deny';
29
+ nonce: string;
30
+ created: number;
31
+ expires: number;
32
+ amr?: string[];
33
+ delegationRef?: string;
34
+ }
35
+ interface SignedApprovalGrant {
36
+ jws: string;
37
+ meta: ApprovalGrantMeta;
38
+ }
39
+ interface ApprovalGrantExpectation {
40
+ requestHash: string;
41
+ audience: string;
42
+ nonce: string;
43
+ agentDid: string;
44
+ now?: number;
45
+ maxLifetimeSec?: number;
46
+ }
47
+ type ApproverKeyResolver = (did: string) => Promise<Ed25519PublicJWK | null>;
48
+ interface ApprovalGrantVerification {
49
+ valid: boolean;
50
+ reason?: string;
51
+ approverDid?: string;
52
+ }
53
+ declare function signApprovalGrant(meta: ApprovalGrantMeta, privateKeyJwk: JWK): Promise<SignedApprovalGrant>;
54
+ declare function verifyApprovalGrant(opts: {
55
+ grant: SignedApprovalGrant;
56
+ expected: ApprovalGrantExpectation;
57
+ resolveKey: ApproverKeyResolver;
58
+ }): Promise<ApprovalGrantVerification>;
59
+ interface SignedQuorumResult {
60
+ satisfied: boolean;
61
+ reason?: string;
62
+ }
63
+ declare function verifySignedApprovalQuorum(opts: {
64
+ grants: SignedApprovalGrant[];
65
+ expected: {
66
+ requestHash: string;
67
+ audience: string;
68
+ agentDid: string;
69
+ now?: number;
70
+ };
71
+ quorum: {
72
+ n: number;
73
+ approvers: string[];
74
+ };
75
+ resolveKey: ApproverKeyResolver;
76
+ nonceStore: ApprovalNonceStore;
77
+ }): Promise<SignedQuorumResult>;
78
+
79
+ export { APPROVAL_GRANT_MAX_LIFETIME_SEC, APPROVAL_GRANT_TYP, type ApprovalGrantExpectation, type ApprovalGrantMeta, type ApprovalGrantVerification, type ApprovalNonceStore, type ApproverKeyResolver, type Ed25519PublicJWK, InMemoryApprovalNonceStore, type SignedApprovalGrant, type SignedQuorumResult, signApprovalGrant, verifyApprovalGrant, verifySignedApprovalQuorum };
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ var jose = require('jose');
4
+
5
+ // src/mcpi/approval-grant/grant.ts
6
+ var APPROVAL_GRANT_TYP = "approval-grant+jwt";
7
+ var APPROVAL_GRANT_MAX_LIFETIME_SEC = 300;
8
+ async function signApprovalGrant(meta, privateKeyJwk) {
9
+ if (!Number.isInteger(meta.created) || !Number.isInteger(meta.expires)) {
10
+ throw new Error("approval grant: created/expires must be integer unix seconds");
11
+ }
12
+ if (meta.expires <= meta.created) {
13
+ throw new Error("approval grant: expires must be after created");
14
+ }
15
+ if (meta.expires - meta.created > APPROVAL_GRANT_MAX_LIFETIME_SEC) {
16
+ throw new Error(`approval grant: lifetime exceeds ${APPROVAL_GRANT_MAX_LIFETIME_SEC}s ceiling`);
17
+ }
18
+ const key = await jose.importJWK(privateKeyJwk, "EdDSA");
19
+ const claims = {
20
+ requestHash: meta.requestHash,
21
+ decision: meta.decision,
22
+ nonce: meta.nonce
23
+ };
24
+ if (meta.amr) claims.amr = meta.amr;
25
+ if (meta.delegationRef) claims.delegationRef = meta.delegationRef;
26
+ const jws = await new jose.SignJWT(claims).setProtectedHeader({
27
+ alg: "EdDSA",
28
+ kid: `${meta.approverDid}#key-1`,
29
+ typ: APPROVAL_GRANT_TYP
30
+ }).setIssuer(meta.approverDid).setSubject(meta.agentDid).setAudience(meta.audience).setJti(meta.approvalRequestId).setIssuedAt(new Date(meta.created * 1e3)).setExpirationTime(new Date(meta.expires * 1e3)).sign(key);
31
+ return { jws, meta };
32
+ }
33
+ async function verifyApprovalGrant(opts) {
34
+ const { grant, expected, resolveKey } = opts;
35
+ const approverDid = grant?.meta?.approverDid;
36
+ if (typeof approverDid !== "string" || approverDid.length === 0) {
37
+ return { valid: false, reason: "missing_approver_did" };
38
+ }
39
+ let publicKeyJwk = null;
40
+ try {
41
+ publicKeyJwk = await resolveKey(approverDid);
42
+ } catch {
43
+ return { valid: false, reason: "approver_key_unresolved" };
44
+ }
45
+ if (!publicKeyJwk) {
46
+ return { valid: false, reason: "approver_key_unresolved" };
47
+ }
48
+ try {
49
+ const key = await jose.importJWK(publicKeyJwk, "EdDSA");
50
+ const { payload, protectedHeader } = await jose.jwtVerify(grant.jws, key, {
51
+ algorithms: ["EdDSA"],
52
+ issuer: approverDid,
53
+ audience: expected.audience,
54
+ ...expected.now !== void 0 ? { currentDate: new Date(expected.now * 1e3) } : {}
55
+ });
56
+ if (protectedHeader.typ !== APPROVAL_GRANT_TYP) {
57
+ return { valid: false, reason: "bad_typ" };
58
+ }
59
+ if (payload.requestHash !== expected.requestHash) {
60
+ return { valid: false, reason: "request_hash_mismatch" };
61
+ }
62
+ if (payload.nonce !== expected.nonce) {
63
+ return { valid: false, reason: "nonce_mismatch" };
64
+ }
65
+ if (payload.sub !== expected.agentDid) {
66
+ return { valid: false, reason: "agent_mismatch" };
67
+ }
68
+ if (payload.decision !== "approve") {
69
+ return { valid: false, reason: "not_approved" };
70
+ }
71
+ const iat = payload.iat;
72
+ const exp = payload.exp;
73
+ if (typeof iat !== "number" || typeof exp !== "number") {
74
+ return { valid: false, reason: "missing_times" };
75
+ }
76
+ if (exp - iat > (expected.maxLifetimeSec ?? APPROVAL_GRANT_MAX_LIFETIME_SEC)) {
77
+ return { valid: false, reason: "lifetime_exceeded" };
78
+ }
79
+ if (grant.meta.requestHash !== payload.requestHash || grant.meta.nonce !== payload.nonce || grant.meta.agentDid !== payload.sub || grant.meta.audience !== payload.aud || grant.meta.decision !== payload.decision || grant.meta.approverDid !== payload.iss) {
80
+ return { valid: false, reason: "meta_mismatch" };
81
+ }
82
+ return { valid: true, approverDid };
83
+ } catch {
84
+ return { valid: false, reason: "verify_failed" };
85
+ }
86
+ }
87
+ async function verifySignedApprovalQuorum(opts) {
88
+ const { grants, expected, quorum, resolveKey, nonceStore } = opts;
89
+ if (!Number.isInteger(quorum.n) || quorum.n < 1) {
90
+ return { satisfied: false, reason: "invalid_quorum" };
91
+ }
92
+ if (!Array.isArray(quorum.approvers) || quorum.approvers.length === 0) {
93
+ return { satisfied: false, reason: "no_approvers" };
94
+ }
95
+ const nonce = nonceStore.current(expected.requestHash);
96
+ if (!nonce) {
97
+ return { satisfied: false, reason: "no_outstanding_challenge" };
98
+ }
99
+ const approvers = /* @__PURE__ */ new Set();
100
+ for (const grant of grants) {
101
+ const v = await verifyApprovalGrant({
102
+ grant,
103
+ expected: {
104
+ requestHash: expected.requestHash,
105
+ audience: expected.audience,
106
+ agentDid: expected.agentDid,
107
+ nonce,
108
+ ...expected.now !== void 0 ? { now: expected.now } : {}
109
+ },
110
+ resolveKey
111
+ });
112
+ if (!v.valid || !v.approverDid) continue;
113
+ if (!quorum.approvers.includes(v.approverDid)) continue;
114
+ approvers.add(v.approverDid);
115
+ }
116
+ if (approvers.size >= quorum.n) {
117
+ if (!nonceStore.tryConsume(expected.requestHash)) {
118
+ return { satisfied: false, reason: "nonce_already_consumed" };
119
+ }
120
+ return { satisfied: true };
121
+ }
122
+ return { satisfied: false, reason: `quorum_not_met:${approvers.size}/${quorum.n}` };
123
+ }
124
+ function generateNonce() {
125
+ return jose.base64url.encode(globalThis.crypto.getRandomValues(new Uint8Array(32)));
126
+ }
127
+ var InMemoryApprovalNonceStore = class {
128
+ issued = /* @__PURE__ */ new Map();
129
+ issue(requestHash, ttlSec = APPROVAL_GRANT_MAX_LIFETIME_SEC) {
130
+ const now = Math.floor(Date.now() / 1e3);
131
+ const existing = this.issued.get(requestHash);
132
+ if (existing && !existing.consumed && existing.expiresAt >= now) {
133
+ return existing.nonce;
134
+ }
135
+ const nonce = generateNonce();
136
+ this.issued.set(requestHash, { nonce, consumed: false, expiresAt: now + ttlSec });
137
+ return nonce;
138
+ }
139
+ current(requestHash) {
140
+ const e = this.issued.get(requestHash);
141
+ if (!e || e.consumed || e.expiresAt < Math.floor(Date.now() / 1e3)) return null;
142
+ return e.nonce;
143
+ }
144
+ tryConsume(requestHash) {
145
+ const e = this.issued.get(requestHash);
146
+ if (!e || e.consumed || e.expiresAt < Math.floor(Date.now() / 1e3)) return false;
147
+ e.consumed = true;
148
+ return true;
149
+ }
150
+ };
151
+
152
+ exports.APPROVAL_GRANT_MAX_LIFETIME_SEC = APPROVAL_GRANT_MAX_LIFETIME_SEC;
153
+ exports.APPROVAL_GRANT_TYP = APPROVAL_GRANT_TYP;
154
+ exports.InMemoryApprovalNonceStore = InMemoryApprovalNonceStore;
155
+ exports.signApprovalGrant = signApprovalGrant;
156
+ exports.verifyApprovalGrant = verifyApprovalGrant;
157
+ exports.verifySignedApprovalQuorum = verifySignedApprovalQuorum;
@@ -0,0 +1,150 @@
1
+ import { importJWK, SignJWT, jwtVerify, base64url } from 'jose';
2
+
3
+ // src/mcpi/approval-grant/grant.ts
4
+ var APPROVAL_GRANT_TYP = "approval-grant+jwt";
5
+ var APPROVAL_GRANT_MAX_LIFETIME_SEC = 300;
6
+ async function signApprovalGrant(meta, privateKeyJwk) {
7
+ if (!Number.isInteger(meta.created) || !Number.isInteger(meta.expires)) {
8
+ throw new Error("approval grant: created/expires must be integer unix seconds");
9
+ }
10
+ if (meta.expires <= meta.created) {
11
+ throw new Error("approval grant: expires must be after created");
12
+ }
13
+ if (meta.expires - meta.created > APPROVAL_GRANT_MAX_LIFETIME_SEC) {
14
+ throw new Error(`approval grant: lifetime exceeds ${APPROVAL_GRANT_MAX_LIFETIME_SEC}s ceiling`);
15
+ }
16
+ const key = await importJWK(privateKeyJwk, "EdDSA");
17
+ const claims = {
18
+ requestHash: meta.requestHash,
19
+ decision: meta.decision,
20
+ nonce: meta.nonce
21
+ };
22
+ if (meta.amr) claims.amr = meta.amr;
23
+ if (meta.delegationRef) claims.delegationRef = meta.delegationRef;
24
+ const jws = await new SignJWT(claims).setProtectedHeader({
25
+ alg: "EdDSA",
26
+ kid: `${meta.approverDid}#key-1`,
27
+ typ: APPROVAL_GRANT_TYP
28
+ }).setIssuer(meta.approverDid).setSubject(meta.agentDid).setAudience(meta.audience).setJti(meta.approvalRequestId).setIssuedAt(new Date(meta.created * 1e3)).setExpirationTime(new Date(meta.expires * 1e3)).sign(key);
29
+ return { jws, meta };
30
+ }
31
+ async function verifyApprovalGrant(opts) {
32
+ const { grant, expected, resolveKey } = opts;
33
+ const approverDid = grant?.meta?.approverDid;
34
+ if (typeof approverDid !== "string" || approverDid.length === 0) {
35
+ return { valid: false, reason: "missing_approver_did" };
36
+ }
37
+ let publicKeyJwk = null;
38
+ try {
39
+ publicKeyJwk = await resolveKey(approverDid);
40
+ } catch {
41
+ return { valid: false, reason: "approver_key_unresolved" };
42
+ }
43
+ if (!publicKeyJwk) {
44
+ return { valid: false, reason: "approver_key_unresolved" };
45
+ }
46
+ try {
47
+ const key = await importJWK(publicKeyJwk, "EdDSA");
48
+ const { payload, protectedHeader } = await jwtVerify(grant.jws, key, {
49
+ algorithms: ["EdDSA"],
50
+ issuer: approverDid,
51
+ audience: expected.audience,
52
+ ...expected.now !== void 0 ? { currentDate: new Date(expected.now * 1e3) } : {}
53
+ });
54
+ if (protectedHeader.typ !== APPROVAL_GRANT_TYP) {
55
+ return { valid: false, reason: "bad_typ" };
56
+ }
57
+ if (payload.requestHash !== expected.requestHash) {
58
+ return { valid: false, reason: "request_hash_mismatch" };
59
+ }
60
+ if (payload.nonce !== expected.nonce) {
61
+ return { valid: false, reason: "nonce_mismatch" };
62
+ }
63
+ if (payload.sub !== expected.agentDid) {
64
+ return { valid: false, reason: "agent_mismatch" };
65
+ }
66
+ if (payload.decision !== "approve") {
67
+ return { valid: false, reason: "not_approved" };
68
+ }
69
+ const iat = payload.iat;
70
+ const exp = payload.exp;
71
+ if (typeof iat !== "number" || typeof exp !== "number") {
72
+ return { valid: false, reason: "missing_times" };
73
+ }
74
+ if (exp - iat > (expected.maxLifetimeSec ?? APPROVAL_GRANT_MAX_LIFETIME_SEC)) {
75
+ return { valid: false, reason: "lifetime_exceeded" };
76
+ }
77
+ if (grant.meta.requestHash !== payload.requestHash || grant.meta.nonce !== payload.nonce || grant.meta.agentDid !== payload.sub || grant.meta.audience !== payload.aud || grant.meta.decision !== payload.decision || grant.meta.approverDid !== payload.iss) {
78
+ return { valid: false, reason: "meta_mismatch" };
79
+ }
80
+ return { valid: true, approverDid };
81
+ } catch {
82
+ return { valid: false, reason: "verify_failed" };
83
+ }
84
+ }
85
+ async function verifySignedApprovalQuorum(opts) {
86
+ const { grants, expected, quorum, resolveKey, nonceStore } = opts;
87
+ if (!Number.isInteger(quorum.n) || quorum.n < 1) {
88
+ return { satisfied: false, reason: "invalid_quorum" };
89
+ }
90
+ if (!Array.isArray(quorum.approvers) || quorum.approvers.length === 0) {
91
+ return { satisfied: false, reason: "no_approvers" };
92
+ }
93
+ const nonce = nonceStore.current(expected.requestHash);
94
+ if (!nonce) {
95
+ return { satisfied: false, reason: "no_outstanding_challenge" };
96
+ }
97
+ const approvers = /* @__PURE__ */ new Set();
98
+ for (const grant of grants) {
99
+ const v = await verifyApprovalGrant({
100
+ grant,
101
+ expected: {
102
+ requestHash: expected.requestHash,
103
+ audience: expected.audience,
104
+ agentDid: expected.agentDid,
105
+ nonce,
106
+ ...expected.now !== void 0 ? { now: expected.now } : {}
107
+ },
108
+ resolveKey
109
+ });
110
+ if (!v.valid || !v.approverDid) continue;
111
+ if (!quorum.approvers.includes(v.approverDid)) continue;
112
+ approvers.add(v.approverDid);
113
+ }
114
+ if (approvers.size >= quorum.n) {
115
+ if (!nonceStore.tryConsume(expected.requestHash)) {
116
+ return { satisfied: false, reason: "nonce_already_consumed" };
117
+ }
118
+ return { satisfied: true };
119
+ }
120
+ return { satisfied: false, reason: `quorum_not_met:${approvers.size}/${quorum.n}` };
121
+ }
122
+ function generateNonce() {
123
+ return base64url.encode(globalThis.crypto.getRandomValues(new Uint8Array(32)));
124
+ }
125
+ var InMemoryApprovalNonceStore = class {
126
+ issued = /* @__PURE__ */ new Map();
127
+ issue(requestHash, ttlSec = APPROVAL_GRANT_MAX_LIFETIME_SEC) {
128
+ const now = Math.floor(Date.now() / 1e3);
129
+ const existing = this.issued.get(requestHash);
130
+ if (existing && !existing.consumed && existing.expiresAt >= now) {
131
+ return existing.nonce;
132
+ }
133
+ const nonce = generateNonce();
134
+ this.issued.set(requestHash, { nonce, consumed: false, expiresAt: now + ttlSec });
135
+ return nonce;
136
+ }
137
+ current(requestHash) {
138
+ const e = this.issued.get(requestHash);
139
+ if (!e || e.consumed || e.expiresAt < Math.floor(Date.now() / 1e3)) return null;
140
+ return e.nonce;
141
+ }
142
+ tryConsume(requestHash) {
143
+ const e = this.issued.get(requestHash);
144
+ if (!e || e.consumed || e.expiresAt < Math.floor(Date.now() / 1e3)) return false;
145
+ e.consumed = true;
146
+ return true;
147
+ }
148
+ };
149
+
150
+ export { APPROVAL_GRANT_MAX_LIFETIME_SEC, APPROVAL_GRANT_TYP, InMemoryApprovalNonceStore, signApprovalGrant, verifyApprovalGrant, verifySignedApprovalQuorum };