@kya-os/mcp-i-runtime 1.3.2 → 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.
Files changed (79) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/handshake.d.ts +23 -43
  3. package/dist/auth/handshake.d.ts.map +1 -1
  4. package/dist/auth/handshake.js +51 -82
  5. package/dist/auth/handshake.js.map +1 -1
  6. package/dist/auth/index.d.ts +1 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js.map +1 -1
  9. package/dist/auth/resume-token.d.ts +52 -0
  10. package/dist/auth/resume-token.d.ts.map +1 -0
  11. package/dist/auth/resume-token.js +89 -0
  12. package/dist/auth/resume-token.js.map +1 -0
  13. package/dist/auth/types.d.ts +15 -0
  14. package/dist/auth/types.d.ts.map +1 -1
  15. package/dist/index.d.ts +5 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +14 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/proof/companion.d.ts +25 -0
  20. package/dist/proof/companion.d.ts.map +1 -0
  21. package/dist/proof/companion.js +14 -0
  22. package/dist/proof/companion.js.map +1 -0
  23. package/dist/proof/generator.d.ts +16 -5
  24. package/dist/proof/generator.d.ts.map +1 -1
  25. package/dist/proof/generator.js +13 -3
  26. package/dist/proof/generator.js.map +1 -1
  27. package/dist/proof/index.d.ts +2 -1
  28. package/dist/proof/index.d.ts.map +1 -1
  29. package/dist/proof/index.js +3 -1
  30. package/dist/proof/index.js.map +1 -1
  31. package/dist/runtime/audit.d.ts.map +1 -1
  32. package/dist/runtime/audit.js +12 -0
  33. package/dist/runtime/audit.js.map +1 -1
  34. package/dist/runtime/dif-core.d.ts +8 -0
  35. package/dist/runtime/dif-core.d.ts.map +1 -1
  36. package/dist/runtime/dif-core.js +10 -0
  37. package/dist/runtime/dif-core.js.map +1 -1
  38. package/dist/services/claims-first-guard.d.ts +33 -0
  39. package/dist/services/claims-first-guard.d.ts.map +1 -0
  40. package/dist/services/claims-first-guard.js +77 -0
  41. package/dist/services/claims-first-guard.js.map +1 -0
  42. package/dist/services/holder-keys.d.ts +95 -0
  43. package/dist/services/holder-keys.d.ts.map +1 -0
  44. package/dist/services/holder-keys.js +281 -0
  45. package/dist/services/holder-keys.js.map +1 -0
  46. package/dist/services/holder-read-slots.d.ts +42 -0
  47. package/dist/services/holder-read-slots.d.ts.map +1 -0
  48. package/dist/services/holder-read-slots.js +82 -0
  49. package/dist/services/holder-read-slots.js.map +1 -0
  50. package/dist/services/request-holder.d.ts +78 -0
  51. package/dist/services/request-holder.d.ts.map +1 -0
  52. package/dist/services/request-holder.js +81 -0
  53. package/dist/services/request-holder.js.map +1 -0
  54. package/eslint.config.js +20 -0
  55. package/package.json +8 -2
  56. package/src/__tests__/runtime/audit.test.ts +108 -0
  57. package/src/auth/__tests__/verify-or-hints-presented.test.ts +155 -0
  58. package/src/auth/handshake.ts +80 -125
  59. package/src/auth/index.ts +1 -0
  60. package/src/auth/resume-token.ts +134 -0
  61. package/src/auth/types.ts +20 -2
  62. package/src/index.ts +25 -0
  63. package/src/proof/__tests__/proof-generator.test.ts +48 -4
  64. package/src/proof/companion.ts +35 -0
  65. package/src/proof/generator.ts +35 -8
  66. package/src/proof/index.ts +3 -0
  67. package/src/runtime/audit.ts +15 -3
  68. package/src/runtime/dif-core.ts +16 -0
  69. package/src/services/__tests__/claims-first-guard.test.ts +93 -0
  70. package/src/services/__tests__/holder-fixtures.ts +135 -0
  71. package/src/services/__tests__/holder-keys.test.ts +257 -0
  72. package/src/services/__tests__/holder-read-slots.test.ts +117 -0
  73. package/src/services/__tests__/holder-reads.test.ts +284 -0
  74. package/src/services/__tests__/proof-verifier.test.ts +8 -5
  75. package/src/services/__tests__/request-holder.test.ts +210 -0
  76. package/src/services/claims-first-guard.ts +89 -0
  77. package/src/services/holder-keys.ts +379 -0
  78. package/src/services/holder-read-slots.ts +85 -0
  79. package/src/services/request-holder.ts +146 -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
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Request holder: the DID whose key a tools/call proves its caller holds.
3
+ *
4
+ * The proof is the call's request proof, `_meta["org.kya-os/request-proof"]`
5
+ * (SPEC-ENTITY-CARD §8, SPEC-MCP-EXTENSION §6), verified fail closed by
6
+ * `@kya-os/mcp/card`'s `requireProof`: its request hash covers the call's
7
+ * method and params without `_meta`, its audience is this server's DID, its
8
+ * nonce is spent once, and it is signed by the key the holder DID names. This
9
+ * is the check the Cloudflare adapter's request admission makes
10
+ * (mcp-i-cloudflare `security/mcp-holder-admission`). A did:key holder's key
11
+ * is resolved locally with no network; a did:web holder's keys are the ones
12
+ * its DID document lists for authentication (./holder-keys).
13
+ *
14
+ * A proof names its holder before anything verifies it, so the holder's
15
+ * document is read only for a proof its own claims do not already refuse
16
+ * (./claims-first-guard).
17
+ *
18
+ * A verified holder is identity only: it grants nothing until a delegation
19
+ * the call presents is verified for it.
20
+ *
21
+ * @module services/request-holder
22
+ */
23
+
24
+ import { loadDifCard, loadDifCore, type DifCard } from "../runtime/dif-core";
25
+ import { claimsFirstGuard } from "./claims-first-guard";
26
+ import {
27
+ withDidWebHolders,
28
+ type DidWebHolderOptions,
29
+ type ProofPublicJwk,
30
+ } from "./holder-keys";
31
+
32
+ type VerifyProofDeps = Parameters<DifCard["requireProof"]>[0];
33
+ type ProofGateCode = Extract<
34
+ Awaited<ReturnType<ReturnType<DifCard["requireProof"]>>>,
35
+ { ok: false }
36
+ >["error"]["code"];
37
+
38
+ /** Seconds of clock skew a request proof's validity window is widened by. */
39
+ export const REQUEST_PROOF_SKEW_SEC = 30;
40
+
41
+ /** Why a call proved no holder: it carried no request proof, or a bad one. */
42
+ export type RequestHolderRefusal = "holder_proof_required" | ProofGateCode;
43
+
44
+ /** The holder a call proved, or why it proved none. */
45
+ export type RequestHolderResult =
46
+ | { ok: true; did: string }
47
+ | { ok: false; code: RequestHolderRefusal };
48
+
49
+ /** How a server checks its calls' request proofs, beside their audience. */
50
+ export interface RequestProofOptions extends DidWebHolderOptions {
51
+ /**
52
+ * The atomic test-and-set that spends a proof's nonce:
53
+ * `(nonce, did, minTtlSec) => Promise<boolean>`, true when the nonce was
54
+ * fresh. Default: one in-memory cache per verifier, so one per process. A
55
+ * proof lives at most 60 seconds and is accepted within 30 seconds of
56
+ * clock skew, so behind several instances that each keep their own cache,
57
+ * a captured proof is accepted once by each, for up to 90 seconds after
58
+ * it was signed. Share one store across the instances that serve one
59
+ * server DID, as the Cloudflare adapter shares a Durable Object.
60
+ */
61
+ consumeNonceIfFresh?: VerifyProofDeps["consumeNonceIfFresh"];
62
+ }
63
+
64
+ export interface RequestHolderOptions extends RequestProofOptions {
65
+ /** This server's DID: a proof addressed to any other is refused. */
66
+ audience: string;
67
+ /** Clock in epoch milliseconds, for tests. */
68
+ now?: () => number;
69
+ }
70
+
71
+ /** A tools/call as received: its method and params, `_meta` included. */
72
+ export interface HolderRequest {
73
+ method: string;
74
+ params?: Record<string, unknown>;
75
+ }
76
+
77
+ export type RequestHolderVerifier = (
78
+ request: HolderRequest
79
+ ) => Promise<RequestHolderResult>;
80
+
81
+ /**
82
+ * The Ed25519 key a did:key holder names by its own key id, resolved with no
83
+ * network. Any other kid, or any other DID method, has no key here.
84
+ */
85
+ export async function resolveDidKeyHolder(
86
+ kid: string
87
+ ): Promise<ProofPublicJwk> {
88
+ const {
89
+ didKeyFragment,
90
+ extractPublicKeyFromDidKey,
91
+ isEd25519DidKey,
92
+ publicKeyToJwk,
93
+ } = await loadDifCore();
94
+ const did = kid.split("#")[0] ?? "";
95
+ const publicKey =
96
+ isEd25519DidKey(did) && kid === `${did}#${didKeyFragment(did)}`
97
+ ? extractPublicKeyFromDidKey(did)
98
+ : null;
99
+ if (!publicKey) {
100
+ throw new Error("Only an Ed25519 did:key holder's own key is accepted");
101
+ }
102
+ return publicKeyToJwk(publicKey) as ProofPublicJwk;
103
+ }
104
+
105
+ /**
106
+ * Build the verifier of the holder a tools/call proves. One verifier keeps
107
+ * one nonce cache, so build it once per server.
108
+ */
109
+ export function createRequestHolderVerifier(
110
+ options: RequestHolderOptions
111
+ ): RequestHolderVerifier {
112
+ let guard: ReturnType<DifCard["requireProof"]> | undefined;
113
+ const holderKeys = withDidWebHolders(
114
+ {
115
+ resolveKey: resolveDidKeyHolder,
116
+ resolveDidKeys: async (did) => {
117
+ const { didKeyFragment } = await loadDifCore();
118
+ return [await resolveDidKeyHolder(`${did}#${didKeyFragment(did)}`)];
119
+ },
120
+ },
121
+ options
122
+ );
123
+
124
+ const guardFor = (card: DifCard) =>
125
+ (guard ??= claimsFirstGuard(card.requireProof, {
126
+ expectedAudience: options.audience,
127
+ skewSec: REQUEST_PROOF_SKEW_SEC,
128
+ ...(options.now ? { now: options.now } : {}),
129
+ resolveKey: holderKeys.resolveKey,
130
+ resolveDidKeys: holderKeys.resolveDidKeys,
131
+ consumeNonceIfFresh:
132
+ options.consumeNonceIfFresh ?? new card.InMemoryNonceCache().consume,
133
+ }));
134
+
135
+ return async ({ method, params = {} }) => {
136
+ const { _meta, ...signed } = params;
137
+ const card = await loadDifCard();
138
+ if (card.readCardProof(_meta) === undefined) {
139
+ return { ok: false, code: "holder_proof_required" };
140
+ }
141
+ const verdict = await guardFor(card)({ method, params: signed }, _meta);
142
+ return verdict.ok
143
+ ? { ok: true, did: verdict.did }
144
+ : { ok: false, code: verdict.error.code };
145
+ };
146
+ }