@kya-os/mcp-i-runtime 1.3.1 → 1.3.3
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/.turbo/turbo-build.log +1 -1
- package/dist/auth/handshake.d.ts +23 -43
- package/dist/auth/handshake.d.ts.map +1 -1
- package/dist/auth/handshake.js +51 -82
- package/dist/auth/handshake.js.map +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/resume-token.d.ts +52 -0
- package/dist/auth/resume-token.d.ts.map +1 -0
- package/dist/auth/resume-token.js +89 -0
- package/dist/auth/resume-token.js.map +1 -0
- package/dist/auth/types.d.ts +15 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +25 -3
- package/dist/index.js.map +1 -1
- package/dist/proof/companion.d.ts +25 -0
- package/dist/proof/companion.d.ts.map +1 -0
- package/dist/proof/companion.js +14 -0
- package/dist/proof/companion.js.map +1 -0
- package/dist/proof/generator.d.ts +22 -9
- package/dist/proof/generator.d.ts.map +1 -1
- package/dist/proof/generator.js +20 -27
- package/dist/proof/generator.js.map +1 -1
- package/dist/proof/index.d.ts +2 -1
- package/dist/proof/index.d.ts.map +1 -1
- package/dist/proof/index.js +3 -1
- package/dist/proof/index.js.map +1 -1
- package/dist/runtime/audit.d.ts.map +1 -1
- package/dist/runtime/audit.js +78 -18
- package/dist/runtime/audit.js.map +1 -1
- package/dist/runtime/base.d.ts +6 -1
- package/dist/runtime/base.d.ts.map +1 -1
- package/dist/runtime/base.js +65 -17
- package/dist/runtime/base.js.map +1 -1
- package/dist/runtime/dif-core.d.ts +8 -0
- package/dist/runtime/dif-core.d.ts.map +1 -1
- package/dist/runtime/dif-core.js +10 -0
- package/dist/runtime/dif-core.js.map +1 -1
- package/dist/services/access-control.service.d.ts.map +1 -1
- package/dist/services/access-control.service.js +12 -5
- package/dist/services/access-control.service.js.map +1 -1
- package/dist/services/claims-first-guard.d.ts +33 -0
- package/dist/services/claims-first-guard.d.ts.map +1 -0
- package/dist/services/claims-first-guard.js +77 -0
- package/dist/services/claims-first-guard.js.map +1 -0
- package/dist/services/holder-keys.d.ts +95 -0
- package/dist/services/holder-keys.d.ts.map +1 -0
- package/dist/services/holder-keys.js +281 -0
- package/dist/services/holder-keys.js.map +1 -0
- package/dist/services/holder-read-slots.d.ts +42 -0
- package/dist/services/holder-read-slots.d.ts.map +1 -0
- package/dist/services/holder-read-slots.js +82 -0
- package/dist/services/holder-read-slots.js.map +1 -0
- package/dist/services/proof-verifier.d.ts +13 -35
- package/dist/services/proof-verifier.d.ts.map +1 -1
- package/dist/services/proof-verifier.js +16 -74
- package/dist/services/proof-verifier.js.map +1 -1
- package/dist/services/request-holder.d.ts +78 -0
- package/dist/services/request-holder.d.ts.map +1 -0
- package/dist/services/request-holder.js +81 -0
- package/dist/services/request-holder.js.map +1 -0
- package/dist/services/tool-context-builder.d.ts.map +1 -1
- package/dist/services/tool-context-builder.js +16 -4
- package/dist/services/tool-context-builder.js.map +1 -1
- package/dist/services/tool-protection.service.d.ts +7 -0
- package/dist/services/tool-protection.service.d.ts.map +1 -1
- package/dist/services/tool-protection.service.js +34 -15
- package/dist/services/tool-protection.service.js.map +1 -1
- package/dist/types/tool-protection.d.ts +94 -0
- package/dist/types/tool-protection.d.ts.map +1 -1
- package/dist/types/tool-protection.js +113 -1
- package/dist/types/tool-protection.js.map +1 -1
- package/eslint.config.js +20 -0
- package/package.json +8 -2
- package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
- package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
- package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
- package/src/__tests__/runtime/audit.test.ts +363 -53
- package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
- package/src/__tests__/runtime/provider-selection.test.ts +4 -6
- package/src/__tests__/runtime/route-interception.test.ts +215 -214
- package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
- package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
- package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
- package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
- package/src/auth/__tests__/verify-or-hints-presented.test.ts +155 -0
- package/src/auth/handshake.ts +80 -125
- package/src/auth/index.ts +1 -0
- package/src/auth/resume-token.ts +134 -0
- package/src/auth/types.ts +20 -2
- package/src/index.ts +40 -1
- package/src/proof/__tests__/proof-generator.test.ts +80 -13
- package/src/proof/companion.ts +35 -0
- package/src/proof/generator.ts +51 -33
- package/src/proof/index.ts +3 -0
- package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
- package/src/runtime/audit.ts +170 -65
- package/src/runtime/base.ts +95 -31
- package/src/runtime/dif-core.ts +16 -0
- package/src/services/__tests__/access-control.service.test.ts +44 -0
- package/src/services/__tests__/claims-first-guard.test.ts +93 -0
- package/src/services/__tests__/holder-fixtures.ts +135 -0
- package/src/services/__tests__/holder-keys.test.ts +257 -0
- package/src/services/__tests__/holder-read-slots.test.ts +117 -0
- package/src/services/__tests__/holder-reads.test.ts +284 -0
- package/src/services/__tests__/proof-verifier.test.ts +286 -195
- package/src/services/__tests__/request-holder.test.ts +210 -0
- package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
- package/src/services/__tests__/tool-context-builder.test.ts +4 -7
- package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
- package/src/services/access-control.service.ts +11 -5
- package/src/services/claims-first-guard.ts +89 -0
- package/src/services/holder-keys.ts +379 -0
- package/src/services/holder-read-slots.ts +85 -0
- package/src/services/proof-verifier.ts +18 -79
- package/src/services/request-holder.ts +146 -0
- package/src/services/tool-context-builder.ts +19 -4
- package/src/services/tool-protection.service.ts +62 -19
- package/src/types/tool-protection.ts +161 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Holder keys: the keys a request proof's holder DID publishes, as the
|
|
3
|
+
* `resolveKey` and `resolveDidKeys` seams of `@kya-os/mcp/card`'s
|
|
4
|
+
* `requireProof` take them.
|
|
5
|
+
*
|
|
6
|
+
* A did:web holder's keys are the Ed25519 methods its DID document lists
|
|
7
|
+
* under `authentication`, the relationship by which a DID's subject proves it
|
|
8
|
+
* is the party calling. `@kya-os/mcp/card`'s `didKeyedJwks` projects them, as
|
|
9
|
+
* it does for a CIMD client's `private_key_jwt`. The document is read through
|
|
10
|
+
* `@kya-os/mcp`'s did:web resolver over its `RuntimeFetchProvider`: a bounded
|
|
11
|
+
* read under the private-network rule, with the connection pinned to the
|
|
12
|
+
* checked address where the runtime resolves host names, within a deadline,
|
|
13
|
+
* and cached per resolver.
|
|
14
|
+
*
|
|
15
|
+
* A holder whose document does not resolve has no keys, so its proof is
|
|
16
|
+
* refused. Why it did not resolve goes to the log, never to the caller, and
|
|
17
|
+
* the failure is remembered for a short while, so calls that prove nothing
|
|
18
|
+
* cannot each drive a read. A proof naming a key the cached document lacks,
|
|
19
|
+
* as after a key rotation, reads the document again, at most once a while
|
|
20
|
+
* per holder, when the resolver can drop what it cached (the library's
|
|
21
|
+
* did:web resolver can).
|
|
22
|
+
*
|
|
23
|
+
* Nothing has verified a proof when its holder's document is read, so a
|
|
24
|
+
* call can name any host. What that can cost is bounded three ways. A
|
|
25
|
+
* server that names `didWebHosts` reads no other host. Documents are read
|
|
26
|
+
* in slots (./holder-read-slots), a few at once in all and for one host.
|
|
27
|
+
* And the holders whose document has resolved before have slots of their
|
|
28
|
+
* own, so a flood of holders that never resolve cannot hold up the agents a
|
|
29
|
+
* server already serves. A failed read is remembered for the holder, not
|
|
30
|
+
* its host: one caller naming holders a host does not have must not refuse
|
|
31
|
+
* every agent that host does have. With no `didWebHosts`, a caller that
|
|
32
|
+
* hosts documents of its own can still fill the slots, which is why a
|
|
33
|
+
* server that knows its agents' hosts should name them.
|
|
34
|
+
*
|
|
35
|
+
* Every other holder goes to the seams the caller gives: each runtime keeps
|
|
36
|
+
* its own did:key resolution.
|
|
37
|
+
*
|
|
38
|
+
* @module services/holder-keys
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import type {
|
|
42
|
+
DIDResolver,
|
|
43
|
+
RuntimeFetchProviderOptions,
|
|
44
|
+
} from "@kya-os/mcp" with { "resolution-mode": "import" };
|
|
45
|
+
import { logger } from "../logging";
|
|
46
|
+
import { loadDifCard, loadDifCore, type DifCard } from "../runtime/dif-core";
|
|
47
|
+
import { HolderReadsBusyError, ReadSlots } from "./holder-read-slots";
|
|
48
|
+
|
|
49
|
+
type VerifyProofDeps = Parameters<DifCard["requireProof"]>[0];
|
|
50
|
+
|
|
51
|
+
/** A public key a request proof is verified with. */
|
|
52
|
+
export type ProofPublicJwk = Awaited<ReturnType<VerifyProofDeps["resolveKey"]>>;
|
|
53
|
+
|
|
54
|
+
/** The key seams a request proof is verified with. */
|
|
55
|
+
export interface HolderKeySeams {
|
|
56
|
+
/** The key `kid` names; throws when its DID publishes no such key. */
|
|
57
|
+
resolveKey(kid: string): Promise<ProofPublicJwk>;
|
|
58
|
+
/** Every key `did` publishes for the proof to be checked against. */
|
|
59
|
+
resolveDidKeys(did: string): Promise<ProofPublicJwk[]>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface DidWebHolderOptions {
|
|
63
|
+
/**
|
|
64
|
+
* The did:web resolver. Default: one `@kya-os/mcp` did:web resolver per
|
|
65
|
+
* process over a `RuntimeFetchProvider`, so a holder's document stays
|
|
66
|
+
* cached across calls.
|
|
67
|
+
*/
|
|
68
|
+
didWebResolver?: DIDResolver;
|
|
69
|
+
/**
|
|
70
|
+
* Options for the `RuntimeFetchProvider` a holder's document is read
|
|
71
|
+
* through, when no `didWebResolver` is given: one resolver over a provider
|
|
72
|
+
* with these options serves these seams. `{ development: true }` reads a
|
|
73
|
+
* did:web holder on this machine, such as `did:web:localhost%3A8443`, in
|
|
74
|
+
* local development; the provider throws when it is built while
|
|
75
|
+
* `NODE_ENV` is `production`.
|
|
76
|
+
*/
|
|
77
|
+
didWebFetch?: RuntimeFetchProviderOptions;
|
|
78
|
+
/**
|
|
79
|
+
* The hosts whose did:web holders this server reads, each as a DID names
|
|
80
|
+
* it: `agents.example`, or `agents.example:8443` with its port. A holder
|
|
81
|
+
* on any other host is refused unread. Default: any host the
|
|
82
|
+
* private-network rule admits. Name them when you know where your agents'
|
|
83
|
+
* DIDs live, since a call names its holder before anything verifies it.
|
|
84
|
+
*/
|
|
85
|
+
didWebHosts?: readonly string[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** How long a holder whose document did not resolve is refused unread. */
|
|
89
|
+
const FAILED_READ_TTL_MS = 15_000;
|
|
90
|
+
/** How often a holder's document may be read again for a key it lacks. */
|
|
91
|
+
const REREAD_INTERVAL_MS = 30_000;
|
|
92
|
+
/** How long a holder whose document resolved keeps its place among the known. */
|
|
93
|
+
const KNOWN_HOLDER_TTL_MS = 60 * 60_000;
|
|
94
|
+
/** The most holders each of those remembers, the oldest forgotten first. */
|
|
95
|
+
const MAX_REMEMBERED_HOLDERS = 1_024;
|
|
96
|
+
/**
|
|
97
|
+
* The slots of the holders whose document has resolved before, and again of
|
|
98
|
+
* those whose document has not: so many read at once, so many of one host,
|
|
99
|
+
* and so many waiting their turn, one more being refused.
|
|
100
|
+
*/
|
|
101
|
+
export const HOLDER_READ_SLOTS = {
|
|
102
|
+
total: 16,
|
|
103
|
+
perHost: 4,
|
|
104
|
+
waiting: 256,
|
|
105
|
+
} as const;
|
|
106
|
+
|
|
107
|
+
/** Holders remembered for a while, bounded in number. */
|
|
108
|
+
class RecentHolders {
|
|
109
|
+
private readonly until = new Map<string, number>();
|
|
110
|
+
|
|
111
|
+
constructor(private readonly ttlMs: number) {}
|
|
112
|
+
|
|
113
|
+
has(did: string): boolean {
|
|
114
|
+
const until = this.until.get(did);
|
|
115
|
+
if (until === undefined) return false;
|
|
116
|
+
if (Date.now() < until) return true;
|
|
117
|
+
this.until.delete(did);
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
add(did: string): void {
|
|
122
|
+
this.until.delete(did);
|
|
123
|
+
const oldest = this.until.keys().next();
|
|
124
|
+
if (!oldest.done && this.until.size >= MAX_REMEMBERED_HOLDERS) {
|
|
125
|
+
this.until.delete(oldest.value);
|
|
126
|
+
}
|
|
127
|
+
this.until.set(did, Date.now() + this.ttlMs);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A resolver that can drop the document it cached for a DID. */
|
|
132
|
+
type RereadableResolver = DIDResolver & {
|
|
133
|
+
clearCacheEntry?: (did: string) => void;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
let sharedResolver: Promise<DIDResolver> | undefined;
|
|
137
|
+
|
|
138
|
+
/** The process's did:web resolver, built on first use. */
|
|
139
|
+
function sharedDidWebResolver(): Promise<DIDResolver> {
|
|
140
|
+
return (sharedResolver ??= loadDifCore().then(
|
|
141
|
+
({ createDidWebResolver, RuntimeFetchProvider }) =>
|
|
142
|
+
createDidWebResolver(new RuntimeFetchProvider())
|
|
143
|
+
));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The DID a DID or DID URL names. */
|
|
147
|
+
const didOf = (didOrKid: string) => didOrKid.split("#")[0] ?? "";
|
|
148
|
+
|
|
149
|
+
/** `host` as a URL writes it, lower case and with any port, or undefined. */
|
|
150
|
+
function hostOf(host: string): string | undefined {
|
|
151
|
+
try {
|
|
152
|
+
const url = new URL(`https://${host}`);
|
|
153
|
+
return url.host !== "" && `https://${url.host}/` === url.href
|
|
154
|
+
? url.host
|
|
155
|
+
: undefined;
|
|
156
|
+
} catch {
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Whether a host is one `hosts` names; every host is when they name none.
|
|
163
|
+
*
|
|
164
|
+
* @throws TypeError for an entry that is not a host
|
|
165
|
+
*/
|
|
166
|
+
function namedHosts(
|
|
167
|
+
hosts: readonly string[] | undefined
|
|
168
|
+
): (host: string) => boolean {
|
|
169
|
+
if (hosts === undefined) return () => true;
|
|
170
|
+
const named = new Set(
|
|
171
|
+
hosts.map((entry) => {
|
|
172
|
+
const host = typeof entry === "string" ? hostOf(entry) : undefined;
|
|
173
|
+
if (host === undefined || host !== entry.toLowerCase()) {
|
|
174
|
+
throw new TypeError(
|
|
175
|
+
`didWebHosts names "${String(entry)}", which is not a host such as agents.example or agents.example:8443`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
return host;
|
|
179
|
+
})
|
|
180
|
+
);
|
|
181
|
+
return (host) => named.has(host);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The keys `did`'s document lists under `authentication`. Throws when the
|
|
186
|
+
* document does not resolve, after logging why.
|
|
187
|
+
*/
|
|
188
|
+
async function authenticationKeys(
|
|
189
|
+
did: string,
|
|
190
|
+
resolver: DIDResolver
|
|
191
|
+
): Promise<ProofPublicJwk[]> {
|
|
192
|
+
const document = await resolver.resolve(did);
|
|
193
|
+
if (!document) {
|
|
194
|
+
const failure = resolver.lastFailure?.(did);
|
|
195
|
+
logger.warn(
|
|
196
|
+
`[RequestHolder] No DID document for holder ${did}: ${
|
|
197
|
+
failure ? `${failure.cause}: ${failure.detail}` : "it did not resolve"
|
|
198
|
+
}`
|
|
199
|
+
);
|
|
200
|
+
throw new Error("The holder's DID document did not resolve");
|
|
201
|
+
}
|
|
202
|
+
const { didKeyedJwks } = await loadDifCard();
|
|
203
|
+
// didKeyedJwks names a key by its JWK's own `kid` when it has one, which
|
|
204
|
+
// hides its method's id, the name a proof's `kid` uses. Each key is listed
|
|
205
|
+
// under its method's id, and under a `kid` of its own beside it.
|
|
206
|
+
const byMethod = didKeyedJwks(namedByMethod(document)).keys;
|
|
207
|
+
const methodNames = new Set(byMethod.map(({ kid }) => kid));
|
|
208
|
+
return [
|
|
209
|
+
...byMethod,
|
|
210
|
+
...didKeyedJwks(document).keys.filter(({ kid }) => !methodNames.has(kid)),
|
|
211
|
+
];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** `method` with a JWK that carries no `kid` of its own. */
|
|
215
|
+
function withoutOwnKid(method: unknown): unknown {
|
|
216
|
+
if (typeof method !== "object" || method === null) return method;
|
|
217
|
+
const jwk = (method as { publicKeyJwk?: unknown }).publicKeyJwk;
|
|
218
|
+
if (typeof jwk !== "object" || jwk === null || !("kid" in jwk)) return method;
|
|
219
|
+
return {
|
|
220
|
+
...method,
|
|
221
|
+
publicKeyJwk: Object.fromEntries(
|
|
222
|
+
Object.entries(jwk).filter(([name]) => name !== "kid")
|
|
223
|
+
),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** `document` with every key named by its verification method's id alone. */
|
|
228
|
+
function namedByMethod<D extends object>(document: D): D {
|
|
229
|
+
const { verificationMethod, authentication } = document as {
|
|
230
|
+
verificationMethod?: unknown;
|
|
231
|
+
authentication?: unknown;
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
...document,
|
|
235
|
+
...(Array.isArray(verificationMethod)
|
|
236
|
+
? { verificationMethod: verificationMethod.map(withoutOwnKid) }
|
|
237
|
+
: {}),
|
|
238
|
+
...(Array.isArray(authentication)
|
|
239
|
+
? { authentication: authentication.map(withoutOwnKid) }
|
|
240
|
+
: {}),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The key `kid` names among `did`'s keys. A key is named by its method's
|
|
246
|
+
* id, or by its JWK's `kid`, as written: a DID URL, a relative `#fragment`,
|
|
247
|
+
* or a bare fragment such as `key-1`.
|
|
248
|
+
*/
|
|
249
|
+
function keyNamed(
|
|
250
|
+
keys: ProofPublicJwk[],
|
|
251
|
+
did: string,
|
|
252
|
+
kid: string
|
|
253
|
+
): ProofPublicJwk | undefined {
|
|
254
|
+
const fragment = kid.startsWith(`${did}#`)
|
|
255
|
+
? kid.slice(did.length + 1)
|
|
256
|
+
: undefined;
|
|
257
|
+
return keys.find(
|
|
258
|
+
({ kid: id }) =>
|
|
259
|
+
id === kid ||
|
|
260
|
+
(fragment !== undefined && (id === `#${fragment}` || id === fragment))
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The resolver `options` name, or the one they configure, or the process's. */
|
|
265
|
+
function resolverOf(options: DidWebHolderOptions): () => Promise<DIDResolver> {
|
|
266
|
+
const { didWebResolver, didWebFetch } = options;
|
|
267
|
+
if (didWebResolver) return async () => didWebResolver;
|
|
268
|
+
if (!didWebFetch) return sharedDidWebResolver;
|
|
269
|
+
let own: Promise<DIDResolver> | undefined;
|
|
270
|
+
return () =>
|
|
271
|
+
(own ??= loadDifCore().then(
|
|
272
|
+
({ createDidWebResolver, RuntimeFetchProvider }) =>
|
|
273
|
+
createDidWebResolver(new RuntimeFetchProvider(didWebFetch))
|
|
274
|
+
));
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The key seams of a did:web holder, read from its DID document. */
|
|
278
|
+
export function didWebHolderKeys(
|
|
279
|
+
options: DidWebHolderOptions = {}
|
|
280
|
+
): HolderKeySeams {
|
|
281
|
+
const resolver = resolverOf(options);
|
|
282
|
+
const isNamedHost = namedHosts(options.didWebHosts);
|
|
283
|
+
const failed = new RecentHolders(FAILED_READ_TTL_MS);
|
|
284
|
+
const reread = new RecentHolders(REREAD_INTERVAL_MS);
|
|
285
|
+
const known = new RecentHolders(KNOWN_HOLDER_TTL_MS);
|
|
286
|
+
const knownSlots = new ReadSlots(HOLDER_READ_SLOTS);
|
|
287
|
+
const newSlots = new ReadSlots(HOLDER_READ_SLOTS);
|
|
288
|
+
const reading = new Map<string, Promise<ProofPublicJwk[]>>();
|
|
289
|
+
let busyLoggedAt = 0;
|
|
290
|
+
|
|
291
|
+
/** Read `did`'s keys in a slot: one of the known holders', or of the new. */
|
|
292
|
+
const read = async (did: string) => {
|
|
293
|
+
const { didWebToUrl } = await loadDifCore();
|
|
294
|
+
const url = didWebToUrl(did);
|
|
295
|
+
const host = url ? new URL(url).host : "";
|
|
296
|
+
if (!isNamedHost(host)) {
|
|
297
|
+
logger.warn(
|
|
298
|
+
`[RequestHolder] Holder ${did} is on a host didWebHosts does not name; its document is not read`
|
|
299
|
+
);
|
|
300
|
+
throw new Error("The holder's host is not one this server reads");
|
|
301
|
+
}
|
|
302
|
+
const slots = known.has(did) ? knownSlots : newSlots;
|
|
303
|
+
const keys = await slots.run(host, async () =>
|
|
304
|
+
authenticationKeys(did, await resolver())
|
|
305
|
+
);
|
|
306
|
+
known.add(did);
|
|
307
|
+
return keys;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const keysOf = (did: string): Promise<ProofPublicJwk[]> => {
|
|
311
|
+
if (failed.has(did)) {
|
|
312
|
+
return Promise.reject(
|
|
313
|
+
new Error("The holder's DID document did not resolve")
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
// Calls that prove one holder at once share its one read.
|
|
317
|
+
const shared = reading.get(did);
|
|
318
|
+
if (shared) return shared;
|
|
319
|
+
const pending = read(did)
|
|
320
|
+
.catch((error: unknown) => {
|
|
321
|
+
if (error instanceof HolderReadsBusyError) {
|
|
322
|
+
// No verdict on the holder: nothing was read, so nothing is remembered.
|
|
323
|
+
if (Date.now() - busyLoggedAt >= FAILED_READ_TTL_MS) {
|
|
324
|
+
busyLoggedAt = Date.now();
|
|
325
|
+
logger.warn(
|
|
326
|
+
`[RequestHolder] ${error.message}; new did:web holders are refused until some finish`
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
} else {
|
|
330
|
+
failed.add(did);
|
|
331
|
+
}
|
|
332
|
+
throw error;
|
|
333
|
+
})
|
|
334
|
+
.finally(() => reading.delete(did));
|
|
335
|
+
reading.set(did, pending);
|
|
336
|
+
return pending;
|
|
337
|
+
};
|
|
338
|
+
/** `kid`'s key in a fresh read of `did`'s document, if one is due. */
|
|
339
|
+
const rereadKey = async (did: string, kid: string) => {
|
|
340
|
+
const current: RereadableResolver = await resolver();
|
|
341
|
+
if (typeof current.clearCacheEntry !== "function" || reread.has(did)) {
|
|
342
|
+
return undefined;
|
|
343
|
+
}
|
|
344
|
+
reread.add(did);
|
|
345
|
+
current.clearCacheEntry(did);
|
|
346
|
+
return keyNamed(await keysOf(did), did, kid);
|
|
347
|
+
};
|
|
348
|
+
return {
|
|
349
|
+
async resolveKey(kid) {
|
|
350
|
+
const did = didOf(kid);
|
|
351
|
+
const key =
|
|
352
|
+
keyNamed(await keysOf(did), did, kid) ?? (await rereadKey(did, kid));
|
|
353
|
+
if (!key) {
|
|
354
|
+
throw new Error(
|
|
355
|
+
"The holder's DID document lists no such key for authentication"
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
return key;
|
|
359
|
+
},
|
|
360
|
+
resolveDidKeys: keysOf,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Seams that read a did:web holder's keys from its DID document, and hand
|
|
366
|
+
* every other holder to `otherHolders`.
|
|
367
|
+
*/
|
|
368
|
+
export function withDidWebHolders(
|
|
369
|
+
otherHolders: HolderKeySeams,
|
|
370
|
+
options: DidWebHolderOptions = {}
|
|
371
|
+
): HolderKeySeams {
|
|
372
|
+
const web = didWebHolderKeys(options);
|
|
373
|
+
const seamsFor = async (didOrKid: string) =>
|
|
374
|
+
(await loadDifCore()).isDidWeb(didOf(didOrKid)) ? web : otherHolders;
|
|
375
|
+
return {
|
|
376
|
+
resolveKey: async (kid) => (await seamsFor(kid)).resolveKey(kid),
|
|
377
|
+
resolveDidKeys: async (did) => (await seamsFor(did)).resolveDidKeys(did),
|
|
378
|
+
};
|
|
379
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slots holder documents are read in.
|
|
3
|
+
*
|
|
4
|
+
* A request proof names its holder before anything verifies it, so a call
|
|
5
|
+
* can name any did:web holder and have its document read. The reads such
|
|
6
|
+
* calls drive are held to so many at once, in all and for one host; a read
|
|
7
|
+
* beyond that waits its turn, in the order it came, and a read beyond the
|
|
8
|
+
* line is refused. A burst of new holders is then read a few at a time, and
|
|
9
|
+
* no number of calls opens more connections than the slots.
|
|
10
|
+
*
|
|
11
|
+
* @module services/holder-read-slots
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A read refused because the slots and the line behind them are full. */
|
|
15
|
+
export class HolderReadsBusyError extends Error {
|
|
16
|
+
constructor() {
|
|
17
|
+
super("Too many holder documents are being read");
|
|
18
|
+
this.name = "HolderReadsBusyError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ReadSlotLimits {
|
|
23
|
+
/** The most reads at once. */
|
|
24
|
+
total: number;
|
|
25
|
+
/** The most reads at once of one host. */
|
|
26
|
+
perHost: number;
|
|
27
|
+
/** The most reads waiting for a slot. */
|
|
28
|
+
waiting: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class ReadSlots {
|
|
32
|
+
private reading = 0;
|
|
33
|
+
private readonly readingOf = new Map<string, number>();
|
|
34
|
+
private readonly line: Array<{ host: string; start: () => void }> = [];
|
|
35
|
+
|
|
36
|
+
constructor(private readonly limits: ReadSlotLimits) {}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Run `read` of a document on `host` in a slot, waiting for one in line.
|
|
40
|
+
*
|
|
41
|
+
* @throws HolderReadsBusyError when the line is full; `read` did not run
|
|
42
|
+
*/
|
|
43
|
+
async run<T>(host: string, read: () => Promise<T>): Promise<T> {
|
|
44
|
+
if (this.hasSlot(host)) {
|
|
45
|
+
this.take(host);
|
|
46
|
+
} else if (this.line.length >= this.limits.waiting) {
|
|
47
|
+
throw new HolderReadsBusyError();
|
|
48
|
+
} else {
|
|
49
|
+
// Its slot is taken for it when its turn comes (./release).
|
|
50
|
+
await new Promise<void>((start) => this.line.push({ host, start }));
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
return await read();
|
|
54
|
+
} finally {
|
|
55
|
+
this.release(host);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private hasSlot(host: string): boolean {
|
|
60
|
+
return (
|
|
61
|
+
this.reading < this.limits.total &&
|
|
62
|
+
(this.readingOf.get(host) ?? 0) < this.limits.perHost
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private take(host: string): void {
|
|
67
|
+
this.reading += 1;
|
|
68
|
+
this.readingOf.set(host, (this.readingOf.get(host) ?? 0) + 1);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Free `host`'s slot, and give one to the first read in line it suits. */
|
|
72
|
+
private release(host: string): void {
|
|
73
|
+
this.reading -= 1;
|
|
74
|
+
const left = (this.readingOf.get(host) ?? 1) - 1;
|
|
75
|
+
if (left > 0) this.readingOf.set(host, left);
|
|
76
|
+
else this.readingOf.delete(host);
|
|
77
|
+
|
|
78
|
+
const next = this.line.findIndex((waiting) => this.hasSlot(waiting.host));
|
|
79
|
+
if (next < 0) return;
|
|
80
|
+
const [waiting] = this.line.splice(next, 1);
|
|
81
|
+
if (!waiting) return;
|
|
82
|
+
this.take(waiting.host);
|
|
83
|
+
waiting.start();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -14,19 +14,11 @@
|
|
|
14
14
|
* `runtime/base.ts` and the runtime subclasses that inject a `ProofVerifier` —
|
|
15
15
|
* are unchanged.
|
|
16
16
|
*
|
|
17
|
-
* `verifyProof` calls DIF's `
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* add to the payload (see `buildCanonicalPayload`'s doc comment) — supplying
|
|
23
|
-
* the payload ourselves keeps the crypto/replay/skew pipeline delegated to
|
|
24
|
-
* DIF while staying correct regardless of DIF's release cadence. One
|
|
25
|
-
* consequence: the content-binding fail-closed check (DIF's `verifyProof`
|
|
26
|
-
* third `expected` argument) is not reachable through `verifyProofDetached`,
|
|
27
|
-
* but this façade never passed that argument through anyway. The one
|
|
28
|
-
* pre-C2 default that differs (local timestamp skew defaulted to 300s vs
|
|
29
|
-
* DIF's 120s) is preserved explicitly when composing the DIF verifier.
|
|
17
|
+
* `verifyProof` calls DIF's `verifyProof`, which rebuilds the signed payload
|
|
18
|
+
* from `proof.meta` with the same `buildProofJwsPayload` the signers use, so
|
|
19
|
+
* nothing in this repo reconstructs the payload itself. The one pre-C2
|
|
20
|
+
* default that differs (local timestamp skew defaulted to 300s vs DIF's
|
|
21
|
+
* 120s) is preserved explicitly when composing the DIF verifier.
|
|
30
22
|
*/
|
|
31
23
|
|
|
32
24
|
import { type Ed25519JWK } from "./crypto.service.js";
|
|
@@ -113,17 +105,9 @@ export class ProofVerifier {
|
|
|
113
105
|
* Verify a DetachedProof. Checks the JWS signature, nonce replay, and
|
|
114
106
|
* timestamp skew via the DIF `ProofVerifier` pipeline.
|
|
115
107
|
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
* the payload using ITS OWN internal builder). `@kya-os/mcp` is a
|
|
120
|
-
* separately-versioned, externally-published dependency; its internal
|
|
121
|
-
* builder does not know about the literal did/kid/audience/toolName/
|
|
122
|
-
* outcome fields this repo's signers add to the payload, so proofs signed
|
|
123
|
-
* here would fail `@kya-os/mcp`'s own reconstruction even though the
|
|
124
|
-
* signature is genuinely valid. Supplying the payload ourselves keeps the
|
|
125
|
-
* nonce-replay/timestamp-skew/signature pipeline delegated to DIF while
|
|
126
|
-
* sidestepping its stale reconstruction.
|
|
108
|
+
* Calls the DIF verifier's `verifyProof()`, which rebuilds the signed
|
|
109
|
+
* payload from `proof.meta` (the shared `buildProofJwsPayload`, RFC 8785)
|
|
110
|
+
* and checks the signature over it.
|
|
127
111
|
*
|
|
128
112
|
* @param proof - The proof to verify
|
|
129
113
|
* @param publicKeyJwk - Ed25519 public key in JWK format (from DID document)
|
|
@@ -134,10 +118,8 @@ export class ProofVerifier {
|
|
|
134
118
|
publicKeyJwk: Ed25519JWK
|
|
135
119
|
): Promise<ProofVerificationResult> {
|
|
136
120
|
const verifier = await this.getDifVerifier();
|
|
137
|
-
|
|
138
|
-
return verifier.verifyProofDetached(
|
|
121
|
+
return verifier.verifyProof(
|
|
139
122
|
proof,
|
|
140
|
-
canonicalPayload,
|
|
141
123
|
publicKeyJwk
|
|
142
124
|
) as Promise<ProofVerificationResult>;
|
|
143
125
|
}
|
|
@@ -271,60 +253,17 @@ export class ProofVerifier {
|
|
|
271
253
|
}
|
|
272
254
|
|
|
273
255
|
/**
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
* The original JWS payload uses standard JWT claims (aud, sub, iss) plus custom proof claims,
|
|
278
|
-
* NOT the proof.meta structure directly.
|
|
279
|
-
*
|
|
280
|
-
* Kept local (not delegated): callers invoke this synchronously, while the DIF
|
|
281
|
-
* verifier is only reachable through the async seam. The reconstruction is
|
|
282
|
-
* byte-identical to DIF's `buildCanonicalPayload`.
|
|
256
|
+
* The canonical (RFC 8785) JWS payload for `meta`, for detached-JWS
|
|
257
|
+
* consumers. Delegates to `@kya-os/mcp`'s `buildProofJwsPayload`; async
|
|
258
|
+
* because that module is reached through the ESM-bridge seam.
|
|
283
259
|
*
|
|
284
260
|
* @param meta - Proof metadata
|
|
285
|
-
* @returns Canonical JSON string
|
|
261
|
+
* @returns Canonical JSON string identical to the payload a signer signs
|
|
286
262
|
*/
|
|
287
|
-
buildCanonicalPayload(meta: DetachedProof["meta"]): string {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
aud: meta.audience, // Audience (who the token is for)
|
|
293
|
-
sub: meta.did, // Subject (agent DID)
|
|
294
|
-
iss: meta.did, // Issuer (agent DID - self-issued)
|
|
295
|
-
|
|
296
|
-
// Literal field names some verifiers (e.g. knowthat.ai) check by
|
|
297
|
-
// exact property, rather than the JWT-standard aliases above -- must
|
|
298
|
-
// stay in lockstep with generator.ts's payload, or reconstruction
|
|
299
|
-
// here will byte-diverge from what was actually signed.
|
|
300
|
-
did: meta.did,
|
|
301
|
-
kid: meta.kid,
|
|
302
|
-
audience: meta.audience,
|
|
303
|
-
|
|
304
|
-
// Custom MCP-I proof claims
|
|
305
|
-
requestHash: meta.requestHash,
|
|
306
|
-
responseHash: meta.responseHash,
|
|
307
|
-
ts: meta.ts,
|
|
308
|
-
nonce: meta.nonce,
|
|
309
|
-
sessionId: meta.sessionId,
|
|
310
|
-
|
|
311
|
-
// Optional claims (only include if present)
|
|
312
|
-
...(meta.scopeId && { scopeId: meta.scopeId }),
|
|
313
|
-
...(meta.delegationRef && { delegationRef: meta.delegationRef }),
|
|
314
|
-
...(meta.clientDid && { clientDid: meta.clientDid }),
|
|
315
|
-
...(meta.toolName && { toolName: meta.toolName }),
|
|
316
|
-
...(meta.submissionOutcome && { outcome: meta.submissionOutcome }),
|
|
317
|
-
};
|
|
318
|
-
|
|
319
|
-
// generator.ts signs this payload via jose's SignJWT, which serializes
|
|
320
|
-
// with a plain JSON.stringify() in object-insertion order (see
|
|
321
|
-
// JWTClaimsBuilder.data() in the jose source) -- NOT RFC 8785 JCS.
|
|
322
|
-
// canonicalize() sorts keys alphabetically, which byte-diverges from
|
|
323
|
-
// what was actually signed even when every field VALUE matches (this
|
|
324
|
-
// silently broke DIF-delegated verification: see the regression tests
|
|
325
|
-
// above). The object literal above already mirrors generator.ts's
|
|
326
|
-
// field order exactly, so a plain JSON.stringify() here reproduces the
|
|
327
|
-
// exact bytes that were signed.
|
|
328
|
-
return JSON.stringify(payload);
|
|
263
|
+
async buildCanonicalPayload(meta: DetachedProof["meta"]): Promise<string> {
|
|
264
|
+
const { buildProofJwsPayload, canonicalizeJSON } = await loadDifCore();
|
|
265
|
+
return canonicalizeJSON(
|
|
266
|
+
buildProofJwsPayload(meta as Parameters<typeof buildProofJwsPayload>[0])
|
|
267
|
+
);
|
|
329
268
|
}
|
|
330
269
|
}
|