@kya-os/mcp-i-runtime 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/config.d.ts +5 -7
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js +4 -6
  5. package/dist/config.js.map +1 -1
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +20 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/runtime/audit-logger.d.ts +6 -28
  11. package/dist/runtime/audit-logger.d.ts.map +1 -1
  12. package/dist/runtime/audit-logger.js +5 -3
  13. package/dist/runtime/audit-logger.js.map +1 -1
  14. package/dist/runtime/audit.d.ts +132 -0
  15. package/dist/runtime/audit.d.ts.map +1 -0
  16. package/dist/runtime/audit.js +424 -0
  17. package/dist/runtime/audit.js.map +1 -0
  18. package/dist/runtime/base.d.ts +9 -48
  19. package/dist/runtime/base.d.ts.map +1 -1
  20. package/dist/runtime/base.js +109 -89
  21. package/dist/runtime/base.js.map +1 -1
  22. package/dist/services/auth-type-satisfies.d.ts +93 -0
  23. package/dist/services/auth-type-satisfies.d.ts.map +1 -0
  24. package/dist/services/auth-type-satisfies.js +127 -0
  25. package/dist/services/auth-type-satisfies.js.map +1 -0
  26. package/dist/services/oauth-config.service.d.ts.map +1 -1
  27. package/dist/services/oauth-config.service.js +29 -0
  28. package/dist/services/oauth-config.service.js.map +1 -1
  29. package/dist/services/tool-context-builder.d.ts +6 -1
  30. package/dist/services/tool-context-builder.d.ts.map +1 -1
  31. package/dist/services/tool-context-builder.js +35 -3
  32. package/dist/services/tool-context-builder.js.map +1 -1
  33. package/package.json +7 -3
  34. package/src/__tests__/config/provider-runtime-config.test.ts +2 -9
  35. package/src/__tests__/config.test.ts +12 -11
  36. package/src/__tests__/integration/full-flow.test.ts +0 -5
  37. package/src/__tests__/integration.test.ts +2 -6
  38. package/src/__tests__/runtime/audit.test.ts +327 -0
  39. package/src/__tests__/runtime/base-extensions.test.ts +0 -46
  40. package/src/__tests__/runtime/base.test.ts +71 -102
  41. package/src/__tests__/runtime/delegation-flow.test.ts +0 -4
  42. package/src/__tests__/runtime/process-tool-call-security.test.ts +5 -11
  43. package/src/__tests__/runtime/proof-client-did.test.ts +0 -4
  44. package/src/__tests__/runtime/provider-selection.test.ts +0 -2
  45. package/src/__tests__/runtime/route-interception.test.ts +7 -4
  46. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +23 -31
  47. package/src/__tests__/services/tool-protection-merged-config.test.ts +0 -40
  48. package/src/config/__tests__/merged-config.spec.ts +0 -26
  49. package/src/config.ts +9 -10
  50. package/src/index.ts +32 -2
  51. package/src/runtime/__tests__/audit-logger-compat.test.ts +15 -0
  52. package/src/runtime/audit-logger.ts +6 -29
  53. package/src/runtime/audit.ts +598 -0
  54. package/src/runtime/base.ts +154 -99
  55. package/src/services/__tests__/auth-type-satisfies.test.ts +232 -0
  56. package/src/services/__tests__/oauth-config.service.test.ts +66 -0
  57. package/src/services/__tests__/proof-verifier.integration.test.ts +1 -1
  58. package/src/services/__tests__/proof-verifier.test.ts +6 -3
  59. package/src/services/__tests__/tool-context-builder-authtype.test.ts +167 -0
  60. package/src/services/auth-type-satisfies.ts +134 -0
  61. package/src/services/oauth-config.service.ts +44 -1
  62. package/src/services/tool-context-builder.ts +64 -18
  63. package/src/__tests__/runtime/audit-logger.test.ts +0 -154
@@ -170,6 +170,72 @@ describe("OAuthConfigService", () => {
170
170
  expect(result.configuredProvider).toBe("github");
171
171
  });
172
172
 
173
+ it("maps provider metadata.clientSecretName (registry-model secret reference)", async () => {
174
+ // Regression: the parser previously dropped `metadata`, so
175
+ // OAuthService.resolveClientSecret could not resolve a confidential
176
+ // provider's secret from secure storage (it keys off
177
+ // `metadata.clientSecretName`). It then fell back to the inline
178
+ // `clientSecret` — which the AgentShield /providers response
179
+ // intentionally OMITS — so the worker sent an empty secret and the
180
+ // OAuth token exchange failed with "client_id and/or client_secret
181
+ // incorrect".
182
+ const apiResponse = {
183
+ success: true,
184
+ data: {
185
+ providers: {
186
+ github: {
187
+ clientId: "gh-id",
188
+ // clientSecret intentionally omitted by the /providers route
189
+ authorizationUrl: "https://github.com/login/oauth/authorize",
190
+ tokenUrl: "https://github.com/login/oauth/access_token",
191
+ scopes: [],
192
+ metadata: {
193
+ clientSecretName: "KYA_PROD_ACME_ABCD1234_GITHUB_CLIENT_SECRET",
194
+ clientSecretVersion: 3,
195
+ },
196
+ },
197
+ // snake_case metadata must be normalized to camelCase
198
+ google: {
199
+ client_id: "g-id",
200
+ authorization_url: "https://accounts.google.com/o/oauth2/v2/auth",
201
+ token_url: "https://oauth2.googleapis.com/token",
202
+ metadata: {
203
+ client_secret_name: "KYA_PROD_ACME_ABCD1234_GOOGLE_CLIENT_SECRET",
204
+ },
205
+ },
206
+ },
207
+ configuredProvider: "github",
208
+ },
209
+ };
210
+ (mockFetchProvider.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
211
+ ok: true,
212
+ status: 200,
213
+ json: async () => apiResponse,
214
+ });
215
+
216
+ const service = new OAuthConfigService({
217
+ baseUrl: "https://api.example.com",
218
+ apiKey: "test-api-key",
219
+ fetchProvider: mockFetchProvider,
220
+ cache: mockCache,
221
+ });
222
+
223
+ const result = await service.getOAuthConfig("proj-123");
224
+
225
+ // The secret NAME reference must survive parsing so resolveClientSecret
226
+ // can resolve the actual secret from secure storage (worker env binding).
227
+ expect(result.providers.github.metadata?.clientSecretName).toBe(
228
+ "KYA_PROD_ACME_ABCD1234_GITHUB_CLIENT_SECRET"
229
+ );
230
+ expect(result.providers.github.metadata?.clientSecretVersion).toBe(3);
231
+ // clientSecret stays null (API omits it): resolution must come via metadata.
232
+ expect(result.providers.github.clientSecret).toBeNull();
233
+ // snake_case metadata is normalized to camelCase.
234
+ expect(result.providers.google.metadata?.clientSecretName).toBe(
235
+ "KYA_PROD_ACME_ABCD1234_GOOGLE_CLIENT_SECRET"
236
+ );
237
+ });
238
+
173
239
  it("should cache fetched config", async () => {
174
240
  const service = new OAuthConfigService({
175
241
  baseUrl: "https://api.example.com",
@@ -35,7 +35,7 @@ describe("ProofVerifier Integration - Real DID Resolution", () => {
35
35
  };
36
36
 
37
37
  const createValidProof = (did: string, kid: string): DetachedProof => {
38
- const header = { alg: "EdDSA", typ: "JWT" };
38
+ const header = { alg: "EdDSA", typ: "JWT", kid };
39
39
  const payload = {
40
40
  aud: "test-audience",
41
41
  sub: did,
@@ -39,7 +39,11 @@ describe('ProofVerifier Security', () => {
39
39
  };
40
40
 
41
41
  const createValidProof = (): DetachedProof => {
42
- const header = { alg: 'EdDSA', typ: 'JWT' };
42
+ const header = {
43
+ alg: 'EdDSA',
44
+ typ: 'JWT',
45
+ kid: 'did:key:z123#key-1',
46
+ };
43
47
  // Create a proper JSON payload that matches the meta structure
44
48
  const payload = {
45
49
  aud: 'test-audience',
@@ -253,7 +257,7 @@ describe('ProofVerifier Security', () => {
253
257
  });
254
258
 
255
259
  it('should handle detached JWS reconstruction', async () => {
256
- const header = { alg: 'EdDSA' };
260
+ const header = { alg: 'EdDSA', kid: 'did:key:z123#key-1' };
257
261
  const headerB64 = btoa(JSON.stringify(header))
258
262
  .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
259
263
  const signatureB64 = btoa('signature')
@@ -486,4 +490,3 @@ describe('ProofVerifier Security', () => {
486
490
  });
487
491
  });
488
492
  });
489
-
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Tests for ToolContextBuilder — delegation auth-type enforcement (Task B3)
3
+ *
4
+ * Security fix: consent-approve auth-gate (2026-07-29). These tests cover the
5
+ * delegation-only fallback in `buildContext` (the OAuth path), asserting that a
6
+ * delegation only authorizes a tool when its OWN authorization type satisfies
7
+ * the tool's required type.
8
+ *
9
+ * They exercise the exact enforcement gap that the demonstrated exploit rode:
10
+ * an anonymous consent-only (`none`) delegation must NOT satisfy an
11
+ * OAuth-gated tool. A legacy stored record with no persisted authorization type
12
+ * (undefined) is likewise rejected (fail-safe → re-challenge).
13
+ *
14
+ * The gate is reached only when no IDP token is stored but a delegation IS
15
+ * present, so every case here mocks `resolveTokenDataFromDid` → null.
16
+ */
17
+
18
+ import { describe, it, expect, vi, beforeEach } from "vitest";
19
+ import { ToolContextBuilder } from "../tool-context-builder";
20
+ import type { IdpTokenResolver } from "../../identity/idp-token-resolver";
21
+ import type { OAuthConfigService } from "../oauth-config.service";
22
+ import type { ProviderResolver } from "../provider-resolver";
23
+ import type { ToolProtection } from "../../types/tool-protection";
24
+ import { OAuthRequiredError } from "../../types/oauth-required-error";
25
+
26
+ describe("ToolContextBuilder — delegation auth-type enforcement (B3)", () => {
27
+ let mockTokenResolver: IdpTokenResolver;
28
+ let mockConfigService: OAuthConfigService;
29
+ let mockProviderResolver: ProviderResolver;
30
+ let builder: ToolContextBuilder;
31
+
32
+ // OAuth-gated tool: resolveProvider is mocked, so the concrete provider is
33
+ // irrelevant — only the required authorization.type drives the gate.
34
+ const oauthTool: ToolProtection = {
35
+ requiresDelegation: true,
36
+ requiredScopes: ["read:user"],
37
+ authorization: { type: "oauth2", provider: "github" },
38
+ };
39
+
40
+ // Legacy OAuth tool: no explicit authorization.type, provider resolved from
41
+ // the deprecated oauthProvider field. The gate falls back to "oauth2".
42
+ const legacyOauthTool: ToolProtection = {
43
+ requiresDelegation: true,
44
+ requiredScopes: ["read:user"],
45
+ oauthProvider: "github",
46
+ };
47
+
48
+ beforeEach(() => {
49
+ mockTokenResolver = {
50
+ // No stored IDP token → force the delegation-only fallback path.
51
+ resolveTokenDataFromDid: vi.fn().mockResolvedValue(null),
52
+ } as unknown as IdpTokenResolver;
53
+
54
+ mockConfigService = {
55
+ getOAuthConfig: vi.fn(),
56
+ } as unknown as OAuthConfigService;
57
+
58
+ mockProviderResolver = {
59
+ resolveProvider: vi.fn().mockResolvedValue("github"),
60
+ } as unknown as ProviderResolver;
61
+
62
+ builder = new ToolContextBuilder({
63
+ tokenResolver: mockTokenResolver,
64
+ configService: mockConfigService,
65
+ providerResolver: mockProviderResolver,
66
+ projectId: "proj-123",
67
+ });
68
+ });
69
+
70
+ it("REJECTS a `none`-type delegation for an oauth-gated tool (the exploit)", async () => {
71
+ await expect(
72
+ builder.buildContext(
73
+ "gated-tool",
74
+ "did:key:z6MkUser",
75
+ "session-123",
76
+ "delegation-token-anon",
77
+ oauthTool,
78
+ "none" // anonymous consent-only delegation
79
+ )
80
+ ).rejects.toThrow(OAuthRequiredError);
81
+ });
82
+
83
+ it("REJECTS a `password`-type delegation for an oauth-gated tool (cross-type)", async () => {
84
+ await expect(
85
+ builder.buildContext(
86
+ "gated-tool",
87
+ "did:key:z6MkUser",
88
+ "session-123",
89
+ "delegation-token-pw",
90
+ oauthTool,
91
+ "password"
92
+ )
93
+ ).rejects.toThrow(OAuthRequiredError);
94
+ });
95
+
96
+ it("REJECTS an undefined-type (legacy record) delegation for a typed tool", async () => {
97
+ await expect(
98
+ builder.buildContext(
99
+ "gated-tool",
100
+ "did:key:z6MkUser",
101
+ "session-123",
102
+ "delegation-token-legacy",
103
+ oauthTool,
104
+ undefined // predates persisting authorizationType → fail-safe
105
+ )
106
+ ).rejects.toThrow(OAuthRequiredError);
107
+ });
108
+
109
+ it("ACCEPTS an `oauth2`-type delegation for an oauth2-gated tool (happy path)", async () => {
110
+ const result = await builder.buildContext(
111
+ "gated-tool",
112
+ "did:key:z6MkUser",
113
+ "session-123",
114
+ "delegation-token-oauth",
115
+ oauthTool,
116
+ "oauth2"
117
+ );
118
+
119
+ expect(result).toBeDefined();
120
+ expect(result!.delegationToken).toBe("delegation-token-oauth");
121
+ expect(result!.provider).toBe("github");
122
+ expect(result!.userDid).toBe("did:key:z6MkUser");
123
+ });
124
+
125
+ it("ACCEPTS an `oauth` (deprecated alias) delegation for an oauth2-gated tool", async () => {
126
+ const result = await builder.buildContext(
127
+ "gated-tool",
128
+ "did:key:z6MkUser",
129
+ "session-123",
130
+ "delegation-token-oauth-alias",
131
+ oauthTool,
132
+ "oauth" // normalizes to oauth2
133
+ );
134
+
135
+ expect(result).toBeDefined();
136
+ expect(result!.delegationToken).toBe("delegation-token-oauth-alias");
137
+ });
138
+
139
+ it("ACCEPTS an `oauth2` delegation for a legacy oauthProvider-only tool (fallback)", async () => {
140
+ // authorization.type is absent → gate falls back to "oauth2"; a genuine
141
+ // OAuth delegation must still authorize such tools (no regression).
142
+ const result = await builder.buildContext(
143
+ "gated-tool",
144
+ "did:key:z6MkUser",
145
+ "session-123",
146
+ "delegation-token-oauth",
147
+ legacyOauthTool,
148
+ "oauth2"
149
+ );
150
+
151
+ expect(result).toBeDefined();
152
+ expect(result!.delegationToken).toBe("delegation-token-oauth");
153
+ });
154
+
155
+ it("REJECTS a `none` delegation for a legacy oauthProvider-only tool", async () => {
156
+ await expect(
157
+ builder.buildContext(
158
+ "gated-tool",
159
+ "did:key:z6MkUser",
160
+ "session-123",
161
+ "delegation-token-anon",
162
+ legacyOauthTool,
163
+ "none"
164
+ )
165
+ ).rejects.toThrow(OAuthRequiredError);
166
+ });
167
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Auth-Type Satisfaction Check
3
+ *
4
+ * Pure comparison used by the delegation-enforcement gate (security fix:
5
+ * consent-approve auth-gate, 2026-07-29, Task B3) to decide whether a
6
+ * delegation's authorization type satisfies a tool's required authorization
7
+ * type.
8
+ *
9
+ * Background: a gated MCP tool call is authorized by presenting a
10
+ * delegation. A bug let a delegation of ANY auth type satisfy a tool that
11
+ * requires a specific type — e.g. an anonymous consent-only (`none`)
12
+ * delegation wrongly satisfied a `password`-gated tool, because call-time
13
+ * enforcement accepted any present delegation without checking its
14
+ * `authorization.type`. This module implements the comparison that closes
15
+ * that gap. Wiring it into the enforcement sites (`agent.ts`,
16
+ * `tool-context-builder.ts`) is a later task (B3) — this module is
17
+ * intentionally standalone and unused by any gate yet.
18
+ *
19
+ * Decision (locked by product owner, 2026-07-29): STRICT NORMALIZED
20
+ * EQUALITY. A delegation type satisfies a required type iff, after folding
21
+ * deprecated aliases, they are equal. There is no "stronger satisfies
22
+ * weaker" lattice — `oauth`/`oauth2` and `password` are NOT interchangeable,
23
+ * and a `password` delegation does NOT satisfy a `none`-gated tool (or vice
24
+ * versa).
25
+ *
26
+ * @module @kya-os/mcp-i-runtime/services/auth-type-satisfies
27
+ */
28
+
29
+ /**
30
+ * Fold deprecated authorization-type aliases to their canonical form and
31
+ * normalize casing/whitespace.
32
+ *
33
+ * Alias rules mirror `normalizeAuthorizationType` in
34
+ * `packages/contracts/src/tool-protection/index.ts` (~774): `oauth` folds to
35
+ * `oauth2`, `credential` folds to `verifiable_credential`. That function
36
+ * operates on a full `AuthorizationRequirement` object and emits a
37
+ * deprecation warning on every call; this is a bare-string equivalent for
38
+ * use at the enforcement gate, where only the stored/required type strings
39
+ * — not the full requirement object — are available, and where a warning
40
+ * log on every tool call would be noise. (Not reusing the alias mapping
41
+ * directly from `@kya-os/contracts` here — it is not exposed as a
42
+ * standalone string-keyed map, only baked into that function's control
43
+ * flow — so the two rules are mirrored inline per the task's fallback
44
+ * guidance.)
45
+ *
46
+ * Canonical types (`AUTHORIZATION_TYPES`, contracts/src/tool-protection/index.ts
47
+ * ~88-106) are stored as lowercase string consts (e.g. "password", "oauth2",
48
+ * "none"), so normalization here only needs to trim and lowercase for
49
+ * defensive consistency — it does not need to handle differently-cased
50
+ * input from any known caller today.
51
+ *
52
+ * @param type - Raw authorization type string, or nullish if unknown/missing.
53
+ * @returns The normalized type string, or `undefined` if `type` is nullish or
54
+ * empty/whitespace-only after trimming.
55
+ */
56
+ export function normalizeAuthType(
57
+ type: string | undefined | null
58
+ ): string | undefined {
59
+ if (type === undefined || type === null) {
60
+ return undefined;
61
+ }
62
+
63
+ const trimmed = type.trim().toLowerCase();
64
+ if (trimmed === "") {
65
+ return undefined;
66
+ }
67
+
68
+ // Deprecated alias -> canonical (mirrors normalizeAuthorizationType).
69
+ if (trimmed === "oauth") {
70
+ return "oauth2";
71
+ }
72
+ if (trimmed === "credential") {
73
+ return "verifiable_credential";
74
+ }
75
+
76
+ return trimmed;
77
+ }
78
+
79
+ /**
80
+ * Decide whether a delegation's authorization type satisfies a tool's
81
+ * required authorization type.
82
+ *
83
+ * Strict normalized equality (locked decision, see module docs above): both
84
+ * types are normalized (alias-folded, trimmed, lowercased) and then compared
85
+ * for exact equality. There is no cross-type satisfaction — a `password`
86
+ * delegation does NOT satisfy an `oauth2`-gated tool, and (by the same
87
+ * strict rule) does NOT satisfy a `none`-gated tool either.
88
+ *
89
+ * Note on `none`-required tools: per strict equality, only a `none`
90
+ * delegation satisfies a `none` requirement. In practice, a tool requiring
91
+ * `none` (consent-only) is not expected to reach this call today — it is
92
+ * rejected earlier, before the delegation-presence gate, by
93
+ * `ConsentOnlyModeError` (see `provider-resolver.ts`) — so this function is
94
+ * expected to be invoked only for TYPED requirements (`password`, `oauth2`,
95
+ * `apikey`, etc.). Strict equality is still implemented faithfully for
96
+ * `none` in case that assumption ever changes.
97
+ *
98
+ * Fail-safe rules (both nullish cases return `false`, never `true`):
99
+ * - If `delegationType` is nullish (missing on a legacy stored record that
100
+ * predates persisting `authorizationType`, or simply absent), this
101
+ * returns `false` regardless of `requiredType` — an unknown/unrecorded
102
+ * delegation type never satisfies a typed requirement.
103
+ * - If `requiredType` is nullish (or normalizes to empty), there is no
104
+ * requirement to compare against. Callers are not expected to invoke this
105
+ * with a nullish `requiredType` (a tool with no authorization requirement
106
+ * doesn't reach this gate), but this fails safe to `false` rather than
107
+ * treating "no requirement" as automatically satisfied.
108
+ *
109
+ * @param delegationType - The delegation's stored/asserted authorization
110
+ * type (e.g. from `getDelegationFromStorage`), or nullish if unknown.
111
+ * @param requiredType - The tool's required authorization type (e.g.
112
+ * `protection.authorization.type`), or nullish.
113
+ * @returns `true` iff both types are present and equal after normalization.
114
+ */
115
+ export function authTypeSatisfies(
116
+ delegationType: string | undefined | null,
117
+ requiredType: string | undefined | null
118
+ ): boolean {
119
+ const normalizedDelegationType = normalizeAuthType(delegationType);
120
+ if (normalizedDelegationType === undefined) {
121
+ // Fail-safe: an unknown/missing delegation type never satisfies a
122
+ // requirement, typed or not.
123
+ return false;
124
+ }
125
+
126
+ const normalizedRequiredType = normalizeAuthType(requiredType);
127
+ if (normalizedRequiredType === undefined) {
128
+ // Fail-safe: no requirement to satisfy is not treated as "anything
129
+ // satisfies it".
130
+ return false;
131
+ }
132
+
133
+ return normalizedDelegationType === normalizedRequiredType;
134
+ }
@@ -8,10 +8,44 @@
8
8
  */
9
9
 
10
10
  import type { FetchProvider } from "../providers/base.js";
11
- import type { OAuthConfig, OAuthProvider } from "@kya-os/contracts/config";
11
+ import type {
12
+ OAuthConfig,
13
+ OAuthProvider,
14
+ OAuthProviderSecretMetadata,
15
+ } from "@kya-os/contracts/config";
12
16
  import type { OAuthConfigCache } from "../cache/oauth-config-cache.js";
13
17
  import { InMemoryOAuthConfigCache } from "../cache/oauth-config-cache.js";
14
18
 
19
+ /**
20
+ * Normalize a provider's secret-reference metadata from the AgentShield
21
+ * `/providers` response into the OAuthProvider `metadata` shape.
22
+ *
23
+ * The response may use camelCase or snake_case; only the secret-*name*
24
+ * references are carried (never the secret values). Returns `undefined` when
25
+ * no metadata is present so the field stays absent on the parsed provider.
26
+ */
27
+ function mapProviderSecretMetadata(
28
+ raw: unknown
29
+ ): OAuthProviderSecretMetadata | undefined {
30
+ if (!raw || typeof raw !== "object") return undefined;
31
+ const m = raw as Record<string, unknown>;
32
+ const metadata: OAuthProviderSecretMetadata = {
33
+ clientSecretName: (m.clientSecretName ?? m.client_secret_name) as
34
+ | string
35
+ | undefined,
36
+ clientIdSecretName: (m.clientIdSecretName ?? m.client_id_secret_name) as
37
+ | string
38
+ | undefined,
39
+ apiKeySecretName: (m.apiKeySecretName ?? m.api_key_secret_name) as
40
+ | string
41
+ | undefined,
42
+ clientSecretVersion: (m.clientSecretVersion ?? m.client_secret_version) as
43
+ | number
44
+ | undefined,
45
+ };
46
+ return metadata;
47
+ }
48
+
15
49
  export interface OAuthConfigServiceConfig {
16
50
  /** Base URL for AgentShield API (e.g., "https://kya.vouched.id") */
17
51
  baseUrl: string;
@@ -136,6 +170,15 @@ export class OAuthConfigService {
136
170
  tokenEndpointAuthMethod: (p.tokenEndpointAuthMethod ?? p.token_endpoint_auth_method) as "client_secret_post" | "client_secret_basic" | undefined,
137
171
  responseType: (p.responseType ?? p.response_type) as string | undefined,
138
172
  grantType: (p.grantType ?? p.grant_type) as string | undefined,
173
+ // Provider-registry secret metadata (clientSecretName etc.). REQUIRED:
174
+ // OAuthService.resolveClientSecret resolves a confidential provider's
175
+ // client secret from secure storage via `metadata.clientSecretName`
176
+ // (the AgentShield /providers response intentionally omits the plaintext
177
+ // `clientSecret`). Without mapping this field here, `metadata` is
178
+ // undefined, resolveClientSecret falls back to the (absent) inline
179
+ // clientSecret, and the worker sends an empty secret — token exchange
180
+ // then fails with "client_id and/or client_secret incorrect".
181
+ metadata: mapProviderSecretMetadata(p.metadata),
139
182
  };
140
183
  }
141
184
 
@@ -21,6 +21,7 @@ import {
21
21
  ConsentOnlyModeError,
22
22
  CredentialAuthModeError,
23
23
  } from "./provider-resolver.js";
24
+ import { authTypeSatisfies } from "./auth-type-satisfies.js";
24
25
 
25
26
  export interface ToolContextBuilderConfig {
26
27
  /** IDP token resolver for resolving tokens from User DID */
@@ -69,6 +70,11 @@ export class ToolContextBuilder {
69
70
  * @param sessionId - Session ID (optional)
70
71
  * @param delegationToken - Delegation token (optional)
71
72
  * @param toolProtection - Tool protection configuration (optional)
73
+ * @param delegationAuthorizationType - The stored authorization type of the
74
+ * presented delegation (from `getDelegationFromStorage`), or undefined for
75
+ * legacy records that predate persisting it. Used by the delegation-only
76
+ * fallback below to reject a delegation whose type does not satisfy the
77
+ * tool's required type (security fix: consent-approve auth-gate, Task B3).
72
78
  * @returns Tool execution context or undefined if not needed
73
79
  */
74
80
  async buildContext(
@@ -76,7 +82,8 @@ export class ToolContextBuilder {
76
82
  userDid: string | undefined,
77
83
  sessionId: string | undefined,
78
84
  delegationToken: string | undefined,
79
- toolProtection: ToolProtection | null
85
+ toolProtection: ToolProtection | null,
86
+ delegationAuthorizationType?: string
80
87
  ): Promise<ToolExecutionContext | undefined> {
81
88
  // Only build context if tool requires OAuth/credentials
82
89
  if (!toolProtection?.requiredScopes?.length || !userDid) {
@@ -127,14 +134,34 @@ export class ToolContextBuilder {
127
134
  // IDP token not available - check if delegation token exists
128
135
  // If delegation exists, tool can still execute without IDP token
129
136
  // (the tool handler should check for idpToken if it needs external API access)
130
- if (delegationToken) {
131
- this.config.logger("[ToolContextBuilder] IDP token not found, but delegation exists - returning minimal context", {
132
- toolName,
133
- userDid: userDid.substring(0, 20) + "...",
134
- provider,
135
- scopes: toolProtection.requiredScopes,
136
- note: "Tool can execute with delegation-only authorization",
137
- });
137
+ //
138
+ // SECURITY (consent-approve auth-gate, Task B3): a delegation only
139
+ // authorizes this tool if its OWN authorization type satisfies the tool's
140
+ // required type. Reaching this OAuth context builder means the tool is
141
+ // neither consent-only (`none`) nor password — those throw
142
+ // ConsentOnlyModeError / CredentialAuthModeError inside resolveProvider,
143
+ // BEFORE this point — so the effective requirement is OAuth. Fall back to
144
+ // "oauth2" only when the tool omits an explicit authorization.type (legacy
145
+ // oauthProvider-only config); this keeps such tools working while a
146
+ // mismatched delegation (e.g. an anonymous `none` consent-only delegation,
147
+ // or a legacy record with no persisted type → undefined) is rejected. On
148
+ // mismatch we do NOT return the delegation-only context; we fall through
149
+ // to OAuthRequiredError so the tool re-challenges.
150
+ const requiredAuthType = toolProtection.authorization?.type ?? "oauth2";
151
+ if (
152
+ delegationToken &&
153
+ authTypeSatisfies(delegationAuthorizationType, requiredAuthType)
154
+ ) {
155
+ this.config.logger(
156
+ "[ToolContextBuilder] IDP token not found, but delegation exists - returning minimal context",
157
+ {
158
+ toolName,
159
+ userDid: userDid.substring(0, 20) + "...",
160
+ provider,
161
+ scopes: toolProtection.requiredScopes,
162
+ note: "Tool can execute with delegation-only authorization",
163
+ }
164
+ );
138
165
 
139
166
  // Return minimal context with delegation info
140
167
  // Tools that need IDP token for external API calls should check for idpToken
@@ -147,13 +174,31 @@ export class ToolContextBuilder {
147
174
  };
148
175
  }
149
176
 
150
- // No delegation token either - throw OAuthRequiredError to trigger auth flow
151
- this.config.logger("[ToolContextBuilder] Token not available, throwing OAuthRequiredError", {
152
- toolName,
153
- userDid: userDid.substring(0, 20) + "...",
154
- provider,
155
- scopes: toolProtection.requiredScopes,
156
- });
177
+ if (delegationToken) {
178
+ // A delegation WAS presented but its authorization type does not satisfy
179
+ // the tool's required type — log and re-challenge instead of authorizing.
180
+ this.config.logger(
181
+ "[ToolContextBuilder] Delegation present but auth-type does not satisfy tool requirement - re-challenging",
182
+ {
183
+ toolName,
184
+ userDid: userDid.substring(0, 20) + "...",
185
+ provider,
186
+ requiredAuthType,
187
+ delegationAuthorizationType: delegationAuthorizationType ?? null,
188
+ }
189
+ );
190
+ }
191
+
192
+ // No (satisfying) delegation token - throw OAuthRequiredError to trigger auth flow
193
+ this.config.logger(
194
+ "[ToolContextBuilder] Token not available, throwing OAuthRequiredError",
195
+ {
196
+ toolName,
197
+ userDid: userDid.substring(0, 20) + "...",
198
+ provider,
199
+ scopes: toolProtection.requiredScopes,
200
+ }
201
+ );
157
202
 
158
203
  // Throw error with provider and scopes info
159
204
  // Auth URL will be built by the Cloudflare layer (agent.ts)
@@ -210,7 +255,9 @@ export class ToolContextBuilder {
210
255
  * @param tokenData - Token data with usage metadata
211
256
  * @returns Headers object for API calls
212
257
  */
213
- private buildAuthHeaders(tokenData: IdpTokensWithMetadata): Record<string, string> {
258
+ private buildAuthHeaders(
259
+ tokenData: IdpTokensWithMetadata
260
+ ): Record<string, string> {
214
261
  const authHeaders: Record<string, string> = {};
215
262
 
216
263
  const tokenUsage = tokenData.tokenUsage || "bearer"; // Default to bearer for OAuth
@@ -282,4 +329,3 @@ export class ToolContextBuilder {
282
329
  }
283
330
  }
284
331
  }
285
-