@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,81 @@
1
+ "use strict";
2
+ /**
3
+ * Request holder: the DID whose key a tools/call proves its caller holds.
4
+ *
5
+ * The proof is the call's request proof, `_meta["org.kya-os/request-proof"]`
6
+ * (SPEC-ENTITY-CARD §8, SPEC-MCP-EXTENSION §6), verified fail closed by
7
+ * `@kya-os/mcp/card`'s `requireProof`: its request hash covers the call's
8
+ * method and params without `_meta`, its audience is this server's DID, its
9
+ * nonce is spent once, and it is signed by the key the holder DID names. This
10
+ * is the check the Cloudflare adapter's request admission makes
11
+ * (mcp-i-cloudflare `security/mcp-holder-admission`). A did:key holder's key
12
+ * is resolved locally with no network; a did:web holder's keys are the ones
13
+ * its DID document lists for authentication (./holder-keys).
14
+ *
15
+ * A proof names its holder before anything verifies it, so the holder's
16
+ * document is read only for a proof its own claims do not already refuse
17
+ * (./claims-first-guard).
18
+ *
19
+ * A verified holder is identity only: it grants nothing until a delegation
20
+ * the call presents is verified for it.
21
+ *
22
+ * @module services/request-holder
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.REQUEST_PROOF_SKEW_SEC = void 0;
26
+ exports.resolveDidKeyHolder = resolveDidKeyHolder;
27
+ exports.createRequestHolderVerifier = createRequestHolderVerifier;
28
+ const dif_core_1 = require("../runtime/dif-core");
29
+ const claims_first_guard_1 = require("./claims-first-guard");
30
+ const holder_keys_1 = require("./holder-keys");
31
+ /** Seconds of clock skew a request proof's validity window is widened by. */
32
+ exports.REQUEST_PROOF_SKEW_SEC = 30;
33
+ /**
34
+ * The Ed25519 key a did:key holder names by its own key id, resolved with no
35
+ * network. Any other kid, or any other DID method, has no key here.
36
+ */
37
+ async function resolveDidKeyHolder(kid) {
38
+ const { didKeyFragment, extractPublicKeyFromDidKey, isEd25519DidKey, publicKeyToJwk, } = await (0, dif_core_1.loadDifCore)();
39
+ const did = kid.split("#")[0] ?? "";
40
+ const publicKey = isEd25519DidKey(did) && kid === `${did}#${didKeyFragment(did)}`
41
+ ? extractPublicKeyFromDidKey(did)
42
+ : null;
43
+ if (!publicKey) {
44
+ throw new Error("Only an Ed25519 did:key holder's own key is accepted");
45
+ }
46
+ return publicKeyToJwk(publicKey);
47
+ }
48
+ /**
49
+ * Build the verifier of the holder a tools/call proves. One verifier keeps
50
+ * one nonce cache, so build it once per server.
51
+ */
52
+ function createRequestHolderVerifier(options) {
53
+ let guard;
54
+ const holderKeys = (0, holder_keys_1.withDidWebHolders)({
55
+ resolveKey: resolveDidKeyHolder,
56
+ resolveDidKeys: async (did) => {
57
+ const { didKeyFragment } = await (0, dif_core_1.loadDifCore)();
58
+ return [await resolveDidKeyHolder(`${did}#${didKeyFragment(did)}`)];
59
+ },
60
+ }, options);
61
+ const guardFor = (card) => (guard ??= (0, claims_first_guard_1.claimsFirstGuard)(card.requireProof, {
62
+ expectedAudience: options.audience,
63
+ skewSec: exports.REQUEST_PROOF_SKEW_SEC,
64
+ ...(options.now ? { now: options.now } : {}),
65
+ resolveKey: holderKeys.resolveKey,
66
+ resolveDidKeys: holderKeys.resolveDidKeys,
67
+ consumeNonceIfFresh: options.consumeNonceIfFresh ?? new card.InMemoryNonceCache().consume,
68
+ }));
69
+ return async ({ method, params = {} }) => {
70
+ const { _meta, ...signed } = params;
71
+ const card = await (0, dif_core_1.loadDifCard)();
72
+ if (card.readCardProof(_meta) === undefined) {
73
+ return { ok: false, code: "holder_proof_required" };
74
+ }
75
+ const verdict = await guardFor(card)({ method, params: signed }, _meta);
76
+ return verdict.ok
77
+ ? { ok: true, did: verdict.did }
78
+ : { ok: false, code: verdict.error.code };
79
+ };
80
+ }
81
+ //# sourceMappingURL=request-holder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-holder.js","sourceRoot":"","sources":["../../src/services/request-holder.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,20 @@
1
+ // Flat config in the same shape as packages/mcp-i/eslint.config.js.
2
+ const { defineConfig } = require("eslint/config");
3
+ const typescriptPlugin = require("@typescript-eslint/eslint-plugin");
4
+ const typescriptParser = require("@typescript-eslint/parser");
5
+
6
+ module.exports = defineConfig([
7
+ {
8
+ files: ["src/**/*.ts"],
9
+ plugins: {
10
+ "@typescript-eslint": typescriptPlugin,
11
+ },
12
+ languageOptions: {
13
+ parser: typescriptParser,
14
+ },
15
+ rules: {
16
+ semi: "off",
17
+ },
18
+ },
19
+ { ignores: ["dist/", "node_modules/", "coverage/"] },
20
+ ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/mcp-i-runtime",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "description": "Shared product-runtime layer for the MCP-I framework (Node + Cloudflare adapters). Protocol types/values live in @kya-os/mcp (DIF).",
5
5
  "license": "MIT",
6
6
  "author": "Dylan Hobbs",
@@ -32,6 +32,10 @@
32
32
  "types": "./dist/runtime/ext-apps-constants.d.ts",
33
33
  "default": "./dist/runtime/ext-apps-constants.js"
34
34
  },
35
+ "./services/claims-first-guard": {
36
+ "types": "./dist/services/claims-first-guard.d.ts",
37
+ "default": "./dist/services/claims-first-guard.js"
38
+ },
35
39
  "./types/tool-protection": {
36
40
  "types": "./dist/types/tool-protection.d.ts",
37
41
  "default": "./dist/types/tool-protection.js"
@@ -61,7 +65,7 @@
61
65
  },
62
66
  "dependencies": {
63
67
  "@kya-os/contracts": "^1.13.1",
64
- "@kya-os/mcp": "1.20.0",
68
+ "@kya-os/mcp": "1.26.0",
65
69
  "jose": "^5.6.3",
66
70
  "json-canonicalize": "2.0.0",
67
71
  "zod": "^3.25.67"
@@ -77,6 +81,8 @@
77
81
  "devDependencies": {
78
82
  "@modelcontextprotocol/ext-apps": "^1.0.0",
79
83
  "@types/node": "^20.14.9",
84
+ "@typescript-eslint/eslint-plugin": "^8.19.1",
85
+ "@typescript-eslint/parser": "^8.19.1",
80
86
  "@vitest/coverage-v8": "^4.0.18",
81
87
  "eslint": "^9.26.0",
82
88
  "typescript": "^5.5.3",
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it, vi } from "vitest";
2
2
  import type { AuditTrailEventInput } from "@kya-os/mcp/audit";
3
+ import { markToolRefusal } from "@kya-os/contracts/config";
3
4
  import type { ProviderRuntimeConfig } from "../../config";
4
5
  import { MCPIRuntimeBase } from "../../runtime/base";
5
6
  import {
@@ -264,6 +265,113 @@ describe("canonical runtime audit lifecycle", () => {
264
265
  });
265
266
  });
266
267
 
268
+ describe("tool refusals in the audit ledger", () => {
269
+ async function terminalEventFor(
270
+ result: Record<string, unknown>
271
+ ): Promise<AuditTrailEventInput> {
272
+ const events: AuditTrailEventInput[] = [];
273
+ const runtime = runtimeWithAudit(async (event) => {
274
+ events.push(event);
275
+ return pendingResult(event, String(events.length));
276
+ });
277
+ await runtime.processToolCall("place_order", {}, async () => result, {
278
+ id: "session",
279
+ nonce: "nonce",
280
+ audience: "client",
281
+ });
282
+ expect(events).toHaveLength(2);
283
+ expect(events[0]!.eventType).toBe("tool.call.started");
284
+ return events[1]!;
285
+ }
286
+
287
+ it.each(["SPEND_CAP_EXCEEDED", "PRODUCT_OUT_OF_SCOPE"])(
288
+ "records a marked %s refusal as tool.call.denied with its code",
289
+ async (code) => {
290
+ const terminal = await terminalEventFor({
291
+ isError: true,
292
+ content: [
293
+ { type: "text", text: "Order refused. Nothing was ordered." },
294
+ ],
295
+ _meta: { ...markToolRefusal(code) },
296
+ });
297
+
298
+ expect(terminal).toMatchObject({
299
+ eventType: "tool.call.denied",
300
+ outcome: "denied",
301
+ reason: { code },
302
+ details: { phase: "denied" },
303
+ });
304
+ expect(JSON.stringify(terminal)).not.toContain("Nothing was ordered");
305
+ }
306
+ );
307
+
308
+ it("records a marked refusal as denied even without isError, like Checkpoint and activity do", async () => {
309
+ const terminal = await terminalEventFor({
310
+ content: [{ type: "text", text: "Refused." }],
311
+ _meta: { ...markToolRefusal("SPEND_CAP_EXCEEDED") },
312
+ });
313
+
314
+ expect(terminal).toMatchObject({
315
+ eventType: "tool.call.denied",
316
+ reason: { code: "SPEND_CAP_EXCEEDED" },
317
+ });
318
+ });
319
+
320
+ it("keeps an inline consent challenge challenged even when it also carries a marker", async () => {
321
+ const terminal = await terminalEventFor({
322
+ structuredContent: { type: "consent_required" },
323
+ _meta: { ...markToolRefusal("SPEND_CAP_EXCEEDED") },
324
+ });
325
+
326
+ expect(terminal).toMatchObject({
327
+ eventType: "tool.call.challenged",
328
+ outcome: "challenged",
329
+ reason: { code: "AUTHORIZATION_REQUIRED" },
330
+ });
331
+ });
332
+
333
+ it("keeps an unmarked isError result a failed tool error, even when its text looks like a code", async () => {
334
+ const terminal = await terminalEventFor({
335
+ isError: true,
336
+ content: [{ type: "text", text: "SPEND_CAP_EXCEEDED" }],
337
+ structuredContent: { ok: false, code: "SPEND_CAP_EXCEEDED" },
338
+ });
339
+
340
+ expect(terminal).toMatchObject({
341
+ eventType: "tool.call.failed",
342
+ outcome: "failed",
343
+ reason: { code: "HANDLER_ERROR_RESULT" },
344
+ });
345
+ });
346
+
347
+ it("keeps a malformed marker a failed tool error", async () => {
348
+ const terminal = await terminalEventFor({
349
+ isError: true,
350
+ content: [],
351
+ _meta: {
352
+ "ai.kya-os/refusal": { code: "over the cap: alice@example.com" },
353
+ },
354
+ });
355
+
356
+ expect(terminal).toMatchObject({
357
+ eventType: "tool.call.failed",
358
+ reason: { code: "HANDLER_ERROR_RESULT" },
359
+ });
360
+ expect(JSON.stringify(terminal)).not.toContain("alice@example.com");
361
+ });
362
+
363
+ it("keeps an allowed order completed", async () => {
364
+ const terminal = await terminalEventFor({
365
+ content: [{ type: "text", text: "Order placed." }],
366
+ });
367
+
368
+ expect(terminal).toMatchObject({
369
+ eventType: "tool.call.completed",
370
+ outcome: "succeeded",
371
+ });
372
+ });
373
+ });
374
+
267
375
  describe("verifier denials in the audit ledger", () => {
268
376
  async function protectedRuntimeWithAudit(
269
377
  record: (event: AuditTrailEventInput) => Promise<unknown>,
@@ -0,0 +1,155 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import {
3
+ MemoryResumeTokenStore,
4
+ verifyOrHints,
5
+ type AuthHandshakeConfig,
6
+ } from "../handshake";
7
+ import type { DelegationVerifier } from "../types";
8
+
9
+ const HOLDER = "did:key:z6MkHolder";
10
+ const SCOPES = ["files:read"];
11
+
12
+ function configWith(verifier: DelegationVerifier): AuthHandshakeConfig {
13
+ return {
14
+ delegationVerifier: verifier,
15
+ resumeTokenStore: new MemoryResumeTokenStore(),
16
+ bouncer: { authorizationUrl: "https://consent.example/consent" },
17
+ };
18
+ }
19
+
20
+ const credential = {
21
+ agent_did: HOLDER,
22
+ user_did: "did:web:user.example",
23
+ scopes: SCOPES,
24
+ authorization: { type: "none" as const },
25
+ };
26
+
27
+ describe("verifyOrHints on a presented delegation", () => {
28
+ it("asks for authorization when the call presents none, and looks nothing up", async () => {
29
+ const verifier = {
30
+ verify: vi.fn(),
31
+ verifyPresented: vi.fn(),
32
+ };
33
+
34
+ const result = await verifyOrHints(
35
+ HOLDER,
36
+ SCOPES,
37
+ configWith(verifier),
38
+ undefined,
39
+ { presented: {} }
40
+ );
41
+
42
+ expect(result.authorized).toBe(false);
43
+ expect(result.reason).toBe("No delegation presented");
44
+ expect(result.authError?.authorizationUrl).toContain(
45
+ encodeURIComponent(HOLDER)
46
+ );
47
+ expect(verifier.verify).not.toHaveBeenCalled();
48
+ expect(verifier.verifyPresented).not.toHaveBeenCalled();
49
+ });
50
+
51
+ it("refuses when the verifier cannot check a presented credential", async () => {
52
+ const verifier = { verify: vi.fn() };
53
+
54
+ const result = await verifyOrHints(
55
+ HOLDER,
56
+ SCOPES,
57
+ configWith(verifier),
58
+ undefined,
59
+ { presented: { credential: "a.b.c" } }
60
+ );
61
+
62
+ expect(result.authorized).toBe(false);
63
+ expect(result.reason).toMatch(/cannot verify a presented delegation/);
64
+ expect(verifier.verify).not.toHaveBeenCalled();
65
+ });
66
+
67
+ it("hands the credential and the proven holder to verifyPresented", async () => {
68
+ const verifier = {
69
+ verify: vi.fn(),
70
+ verifyPresented: vi.fn().mockResolvedValue({ valid: true, credential }),
71
+ };
72
+
73
+ const result = await verifyOrHints(
74
+ HOLDER,
75
+ SCOPES,
76
+ configWith(verifier),
77
+ undefined,
78
+ { presented: { credential: "a.b.c" } }
79
+ );
80
+
81
+ expect(verifier.verifyPresented).toHaveBeenCalledWith(
82
+ "a.b.c",
83
+ HOLDER,
84
+ SCOPES
85
+ );
86
+ // A credential-only decision is authority on the presented path.
87
+ expect(result.authorized).toBe(true);
88
+ expect(result.credential).toBe(credential);
89
+ expect(verifier.verify).not.toHaveBeenCalled();
90
+ });
91
+
92
+ it("refuses a presented credential the verifier rejects", async () => {
93
+ const verifier = {
94
+ verify: vi.fn(),
95
+ verifyPresented: vi
96
+ .fn()
97
+ .mockResolvedValue({ valid: false, reason: "Not this holder's" }),
98
+ };
99
+
100
+ const result = await verifyOrHints(
101
+ HOLDER,
102
+ SCOPES,
103
+ configWith(verifier),
104
+ undefined,
105
+ { presented: { credential: "a.b.c" } }
106
+ );
107
+
108
+ expect(result.authorized).toBe(false);
109
+ expect(result.reason).toBe("Not this holder's");
110
+ });
111
+
112
+ it("still needs a stored record when it looks one up for the agent", async () => {
113
+ const verifier = {
114
+ verify: vi.fn().mockResolvedValue({ valid: true, credential }),
115
+ };
116
+
117
+ const result = await verifyOrHints(HOLDER, SCOPES, configWith(verifier));
118
+
119
+ expect(result.authorized).toBe(false);
120
+ });
121
+ });
122
+
123
+ describe("verifyOrHints without a presented delegation", () => {
124
+ it("warns once that it authorizes on a DID the caller only names", async () => {
125
+ // The warning is said once per process, so this reads a module of its own.
126
+ vi.resetModules();
127
+ const fresh = await import("../handshake");
128
+ const { logger } = await import("../../logging");
129
+ const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
130
+ const verifier = {
131
+ verify: vi.fn().mockResolvedValue({ valid: true, credential }),
132
+ verifyPresented: vi.fn().mockResolvedValue({ valid: true, credential }),
133
+ };
134
+ const config = {
135
+ ...configWith(verifier),
136
+ resumeTokenStore: new fresh.MemoryResumeTokenStore(),
137
+ };
138
+ const lookups = () =>
139
+ warn.mock.calls.filter(([message]) =>
140
+ String(message).includes("options.presented")
141
+ );
142
+
143
+ await fresh.verifyOrHints(HOLDER, SCOPES, config, undefined, {
144
+ presented: { credential: "a.b.c" },
145
+ });
146
+ expect(lookups()).toHaveLength(0);
147
+
148
+ await fresh.verifyOrHints(HOLDER, SCOPES, config);
149
+ await fresh.verifyOrHints(HOLDER, SCOPES, config);
150
+
151
+ expect(verifier.verify).toHaveBeenCalledTimes(2);
152
+ expect(lookups()).toHaveLength(1);
153
+ warn.mockRestore();
154
+ });
155
+ });
@@ -23,8 +23,14 @@ import {
23
23
  import { DelegationRecord } from "@kya-os/contracts/delegation";
24
24
  import { logger } from "../logging";
25
25
  import { DelegationVerifier, VerifyDelegationResult } from "./types";
26
+ import type { ResumeTokenStore } from "./resume-token";
26
27
 
27
28
  export type { DelegationVerifier, VerifyDelegationResult };
29
+ export {
30
+ generateResumeToken,
31
+ MemoryResumeTokenStore,
32
+ type ResumeTokenStore,
33
+ } from "./resume-token";
28
34
 
29
35
  /**
30
36
  * Agent reputation data from KTA
@@ -95,147 +101,57 @@ export interface VerifyOrHintsResult {
95
101
  authError?: NeedsAuthorizationError;
96
102
  reputation?: AgentReputation;
97
103
  reason?: string;
104
+ /** The code the delegation verifier refused with, when it names one. */
105
+ code?: string;
98
106
  }
99
107
 
100
108
  /**
101
- * Resume token store interface
109
+ * Options for {@link verifyOrHints}.
102
110
  */
103
- export interface ResumeTokenStore {
104
- create(
105
- agentDid: string,
106
- scopes: string[],
107
- metadata?: Record<string, unknown>
108
- ): Promise<string>;
109
-
110
- get(token: string): Promise<{
111
- agentDid: string;
112
- scopes: string[];
113
- createdAt: number;
114
- expiresAt: number;
115
- metadata?: Record<string, unknown>;
116
- } | null>;
117
-
118
- fulfill(token: string): Promise<void>;
119
- }
120
-
121
- /**
122
- * Mint a capability-bearing resume token with CSPRNG entropy.
123
- *
124
- * Format: `${prefix}_${hex(16 random bytes)}` (128 bits). Uses Web Crypto
125
- * `getRandomValues` (Node 18+, Cloudflare Workers, browsers), falling back to
126
- * `randomUUID` — both CSPRNG. Replaces the prior `Date.now()_Math.random()`
127
- * form, which leaked creation time and had weak uniqueness/guessability for a
128
- * token that grants delegated access. No Node-specific imports (Buffer-free),
129
- * so it stays safe on every fetch-capable runtime.
130
- */
131
- export function generateResumeToken(prefix = "rt"): string {
132
- if (typeof crypto !== "undefined" && crypto.getRandomValues) {
133
- const bytes = new Uint8Array(16);
134
- crypto.getRandomValues(bytes);
135
- let hex = "";
136
- for (let i = 0; i < bytes.length; i++) {
137
- hex += bytes[i].toString(16).padStart(2, "0");
138
- }
139
- return `${prefix}_${hex}`;
140
- }
141
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
142
- return `${prefix}_${crypto.randomUUID().replace(/-/g, "")}`;
143
- }
144
- throw new Error("CSPRNG unavailable: cannot mint resume token");
111
+ export interface VerifyOrHintsOptions {
112
+ /**
113
+ * Authorize on a presented delegation only. `agentDid` is then the holder
114
+ * the call proved it holds the key of, never a DID the caller merely
115
+ * named, and `credential` the delegation credential the call presents
116
+ * (absent when it presents none, which asks for authorization). The
117
+ * verifier's `verifyPresented` decides; nothing is looked up for the agent.
118
+ */
119
+ presented?: { credential?: string };
145
120
  }
146
121
 
147
- /**
148
- * Simple in-memory resume token store (for testing/development).
149
- * Not suitable for multi-instance deployments.
150
- */
151
- export class MemoryResumeTokenStore implements ResumeTokenStore {
152
- private tokens = new Map<
153
- string,
154
- {
155
- agentDid: string;
156
- scopes: string[];
157
- createdAt: number;
158
- expiresAt: number;
159
- metadata?: Record<string, unknown>;
160
- fulfilled: boolean;
161
- }
162
- >();
163
- private ttl: number;
164
-
165
- constructor(ttlMs = 600_000) {
166
- this.ttl = ttlMs;
167
- }
168
-
169
- async create(
170
- agentDid: string,
171
- scopes: string[],
172
- metadata?: Record<string, unknown>
173
- ): Promise<string> {
174
- const token = generateResumeToken("rt");
175
- const now = Date.now();
176
-
177
- this.tokens.set(token, {
178
- agentDid,
179
- scopes,
180
- createdAt: now,
181
- expiresAt: now + this.ttl,
182
- metadata,
183
- fulfilled: false,
184
- });
185
-
186
- return token;
187
- }
188
-
189
- async get(token: string): Promise<{
190
- agentDid: string;
191
- scopes: string[];
192
- createdAt: number;
193
- expiresAt: number;
194
- metadata?: Record<string, unknown>;
195
- } | null> {
196
- const data = this.tokens.get(token);
197
- if (!data) return null;
198
-
199
- if (Date.now() > data.expiresAt) {
200
- this.tokens.delete(token);
201
- return null;
202
- }
203
-
204
- if (data.fulfilled) return null;
205
-
206
- return {
207
- agentDid: data.agentDid,
208
- scopes: data.scopes,
209
- createdAt: data.createdAt,
210
- expiresAt: data.expiresAt,
211
- metadata: data.metadata,
212
- };
213
- }
214
-
215
- async fulfill(token: string): Promise<void> {
216
- const data = this.tokens.get(token);
217
- if (data) {
218
- data.fulfilled = true;
219
- }
220
- }
221
-
222
- clear(): void {
223
- this.tokens.clear();
224
- }
122
+ let warnedOfNamedDid = false;
123
+
124
+ /** Say once that a delegation is being looked up for a DID nothing proved here. */
125
+ function warnOfNamedDid(): void {
126
+ if (warnedOfNamedDid) return;
127
+ warnedOfNamedDid = true;
128
+ logger.warn(
129
+ "[AuthHandshake] verifyOrHints was called without options.presented, so it authorizes on a " +
130
+ "delegation looked up for the DID it was given, which nothing here proved. Pass the " +
131
+ "holder a call's request proof shows as agentDid and the delegation the call presents as " +
132
+ "options.presented."
133
+ );
225
134
  }
226
135
 
227
136
  /**
228
137
  * Main auth handshake function.
229
138
  *
230
- * Verifies agent authorization or returns authorization hints.
139
+ * Verifies agent authorization or returns authorization hints. With
140
+ * `options.presented` it authorizes only on the delegation a call presents,
141
+ * for the holder the call proved, which is how every protected call is
142
+ * checked. Without it, it looks a delegation up for `agentDid`: the caller
143
+ * must have established that DID itself, a DID a client only names
144
+ * authorizes whoever names it, and the first such call logs a warning.
231
145
  */
232
146
  export async function verifyOrHints(
233
147
  agentDid: string,
234
148
  scopes: string[],
235
149
  config: AuthHandshakeConfig,
236
- _resumeToken?: string
150
+ _resumeToken?: string,
151
+ options: VerifyOrHintsOptions = {}
237
152
  ): Promise<VerifyOrHintsResult> {
238
153
  const startTime = Date.now();
154
+ if (!options.presented) warnOfNamedDid();
239
155
 
240
156
  if (config.debug) {
241
157
  logger.debug(
@@ -281,7 +197,14 @@ export async function verifyOrHints(
281
197
  let delegationResult: VerifyDelegationResult;
282
198
 
283
199
  try {
284
- delegationResult = await config.delegationVerifier.verify(agentDid, scopes);
200
+ delegationResult = options.presented
201
+ ? await verifyPresentedDelegation(
202
+ config.delegationVerifier,
203
+ options.presented.credential,
204
+ agentDid,
205
+ scopes
206
+ )
207
+ : await config.delegationVerifier.verify(agentDid, scopes);
285
208
  } catch (error) {
286
209
  logger.error("[AuthHandshake] Delegation verification failed:", error);
287
210
  const errorMessage = `Delegation verification error: ${error instanceof Error ? error.message : "Unknown error"}`;
@@ -300,7 +223,15 @@ export async function verifyOrHints(
300
223
  };
301
224
  }
302
225
 
303
- if (delegationResult.valid && delegationResult.delegation) {
226
+ // A presented credential the verifier accepted is authority even when no
227
+ // stored record stands behind it (a credential-only decision).
228
+ const accepted =
229
+ delegationResult.valid &&
230
+ (delegationResult.delegation !== undefined ||
231
+ (options.presented !== undefined &&
232
+ delegationResult.credential !== undefined));
233
+
234
+ if (accepted) {
304
235
  if (config.debug) {
305
236
  logger.debug(
306
237
  `[AuthHandshake] Delegation valid, authorized (${Date.now() - startTime}ms)`
@@ -334,9 +265,33 @@ export async function verifyOrHints(
334
265
  authError,
335
266
  reputation,
336
267
  reason: delegationResult.reason ?? "No delegation",
268
+ ...(delegationResult.code ? { code: delegationResult.code } : {}),
337
269
  };
338
270
  }
339
271
 
272
+ /**
273
+ * Verify the delegation a call presents, for the holder it proved. Refused,
274
+ * never looked up, when the call presents none or the verifier cannot check
275
+ * a presented credential.
276
+ */
277
+ async function verifyPresentedDelegation(
278
+ verifier: DelegationVerifier,
279
+ credential: string | undefined,
280
+ holderDid: string,
281
+ scopes: string[]
282
+ ): Promise<VerifyDelegationResult> {
283
+ if (!credential) {
284
+ return { valid: false, reason: "No delegation presented" };
285
+ }
286
+ if (!verifier.verifyPresented) {
287
+ return {
288
+ valid: false,
289
+ reason: "The delegation verifier cannot verify a presented delegation",
290
+ };
291
+ }
292
+ return verifier.verifyPresented(credential, holderDid, scopes);
293
+ }
294
+
340
295
  /**
341
296
  * Fetch agent reputation from KTA.
342
297
  */
package/src/auth/index.ts CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  MemoryResumeTokenStore,
8
8
  generateResumeToken,
9
9
  type AuthHandshakeConfig,
10
+ type VerifyOrHintsOptions,
10
11
  type VerifyOrHintsResult,
11
12
  type AgentReputation,
12
13
  type ResumeTokenStore,