@kya-os/mcp-i-core 1.2.3-canary.7 → 1.3.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.
- package/.claude/settings.local.json +9 -0
- package/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-test.log +2979 -0
- package/COMPLIANCE_IMPROVEMENT_REPORT.md +483 -0
- package/Composer 3.md +615 -0
- package/GPT-5.md +1169 -0
- package/OPUS-plan.md +352 -0
- package/PHASE_3_AND_4.1_SUMMARY.md +585 -0
- package/PHASE_3_SUMMARY.md +317 -0
- package/PHASE_4.1.3_SUMMARY.md +428 -0
- package/PHASE_4.1_COMPLETE.md +525 -0
- package/PHASE_4_USER_DID_IDENTITY_LINKING_PLAN.md +1240 -0
- package/SCHEMA_COMPLIANCE_REPORT.md +275 -0
- package/TEST_PLAN.md +571 -0
- package/coverage/coverage-final.json +57 -0
- package/dist/__tests__/utils/mock-providers.d.ts +1 -2
- package/dist/__tests__/utils/mock-providers.d.ts.map +1 -1
- package/dist/__tests__/utils/mock-providers.js.map +1 -1
- package/dist/cache/oauth-config-cache.d.ts +69 -0
- package/dist/cache/oauth-config-cache.d.ts.map +1 -0
- package/dist/cache/oauth-config-cache.js +76 -0
- package/dist/cache/oauth-config-cache.js.map +1 -0
- package/dist/identity/idp-token-resolver.d.ts +53 -0
- package/dist/identity/idp-token-resolver.d.ts.map +1 -0
- package/dist/identity/idp-token-resolver.js +108 -0
- package/dist/identity/idp-token-resolver.js.map +1 -0
- package/dist/identity/idp-token-storage.interface.d.ts +42 -0
- package/dist/identity/idp-token-storage.interface.d.ts.map +1 -0
- package/dist/identity/idp-token-storage.interface.js +12 -0
- package/dist/identity/idp-token-storage.interface.js.map +1 -0
- package/dist/identity/user-did-manager.d.ts +39 -1
- package/dist/identity/user-did-manager.d.ts.map +1 -1
- package/dist/identity/user-did-manager.js +69 -3
- package/dist/identity/user-did-manager.js.map +1 -1
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +39 -1
- package/dist/index.js.map +1 -1
- package/dist/runtime/audit-logger.d.ts +37 -0
- package/dist/runtime/audit-logger.d.ts.map +1 -0
- package/dist/runtime/audit-logger.js +9 -0
- package/dist/runtime/audit-logger.js.map +1 -0
- package/dist/runtime/base.d.ts +58 -2
- package/dist/runtime/base.d.ts.map +1 -1
- package/dist/runtime/base.js +266 -11
- package/dist/runtime/base.js.map +1 -1
- package/dist/services/access-control.service.d.ts.map +1 -1
- package/dist/services/access-control.service.js +200 -35
- package/dist/services/access-control.service.js.map +1 -1
- package/dist/services/authorization/authorization-registry.d.ts +29 -0
- package/dist/services/authorization/authorization-registry.d.ts.map +1 -0
- package/dist/services/authorization/authorization-registry.js +57 -0
- package/dist/services/authorization/authorization-registry.js.map +1 -0
- package/dist/services/authorization/types.d.ts +53 -0
- package/dist/services/authorization/types.d.ts.map +1 -0
- package/dist/services/authorization/types.js +10 -0
- package/dist/services/authorization/types.js.map +1 -0
- package/dist/services/batch-delegation.service.d.ts +53 -0
- package/dist/services/batch-delegation.service.d.ts.map +1 -0
- package/dist/services/batch-delegation.service.js +95 -0
- package/dist/services/batch-delegation.service.js.map +1 -0
- package/dist/services/oauth-config.service.d.ts +53 -0
- package/dist/services/oauth-config.service.d.ts.map +1 -0
- package/dist/services/oauth-config.service.js +119 -0
- package/dist/services/oauth-config.service.js.map +1 -0
- package/dist/services/oauth-provider-registry.d.ts +88 -0
- package/dist/services/oauth-provider-registry.d.ts.map +1 -0
- package/dist/services/oauth-provider-registry.js +128 -0
- package/dist/services/oauth-provider-registry.js.map +1 -0
- package/dist/services/oauth-service.d.ts +77 -0
- package/dist/services/oauth-service.d.ts.map +1 -0
- package/dist/services/oauth-service.js +348 -0
- package/dist/services/oauth-service.js.map +1 -0
- package/dist/services/oauth-token-retrieval.service.d.ts +49 -0
- package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -0
- package/dist/services/oauth-token-retrieval.service.js +150 -0
- package/dist/services/oauth-token-retrieval.service.js.map +1 -0
- package/dist/services/provider-resolver.d.ts +48 -0
- package/dist/services/provider-resolver.d.ts.map +1 -0
- package/dist/services/provider-resolver.js +121 -0
- package/dist/services/provider-resolver.js.map +1 -0
- package/dist/services/provider-validator.d.ts +55 -0
- package/dist/services/provider-validator.d.ts.map +1 -0
- package/dist/services/provider-validator.js +135 -0
- package/dist/services/provider-validator.js.map +1 -0
- package/dist/services/tool-context-builder.d.ts +57 -0
- package/dist/services/tool-context-builder.d.ts.map +1 -0
- package/dist/services/tool-context-builder.js +125 -0
- package/dist/services/tool-context-builder.js.map +1 -0
- package/dist/services/tool-protection.service.d.ts +87 -10
- package/dist/services/tool-protection.service.d.ts.map +1 -1
- package/dist/services/tool-protection.service.js +282 -112
- package/dist/services/tool-protection.service.js.map +1 -1
- package/dist/types/oauth-required-error.d.ts +40 -0
- package/dist/types/oauth-required-error.d.ts.map +1 -0
- package/dist/types/oauth-required-error.js +40 -0
- package/dist/types/oauth-required-error.js.map +1 -0
- package/dist/utils/did-helpers.d.ts +33 -0
- package/dist/utils/did-helpers.d.ts.map +1 -1
- package/dist/utils/did-helpers.js +40 -0
- package/dist/utils/did-helpers.js.map +1 -1
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/docs/API_REFERENCE.md +1362 -0
- package/docs/COMPLIANCE_MATRIX.md +691 -0
- package/docs/STATUSLIST2021_GUIDE.md +696 -0
- package/docs/W3C_VC_DELEGATION_GUIDE.md +710 -0
- package/package.json +24 -50
- package/scripts/audit-compliance.ts +724 -0
- package/src/__tests__/cache/tool-protection-cache.test.ts +640 -0
- package/src/__tests__/config/provider-runtime-config.test.ts +309 -0
- package/src/__tests__/delegation-e2e.test.ts +690 -0
- package/src/__tests__/identity/user-did-manager.test.ts +213 -0
- package/src/__tests__/index.test.ts +56 -0
- package/src/__tests__/integration/full-flow.test.ts +776 -0
- package/src/__tests__/integration.test.ts +281 -0
- package/src/__tests__/providers/base.test.ts +173 -0
- package/src/__tests__/providers/memory.test.ts +319 -0
- package/src/__tests__/regression/phase2-regression.test.ts +429 -0
- package/src/__tests__/runtime/audit-logger.test.ts +154 -0
- package/src/__tests__/runtime/base-extensions.test.ts +593 -0
- package/src/__tests__/runtime/base.test.ts +869 -0
- package/src/__tests__/runtime/delegation-flow.test.ts +164 -0
- package/src/__tests__/runtime/proof-client-did.test.ts +375 -0
- package/src/__tests__/runtime/route-interception.test.ts +686 -0
- package/src/__tests__/runtime/tool-protection-enforcement.test.ts +908 -0
- package/src/__tests__/services/agentshield-integration.test.ts +784 -0
- package/src/__tests__/services/provider-resolver-edge-cases.test.ts +591 -0
- package/src/__tests__/services/tool-protection-oauth-provider.test.ts +480 -0
- package/src/__tests__/services/tool-protection.service.test.ts +1366 -0
- package/src/__tests__/utils/mock-providers.ts +340 -0
- package/src/cache/oauth-config-cache.d.ts +69 -0
- package/src/cache/oauth-config-cache.d.ts.map +1 -0
- package/src/cache/oauth-config-cache.js.map +1 -0
- package/src/cache/oauth-config-cache.ts +123 -0
- package/src/cache/tool-protection-cache.ts +171 -0
- package/src/compliance/EXAMPLE.md +412 -0
- package/src/compliance/__tests__/schema-verifier.test.ts +797 -0
- package/src/compliance/index.ts +8 -0
- package/src/compliance/schema-registry.ts +460 -0
- package/src/compliance/schema-verifier.ts +708 -0
- package/src/config/__tests__/remote-config.spec.ts +268 -0
- package/src/config/remote-config.ts +174 -0
- package/src/config.ts +309 -0
- package/src/delegation/__tests__/audience-validator.test.ts +112 -0
- package/src/delegation/__tests__/bitstring.test.ts +346 -0
- package/src/delegation/__tests__/cascading-revocation.test.ts +628 -0
- package/src/delegation/__tests__/delegation-graph.test.ts +584 -0
- package/src/delegation/__tests__/utils.test.ts +152 -0
- package/src/delegation/__tests__/vc-issuer.test.ts +442 -0
- package/src/delegation/__tests__/vc-verifier.test.ts +922 -0
- package/src/delegation/audience-validator.ts +52 -0
- package/src/delegation/bitstring.ts +278 -0
- package/src/delegation/cascading-revocation.ts +370 -0
- package/src/delegation/delegation-graph.ts +299 -0
- package/src/delegation/index.ts +14 -0
- package/src/delegation/statuslist-manager.ts +353 -0
- package/src/delegation/storage/__tests__/memory-graph-storage.test.ts +366 -0
- package/src/delegation/storage/__tests__/memory-statuslist-storage.test.ts +228 -0
- package/src/delegation/storage/index.ts +9 -0
- package/src/delegation/storage/memory-graph-storage.ts +178 -0
- package/src/delegation/storage/memory-statuslist-storage.ts +77 -0
- package/src/delegation/utils.ts +42 -0
- package/src/delegation/vc-issuer.ts +232 -0
- package/src/delegation/vc-verifier.ts +568 -0
- package/src/identity/idp-token-resolver.ts +147 -0
- package/src/identity/idp-token-storage.interface.ts +59 -0
- package/src/identity/user-did-manager.ts +370 -0
- package/src/index.ts +260 -0
- package/src/providers/base.d.ts +91 -0
- package/src/providers/base.d.ts.map +1 -0
- package/src/providers/base.js.map +1 -0
- package/src/providers/base.ts +96 -0
- package/src/providers/memory.ts +142 -0
- package/src/runtime/audit-logger.ts +39 -0
- package/src/runtime/base.ts +1329 -0
- package/src/services/__tests__/access-control.integration.test.ts +443 -0
- package/src/services/__tests__/access-control.proof-response-validation.test.ts +578 -0
- package/src/services/__tests__/access-control.service.test.ts +970 -0
- package/src/services/__tests__/batch-delegation.service.test.ts +351 -0
- package/src/services/__tests__/crypto.service.test.ts +531 -0
- package/src/services/__tests__/oauth-provider-registry.test.ts +142 -0
- package/src/services/__tests__/proof-verifier.integration.test.ts +485 -0
- package/src/services/__tests__/proof-verifier.test.ts +489 -0
- package/src/services/__tests__/provider-resolution.integration.test.ts +202 -0
- package/src/services/__tests__/provider-resolver.test.ts +213 -0
- package/src/services/__tests__/storage.service.test.ts +358 -0
- package/src/services/access-control.service.ts +990 -0
- package/src/services/authorization/authorization-registry.ts +66 -0
- package/src/services/authorization/types.ts +71 -0
- package/src/services/batch-delegation.service.ts +137 -0
- package/src/services/crypto.service.ts +302 -0
- package/src/services/errors.ts +76 -0
- package/src/services/index.ts +9 -0
- package/src/services/oauth-config.service.d.ts +53 -0
- package/src/services/oauth-config.service.d.ts.map +1 -0
- package/src/services/oauth-config.service.js.map +1 -0
- package/src/services/oauth-config.service.ts +169 -0
- package/src/services/oauth-provider-registry.d.ts +57 -0
- package/src/services/oauth-provider-registry.d.ts.map +1 -0
- package/src/services/oauth-provider-registry.js.map +1 -0
- package/src/services/oauth-provider-registry.ts +141 -0
- package/src/services/oauth-service.ts +510 -0
- package/src/services/oauth-token-retrieval.service.ts +245 -0
- package/src/services/proof-verifier.ts +478 -0
- package/src/services/provider-resolver.d.ts +48 -0
- package/src/services/provider-resolver.d.ts.map +1 -0
- package/src/services/provider-resolver.js.map +1 -0
- package/src/services/provider-resolver.ts +146 -0
- package/src/services/provider-validator.ts +170 -0
- package/src/services/storage.service.ts +566 -0
- package/src/services/tool-context-builder.ts +172 -0
- package/src/services/tool-protection.service.ts +958 -0
- package/src/types/oauth-required-error.ts +63 -0
- package/src/types/tool-protection.ts +155 -0
- package/src/utils/__tests__/did-helpers.test.ts +101 -0
- package/src/utils/base64.ts +148 -0
- package/src/utils/cors.ts +83 -0
- package/src/utils/did-helpers.ts +150 -0
- package/src/utils/index.ts +8 -0
- package/src/utils/storage-keys.ts +278 -0
- package/tsconfig.json +21 -0
- package/vitest.config.ts +56 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth Token Retrieval Service
|
|
3
|
+
*
|
|
4
|
+
* Retrieves OAuth tokens from AgentShield after receiving delegation token.
|
|
5
|
+
* Implements the two-step token flow for Phase 3 custom IDP support.
|
|
6
|
+
*
|
|
7
|
+
* @package @kya-os/mcp-i-core
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { IdpTokens } from "@kya-os/contracts/config";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Configuration for OAuthTokenRetrievalService
|
|
14
|
+
*/
|
|
15
|
+
export interface OAuthTokenRetrievalServiceConfig {
|
|
16
|
+
/** AgentShield API base URL */
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
/** Fetch implementation */
|
|
19
|
+
fetchProvider: typeof fetch;
|
|
20
|
+
/** Optional logger callback */
|
|
21
|
+
logger?: (message: string, data?: any) => void;
|
|
22
|
+
/** Optional retry configuration */
|
|
23
|
+
retryConfig?: {
|
|
24
|
+
maxRetries?: number;
|
|
25
|
+
retryDelay?: number; // milliseconds
|
|
26
|
+
retryBackoff?: number; // multiplier for exponential backoff
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Response from AgentShield token retrieval endpoint
|
|
32
|
+
*/
|
|
33
|
+
interface OAuthTokenRetrievalResponse {
|
|
34
|
+
success: true;
|
|
35
|
+
data: {
|
|
36
|
+
oauth_access_token: string;
|
|
37
|
+
oauth_refresh_token: string | null;
|
|
38
|
+
oauth_expires_at: string | null; // ISO 8601 datetime string
|
|
39
|
+
oauth_expires_in: number | null; // seconds
|
|
40
|
+
oauth_token_type: string;
|
|
41
|
+
oauth_scope: string | null;
|
|
42
|
+
};
|
|
43
|
+
metadata?: {
|
|
44
|
+
requestId?: string;
|
|
45
|
+
timestamp?: string; // ISO 8601
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Error response from AgentShield
|
|
51
|
+
*/
|
|
52
|
+
interface OAuthTokenRetrievalErrorResponse {
|
|
53
|
+
success: false;
|
|
54
|
+
error: {
|
|
55
|
+
code: string;
|
|
56
|
+
message: string;
|
|
57
|
+
details?: any;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Service for retrieving OAuth tokens from AgentShield
|
|
63
|
+
*/
|
|
64
|
+
export class OAuthTokenRetrievalService {
|
|
65
|
+
private config: Required<OAuthTokenRetrievalServiceConfig> & {
|
|
66
|
+
retryConfig: Required<NonNullable<OAuthTokenRetrievalServiceConfig["retryConfig"]>>;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
constructor(config: OAuthTokenRetrievalServiceConfig) {
|
|
70
|
+
const defaultRetryConfig = {
|
|
71
|
+
maxRetries: 3,
|
|
72
|
+
retryDelay: 1000,
|
|
73
|
+
retryBackoff: 2,
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
this.config = {
|
|
77
|
+
...config,
|
|
78
|
+
logger: config.logger || (() => {}),
|
|
79
|
+
retryConfig: {
|
|
80
|
+
...defaultRetryConfig,
|
|
81
|
+
...config.retryConfig,
|
|
82
|
+
},
|
|
83
|
+
} as Required<OAuthTokenRetrievalServiceConfig> & {
|
|
84
|
+
retryConfig: Required<NonNullable<OAuthTokenRetrievalServiceConfig["retryConfig"]>>;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Retrieve OAuth tokens from AgentShield
|
|
90
|
+
*
|
|
91
|
+
* @param delegationId - Delegation ID from token exchange response
|
|
92
|
+
* @param delegationToken - Delegation token (JWT) for authorization
|
|
93
|
+
* @returns OAuth tokens mapped to IdpTokens format, or null if unavailable
|
|
94
|
+
*/
|
|
95
|
+
async retrieveTokens(
|
|
96
|
+
delegationId: string,
|
|
97
|
+
delegationToken: string
|
|
98
|
+
): Promise<IdpTokens | null> {
|
|
99
|
+
const endpoint = `${this.config.baseUrl}/api/v1/bouncer/delegations/${delegationId}/tokens`;
|
|
100
|
+
|
|
101
|
+
this.config.logger("[OAuthTokenRetrievalService] Retrieving OAuth tokens", {
|
|
102
|
+
delegationId,
|
|
103
|
+
endpoint,
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
let lastError: Error | null = null;
|
|
107
|
+
let attempt = 0;
|
|
108
|
+
|
|
109
|
+
// Retry logic for transient failures
|
|
110
|
+
while (attempt <= this.config.retryConfig.maxRetries) {
|
|
111
|
+
try {
|
|
112
|
+
const response = await this.config.fetchProvider(endpoint, {
|
|
113
|
+
method: "GET",
|
|
114
|
+
headers: {
|
|
115
|
+
Authorization: `Bearer ${delegationToken}`,
|
|
116
|
+
Accept: "application/json",
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (!response.ok) {
|
|
121
|
+
const errorData = await response.json().catch(() => ({})) as
|
|
122
|
+
| OAuthTokenRetrievalErrorResponse
|
|
123
|
+
| { error?: string; message?: string };
|
|
124
|
+
|
|
125
|
+
if (response.status === 404 || response.status === 401) {
|
|
126
|
+
// Token unavailable or unauthorized - don't retry
|
|
127
|
+
this.config.logger(
|
|
128
|
+
"[OAuthTokenRetrievalService] Tokens unavailable",
|
|
129
|
+
{
|
|
130
|
+
status: response.status,
|
|
131
|
+
delegationId,
|
|
132
|
+
error: errorData,
|
|
133
|
+
}
|
|
134
|
+
);
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Transient error - retry
|
|
139
|
+
const errorMessage =
|
|
140
|
+
(errorData as OAuthTokenRetrievalErrorResponse).error?.message ||
|
|
141
|
+
(errorData as any).error ||
|
|
142
|
+
(errorData as any).message ||
|
|
143
|
+
`HTTP ${response.status}`;
|
|
144
|
+
|
|
145
|
+
throw new Error(`Token retrieval failed: ${errorMessage}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const result = (await response.json()) as
|
|
149
|
+
| OAuthTokenRetrievalResponse
|
|
150
|
+
| OAuthTokenRetrievalErrorResponse;
|
|
151
|
+
|
|
152
|
+
if (!result.success) {
|
|
153
|
+
this.config.logger(
|
|
154
|
+
"[OAuthTokenRetrievalService] Token retrieval error response",
|
|
155
|
+
{
|
|
156
|
+
delegationId,
|
|
157
|
+
error: result.error,
|
|
158
|
+
}
|
|
159
|
+
);
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Map response to IdpTokens format
|
|
164
|
+
const tokens = this.mapToIdpTokens(result.data);
|
|
165
|
+
|
|
166
|
+
this.config.logger(
|
|
167
|
+
"[OAuthTokenRetrievalService] OAuth tokens retrieved successfully",
|
|
168
|
+
{
|
|
169
|
+
delegationId,
|
|
170
|
+
expiresAt: new Date(tokens.expires_at).toISOString(),
|
|
171
|
+
hasRefreshToken: !!tokens.refresh_token,
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
return tokens;
|
|
176
|
+
} catch (error) {
|
|
177
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
178
|
+
|
|
179
|
+
if (attempt < this.config.retryConfig.maxRetries) {
|
|
180
|
+
const delay =
|
|
181
|
+
this.config.retryConfig.retryDelay *
|
|
182
|
+
Math.pow(this.config.retryConfig.retryBackoff, attempt);
|
|
183
|
+
|
|
184
|
+
this.config.logger(
|
|
185
|
+
"[OAuthTokenRetrievalService] Retry attempt failed, retrying",
|
|
186
|
+
{
|
|
187
|
+
attempt: attempt + 1,
|
|
188
|
+
maxRetries: this.config.retryConfig.maxRetries,
|
|
189
|
+
delay,
|
|
190
|
+
error: lastError.message,
|
|
191
|
+
}
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
195
|
+
attempt++;
|
|
196
|
+
} else {
|
|
197
|
+
// Max retries exceeded
|
|
198
|
+
this.config.logger(
|
|
199
|
+
"[OAuthTokenRetrievalService] Max retries exceeded",
|
|
200
|
+
{
|
|
201
|
+
delegationId,
|
|
202
|
+
error: lastError.message,
|
|
203
|
+
attempts: attempt + 1,
|
|
204
|
+
}
|
|
205
|
+
);
|
|
206
|
+
// Return null instead of throwing - delegation token still valid
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Map AgentShield response to IdpTokens format
|
|
217
|
+
*
|
|
218
|
+
* @param data - Response data from AgentShield
|
|
219
|
+
* @returns IdpTokens object
|
|
220
|
+
*/
|
|
221
|
+
private mapToIdpTokens(
|
|
222
|
+
data: OAuthTokenRetrievalResponse["data"]
|
|
223
|
+
): IdpTokens {
|
|
224
|
+
// Convert ISO 8601 string to milliseconds timestamp
|
|
225
|
+
let expiresAt: number;
|
|
226
|
+
if (data.oauth_expires_at) {
|
|
227
|
+
expiresAt = new Date(data.oauth_expires_at).getTime();
|
|
228
|
+
} else if (data.oauth_expires_in) {
|
|
229
|
+
expiresAt = Date.now() + data.oauth_expires_in * 1000;
|
|
230
|
+
} else {
|
|
231
|
+
// Default to 1 hour if neither provided
|
|
232
|
+
expiresAt = Date.now() + 3600 * 1000;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
access_token: data.oauth_access_token,
|
|
237
|
+
refresh_token: data.oauth_refresh_token || undefined,
|
|
238
|
+
expires_in: data.oauth_expires_in || undefined,
|
|
239
|
+
expires_at: expiresAt,
|
|
240
|
+
token_type: data.oauth_token_type || "Bearer",
|
|
241
|
+
scope: data.oauth_scope || undefined,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ProofVerifier
|
|
3
|
+
*
|
|
4
|
+
* Centralized proof verification service that validates DetachedProof
|
|
5
|
+
* signatures, enforces nonce replay protection, and checks timestamp skew.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { CryptoService, type Ed25519JWK } from "./crypto.service.js";
|
|
9
|
+
import { CryptoProvider } from "../providers/base.js";
|
|
10
|
+
import { ClockProvider } from "../providers/base.js";
|
|
11
|
+
import { NonceCacheProvider } from "../providers/base.js";
|
|
12
|
+
import { FetchProvider } from "../providers/base.js";
|
|
13
|
+
import {
|
|
14
|
+
DetachedProofSchema,
|
|
15
|
+
type DetachedProof,
|
|
16
|
+
} from "@kya-os/contracts/proof";
|
|
17
|
+
import { canonicalize } from "json-canonicalize";
|
|
18
|
+
import {
|
|
19
|
+
ProofVerificationError,
|
|
20
|
+
PROOF_VERIFICATION_ERROR_CODES,
|
|
21
|
+
type ProofVerificationErrorCode,
|
|
22
|
+
} from "./errors.js";
|
|
23
|
+
|
|
24
|
+
export interface ProofVerificationResult {
|
|
25
|
+
valid: boolean;
|
|
26
|
+
reason?: string;
|
|
27
|
+
error?: Error;
|
|
28
|
+
errorCode?: ProofVerificationErrorCode;
|
|
29
|
+
details?: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ProofVerifierConfig {
|
|
33
|
+
cryptoProvider: CryptoProvider;
|
|
34
|
+
clockProvider: ClockProvider;
|
|
35
|
+
nonceCacheProvider: NonceCacheProvider;
|
|
36
|
+
fetchProvider: FetchProvider;
|
|
37
|
+
timestampSkewSeconds?: number;
|
|
38
|
+
nonceTtlSeconds?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class ProofVerifier {
|
|
42
|
+
private cryptoService: CryptoService;
|
|
43
|
+
private clock: ClockProvider;
|
|
44
|
+
private nonceCache: NonceCacheProvider;
|
|
45
|
+
private fetch: FetchProvider;
|
|
46
|
+
private timestampSkewSeconds: number;
|
|
47
|
+
private nonceTtlSeconds: number;
|
|
48
|
+
|
|
49
|
+
constructor(config: ProofVerifierConfig) {
|
|
50
|
+
this.cryptoService = new CryptoService(config.cryptoProvider);
|
|
51
|
+
this.clock = config.clockProvider;
|
|
52
|
+
this.nonceCache = config.nonceCacheProvider;
|
|
53
|
+
this.fetch = config.fetchProvider;
|
|
54
|
+
this.timestampSkewSeconds = config.timestampSkewSeconds ?? 120; // Default 2 minutes
|
|
55
|
+
this.nonceTtlSeconds = config.nonceTtlSeconds ?? 300; // Default 5 minutes
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Verify a DetachedProof
|
|
60
|
+
* Automatically reconstructs canonical payload from proof.meta for signature verification
|
|
61
|
+
* @param proof - The proof to verify
|
|
62
|
+
* @param publicKeyJwk - Ed25519 public key in JWK format (from DID document)
|
|
63
|
+
* @returns Verification result
|
|
64
|
+
*/
|
|
65
|
+
async verifyProof(
|
|
66
|
+
proof: DetachedProof,
|
|
67
|
+
publicKeyJwk: Ed25519JWK
|
|
68
|
+
): Promise<ProofVerificationResult> {
|
|
69
|
+
try {
|
|
70
|
+
// 1. Validate proof structure
|
|
71
|
+
const structureValidation = await this.validateProofStructure(proof);
|
|
72
|
+
if (!structureValidation.valid) {
|
|
73
|
+
return structureValidation;
|
|
74
|
+
}
|
|
75
|
+
const validatedProof = structureValidation.proof!;
|
|
76
|
+
|
|
77
|
+
// 2. Check nonce replay protection (scoped to agent DID to prevent cross-agent replay attacks)
|
|
78
|
+
const nonceValidation = await this.validateNonce(
|
|
79
|
+
validatedProof.meta.nonce,
|
|
80
|
+
validatedProof.meta.did
|
|
81
|
+
);
|
|
82
|
+
if (!nonceValidation.valid) {
|
|
83
|
+
return nonceValidation;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 3. Check timestamp skew
|
|
87
|
+
const timestampValidation = await this.validateTimestamp(
|
|
88
|
+
validatedProof.meta.ts
|
|
89
|
+
);
|
|
90
|
+
if (!timestampValidation.valid) {
|
|
91
|
+
return timestampValidation;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 4. Reconstruct canonical payload from proof meta
|
|
95
|
+
const canonicalPayloadString = this.buildCanonicalPayload(
|
|
96
|
+
validatedProof.meta
|
|
97
|
+
);
|
|
98
|
+
const canonicalPayloadBytes = new TextEncoder().encode(
|
|
99
|
+
canonicalPayloadString
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
// 5. Verify JWS signature with detached canonical payload
|
|
103
|
+
const signatureValidation = await this.verifySignature(
|
|
104
|
+
validatedProof.jws,
|
|
105
|
+
publicKeyJwk,
|
|
106
|
+
canonicalPayloadBytes,
|
|
107
|
+
validatedProof.meta.kid
|
|
108
|
+
);
|
|
109
|
+
if (!signatureValidation.valid) {
|
|
110
|
+
return signatureValidation;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 6. Add nonce to cache to prevent replay (scoped to agent DID)
|
|
114
|
+
await this.addNonceToCache(
|
|
115
|
+
validatedProof.meta.nonce,
|
|
116
|
+
validatedProof.meta.did
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
valid: true,
|
|
121
|
+
};
|
|
122
|
+
} catch (error) {
|
|
123
|
+
// Security-safe failure: never throw, always return error result
|
|
124
|
+
return {
|
|
125
|
+
valid: false,
|
|
126
|
+
reason: "Proof verification error",
|
|
127
|
+
errorCode: PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,
|
|
128
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
129
|
+
details: {
|
|
130
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Verify proof with detached payload (for CLI/verifier compatibility)
|
|
138
|
+
* @param proof - The proof to verify
|
|
139
|
+
* @param canonicalPayload - Canonical JSON payload (for detached JWS) as string or Uint8Array
|
|
140
|
+
* @param publicKeyJwk - Ed25519 public key in JWK format
|
|
141
|
+
* @returns Verification result
|
|
142
|
+
*/
|
|
143
|
+
async verifyProofDetached(
|
|
144
|
+
proof: DetachedProof,
|
|
145
|
+
canonicalPayload: string | Uint8Array,
|
|
146
|
+
publicKeyJwk: Ed25519JWK
|
|
147
|
+
): Promise<ProofVerificationResult> {
|
|
148
|
+
try {
|
|
149
|
+
// 1. Validate proof structure
|
|
150
|
+
const structureValidation = await this.validateProofStructure(proof);
|
|
151
|
+
if (!structureValidation.valid) {
|
|
152
|
+
return structureValidation;
|
|
153
|
+
}
|
|
154
|
+
const validatedProof = structureValidation.proof!;
|
|
155
|
+
|
|
156
|
+
// 2. Check nonce replay protection (scoped to agent DID to prevent cross-agent replay attacks)
|
|
157
|
+
const nonceValidation = await this.validateNonce(
|
|
158
|
+
validatedProof.meta.nonce,
|
|
159
|
+
validatedProof.meta.did
|
|
160
|
+
);
|
|
161
|
+
if (!nonceValidation.valid) {
|
|
162
|
+
return nonceValidation;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 3. Check timestamp skew
|
|
166
|
+
const timestampValidation = await this.validateTimestamp(
|
|
167
|
+
validatedProof.meta.ts
|
|
168
|
+
);
|
|
169
|
+
if (!timestampValidation.valid) {
|
|
170
|
+
return timestampValidation;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 4. Convert canonical payload to Uint8Array if needed
|
|
174
|
+
const canonicalPayloadBytes =
|
|
175
|
+
canonicalPayload instanceof Uint8Array
|
|
176
|
+
? canonicalPayload
|
|
177
|
+
: new TextEncoder().encode(canonicalPayload);
|
|
178
|
+
|
|
179
|
+
// 5. Verify JWS signature with detached payload
|
|
180
|
+
const signatureValidation = await this.verifySignature(
|
|
181
|
+
validatedProof.jws,
|
|
182
|
+
publicKeyJwk,
|
|
183
|
+
canonicalPayloadBytes,
|
|
184
|
+
validatedProof.meta.kid
|
|
185
|
+
);
|
|
186
|
+
if (!signatureValidation.valid) {
|
|
187
|
+
return signatureValidation;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// 6. Add nonce to cache (scoped to agent DID)
|
|
191
|
+
await this.addNonceToCache(
|
|
192
|
+
validatedProof.meta.nonce,
|
|
193
|
+
validatedProof.meta.did
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
valid: true,
|
|
198
|
+
};
|
|
199
|
+
} catch (error) {
|
|
200
|
+
// Security-safe failure: never throw, always return error result
|
|
201
|
+
return {
|
|
202
|
+
valid: false,
|
|
203
|
+
reason: "Proof verification error",
|
|
204
|
+
errorCode: PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,
|
|
205
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
206
|
+
details: {
|
|
207
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Validate proof structure using Zod schema
|
|
215
|
+
* @private
|
|
216
|
+
*/
|
|
217
|
+
private async validateProofStructure(
|
|
218
|
+
proof: DetachedProof
|
|
219
|
+
): Promise<ProofVerificationResult & { proof?: DetachedProof }> {
|
|
220
|
+
const validationResult = DetachedProofSchema.safeParse(proof);
|
|
221
|
+
if (!validationResult.success) {
|
|
222
|
+
return {
|
|
223
|
+
valid: false,
|
|
224
|
+
reason: "Invalid proof structure",
|
|
225
|
+
errorCode: PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,
|
|
226
|
+
error: new Error(
|
|
227
|
+
`Proof validation failed: ${validationResult.error.message}`
|
|
228
|
+
),
|
|
229
|
+
details: {
|
|
230
|
+
zodErrors: validationResult.error.errors,
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
return {
|
|
235
|
+
valid: true,
|
|
236
|
+
proof: validationResult.data,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Validate nonce replay protection
|
|
242
|
+
* @private
|
|
243
|
+
*/
|
|
244
|
+
private async validateNonce(
|
|
245
|
+
nonce: string,
|
|
246
|
+
agentDid?: string
|
|
247
|
+
): Promise<ProofVerificationResult> {
|
|
248
|
+
const nonceUsed = await this.nonceCache.has(nonce, agentDid);
|
|
249
|
+
if (nonceUsed) {
|
|
250
|
+
return {
|
|
251
|
+
valid: false,
|
|
252
|
+
reason: "Nonce already used (replay attack detected)",
|
|
253
|
+
errorCode: PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,
|
|
254
|
+
details: {
|
|
255
|
+
nonce,
|
|
256
|
+
agentDid,
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
return { valid: true };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Validate timestamp skew
|
|
265
|
+
* @private
|
|
266
|
+
*/
|
|
267
|
+
private async validateTimestamp(
|
|
268
|
+
timestamp: number
|
|
269
|
+
): Promise<ProofVerificationResult> {
|
|
270
|
+
// Convert seconds to milliseconds for clock provider (which uses Date.now())
|
|
271
|
+
const timestampMs = timestamp * 1000;
|
|
272
|
+
if (!this.clock.isWithinSkew(timestampMs, this.timestampSkewSeconds)) {
|
|
273
|
+
return {
|
|
274
|
+
valid: false,
|
|
275
|
+
reason: `Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,
|
|
276
|
+
errorCode: PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,
|
|
277
|
+
details: {
|
|
278
|
+
timestamp,
|
|
279
|
+
timestampMs,
|
|
280
|
+
skewSeconds: this.timestampSkewSeconds,
|
|
281
|
+
currentTime: this.clock.now(),
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
return { valid: true };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Verify JWS signature
|
|
290
|
+
* @private
|
|
291
|
+
*/
|
|
292
|
+
private async verifySignature(
|
|
293
|
+
jws: string,
|
|
294
|
+
publicKeyJwk: Ed25519JWK,
|
|
295
|
+
canonicalPayloadBytes: Uint8Array,
|
|
296
|
+
expectedKid?: string
|
|
297
|
+
): Promise<ProofVerificationResult> {
|
|
298
|
+
const signatureValid = await this.cryptoService.verifyJWS(
|
|
299
|
+
jws,
|
|
300
|
+
publicKeyJwk,
|
|
301
|
+
{
|
|
302
|
+
detachedPayload: canonicalPayloadBytes,
|
|
303
|
+
expectedKid,
|
|
304
|
+
alg: "EdDSA",
|
|
305
|
+
}
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
if (!signatureValid) {
|
|
309
|
+
return {
|
|
310
|
+
valid: false,
|
|
311
|
+
reason: "Invalid JWS signature",
|
|
312
|
+
errorCode: PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,
|
|
313
|
+
details: {
|
|
314
|
+
jwsLength: jws.length,
|
|
315
|
+
expectedKid,
|
|
316
|
+
actualKid: publicKeyJwk.kid,
|
|
317
|
+
},
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return { valid: true };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Add nonce to cache to prevent replay (scoped to agent DID)
|
|
326
|
+
* @private
|
|
327
|
+
*/
|
|
328
|
+
private async addNonceToCache(
|
|
329
|
+
nonce: string,
|
|
330
|
+
agentDid: string
|
|
331
|
+
): Promise<void> {
|
|
332
|
+
// Pass TTL in seconds, not absolute timestamp
|
|
333
|
+
await this.nonceCache.add(nonce, this.nonceTtlSeconds, agentDid);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Fetch public key from DID document
|
|
338
|
+
* @param did - DID to resolve
|
|
339
|
+
* @param kid - Key ID (optional, defaults to first verification method)
|
|
340
|
+
* @returns Ed25519 JWK or null if not found
|
|
341
|
+
* @throws {ProofVerificationError} If DID resolution fails with specific error code
|
|
342
|
+
*/
|
|
343
|
+
async fetchPublicKeyFromDID(
|
|
344
|
+
did: string,
|
|
345
|
+
kid?: string
|
|
346
|
+
): Promise<Ed25519JWK | null> {
|
|
347
|
+
try {
|
|
348
|
+
const didDoc = await this.fetch.resolveDID(did);
|
|
349
|
+
|
|
350
|
+
if (!didDoc) {
|
|
351
|
+
throw new ProofVerificationError(
|
|
352
|
+
PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,
|
|
353
|
+
`DID document not found: ${did}`,
|
|
354
|
+
{ did }
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (
|
|
359
|
+
!didDoc.verificationMethod ||
|
|
360
|
+
didDoc.verificationMethod.length === 0
|
|
361
|
+
) {
|
|
362
|
+
throw new ProofVerificationError(
|
|
363
|
+
PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,
|
|
364
|
+
`No verification methods found in DID document: ${did}`,
|
|
365
|
+
{ did }
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Find verification method by kid or use first one
|
|
370
|
+
let verificationMethod:
|
|
371
|
+
| { id: string; publicKeyJwk?: unknown }
|
|
372
|
+
| undefined;
|
|
373
|
+
if (kid) {
|
|
374
|
+
const kidWithHash = kid.startsWith("#") ? kid : `#${kid}`;
|
|
375
|
+
verificationMethod = didDoc.verificationMethod.find(
|
|
376
|
+
(vm: { id: string }) =>
|
|
377
|
+
vm.id === kidWithHash || vm.id === `${did}${kidWithHash}`
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
if (!verificationMethod) {
|
|
381
|
+
throw new ProofVerificationError(
|
|
382
|
+
PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,
|
|
383
|
+
`Verification method not found for kid: ${kid}`,
|
|
384
|
+
{
|
|
385
|
+
did,
|
|
386
|
+
kid,
|
|
387
|
+
availableKids: didDoc.verificationMethod.map(
|
|
388
|
+
(vm: { id: string }) => vm.id
|
|
389
|
+
),
|
|
390
|
+
}
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
} else {
|
|
394
|
+
verificationMethod = didDoc.verificationMethod[0];
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (!verificationMethod?.publicKeyJwk) {
|
|
398
|
+
throw new ProofVerificationError(
|
|
399
|
+
PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,
|
|
400
|
+
`Public key JWK not found in verification method`,
|
|
401
|
+
{ did, kid, verificationMethodId: verificationMethod?.id }
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const jwk = verificationMethod.publicKeyJwk as {
|
|
406
|
+
kty?: string;
|
|
407
|
+
crv?: string;
|
|
408
|
+
x?: string;
|
|
409
|
+
[key: string]: unknown;
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
// Validate it's an Ed25519 key
|
|
413
|
+
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.x) {
|
|
414
|
+
throw new ProofVerificationError(
|
|
415
|
+
PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,
|
|
416
|
+
`Unsupported key type or curve: kty=${jwk.kty}, crv=${jwk.crv}`,
|
|
417
|
+
{ did, kid, jwk: { kty: jwk.kty, crv: jwk.crv } }
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
return jwk as Ed25519JWK;
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (error instanceof ProofVerificationError) {
|
|
424
|
+
throw error;
|
|
425
|
+
}
|
|
426
|
+
console.error(
|
|
427
|
+
"[ProofVerifier] Failed to fetch public key from DID:",
|
|
428
|
+
error
|
|
429
|
+
);
|
|
430
|
+
throw new ProofVerificationError(
|
|
431
|
+
PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,
|
|
432
|
+
`DID resolution failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
433
|
+
{
|
|
434
|
+
did,
|
|
435
|
+
kid,
|
|
436
|
+
originalError: error instanceof Error ? error.message : String(error),
|
|
437
|
+
}
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Build canonical payload from proof meta
|
|
444
|
+
*
|
|
445
|
+
* CRITICAL: This must reconstruct the exact JWS payload structure that was originally signed.
|
|
446
|
+
* The original JWS payload uses standard JWT claims (aud, sub, iss) plus custom proof claims,
|
|
447
|
+
* NOT the proof.meta structure directly.
|
|
448
|
+
*
|
|
449
|
+
* @param meta - Proof metadata
|
|
450
|
+
* @returns Canonical JSON string matching the original JWS payload structure
|
|
451
|
+
*/
|
|
452
|
+
buildCanonicalPayload(meta: DetachedProof["meta"]): string {
|
|
453
|
+
// Reconstruct the original JWS payload structure that was signed
|
|
454
|
+
// This matches the structure used in proof generation (proof.ts, proof-generator.ts)
|
|
455
|
+
const payload = {
|
|
456
|
+
// Standard JWT claims (RFC 7519) - these are what was actually signed
|
|
457
|
+
aud: meta.audience, // Audience (who the token is for)
|
|
458
|
+
sub: meta.did, // Subject (agent DID)
|
|
459
|
+
iss: meta.did, // Issuer (agent DID - self-issued)
|
|
460
|
+
|
|
461
|
+
// Custom MCP-I proof claims
|
|
462
|
+
requestHash: meta.requestHash,
|
|
463
|
+
responseHash: meta.responseHash,
|
|
464
|
+
ts: meta.ts,
|
|
465
|
+
nonce: meta.nonce,
|
|
466
|
+
sessionId: meta.sessionId,
|
|
467
|
+
|
|
468
|
+
// Optional claims (only include if present)
|
|
469
|
+
...(meta.scopeId && { scopeId: meta.scopeId }),
|
|
470
|
+
...(meta.delegationRef && { delegationRef: meta.delegationRef }),
|
|
471
|
+
...(meta.clientDid && { clientDid: meta.clientDid }),
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// Canonicalize the reconstructed payload using the same function as proof generation
|
|
475
|
+
// CRITICAL: Must use json-canonicalize canonicalize() to match proof.ts exactly
|
|
476
|
+
return canonicalize(payload);
|
|
477
|
+
}
|
|
478
|
+
}
|