@kya-os/mcp-i-runtime 1.3.0 → 1.3.2

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 (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/proof/generator.d.ts +8 -6
  7. package/dist/proof/generator.d.ts.map +1 -1
  8. package/dist/proof/generator.js +7 -24
  9. package/dist/proof/generator.js.map +1 -1
  10. package/dist/runtime/audit.d.ts.map +1 -1
  11. package/dist/runtime/audit.js +66 -18
  12. package/dist/runtime/audit.js.map +1 -1
  13. package/dist/runtime/base.d.ts +6 -1
  14. package/dist/runtime/base.d.ts.map +1 -1
  15. package/dist/runtime/base.js +65 -17
  16. package/dist/runtime/base.js.map +1 -1
  17. package/dist/services/access-control.service.d.ts.map +1 -1
  18. package/dist/services/access-control.service.js +12 -5
  19. package/dist/services/access-control.service.js.map +1 -1
  20. package/dist/services/proof-verifier.d.ts +13 -35
  21. package/dist/services/proof-verifier.d.ts.map +1 -1
  22. package/dist/services/proof-verifier.js +16 -74
  23. package/dist/services/proof-verifier.js.map +1 -1
  24. package/dist/services/tool-context-builder.d.ts.map +1 -1
  25. package/dist/services/tool-context-builder.js +16 -4
  26. package/dist/services/tool-context-builder.js.map +1 -1
  27. package/dist/services/tool-protection.service.d.ts +7 -0
  28. package/dist/services/tool-protection.service.d.ts.map +1 -1
  29. package/dist/services/tool-protection.service.js +34 -15
  30. package/dist/services/tool-protection.service.js.map +1 -1
  31. package/dist/types/tool-protection.d.ts +94 -0
  32. package/dist/types/tool-protection.d.ts.map +1 -1
  33. package/dist/types/tool-protection.js +113 -1
  34. package/dist/types/tool-protection.js.map +1 -1
  35. package/package.json +4 -3
  36. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  37. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  38. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  39. package/src/__tests__/runtime/audit.test.ts +255 -53
  40. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  41. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  42. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  43. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  44. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  45. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  46. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  47. package/src/index.ts +15 -1
  48. package/src/proof/__tests__/proof-generator.test.ts +35 -12
  49. package/src/proof/generator.ts +18 -27
  50. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  51. package/src/runtime/audit.ts +155 -62
  52. package/src/runtime/base.ts +95 -31
  53. package/src/services/__tests__/access-control.service.test.ts +44 -0
  54. package/src/services/__tests__/proof-verifier.test.ts +283 -195
  55. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  56. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  57. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  58. package/src/services/access-control.service.ts +11 -5
  59. package/src/services/proof-verifier.ts +18 -79
  60. package/src/services/tool-context-builder.ts +19 -4
  61. package/src/services/tool-protection.service.ts +62 -19
  62. package/src/types/tool-protection.ts +161 -0
@@ -10,6 +10,7 @@ import type {
10
10
  // the denial code list, so the known codes come from this package instead.
11
11
  import type { DelegationDenialCode } from "@kya-os/contracts/config";
12
12
  import { DEFAULT_DENIAL_MESSAGES } from "./delegation-denial.js";
13
+ import { AmountLimitError } from "../types/tool-protection.js";
13
14
 
14
15
  const encoder = new TextEncoder();
15
16
  const MAX_REFERENCE_LENGTH = 256;
@@ -37,7 +38,7 @@ export interface RuntimeAuditAssurance {
37
38
  * remains AAP-0. Legacy diagnostic logging is deliberately not consulted.
38
39
  */
39
40
  export function resolveRuntimeAuditAssurance(
40
- config: RuntimeAuditConfig | undefined,
41
+ config: RuntimeAuditConfig | undefined
41
42
  ): RuntimeAuditAssurance {
42
43
  if (config === undefined) return { enabled: false, profile: "AAP-0" };
43
44
  const capabilities = config.trail.capabilities;
@@ -73,7 +74,13 @@ export interface RuntimeConsentAuditInput {
73
74
  }
74
75
 
75
76
  export interface RuntimeDelegationAuditInput {
76
- phase: "issued" | "verified" | "rejected" | "revoked" | "cascade_revoked" | "outbound_attached";
77
+ phase:
78
+ | "issued"
79
+ | "verified"
80
+ | "rejected"
81
+ | "revoked"
82
+ | "cascade_revoked"
83
+ | "outbound_attached";
77
84
  outcome: "succeeded" | "failed" | "denied";
78
85
  sessionId: string;
79
86
  delegationRef: string;
@@ -98,9 +105,9 @@ export interface RuntimeAuditCallContext {
98
105
  }
99
106
 
100
107
  export interface RuntimeAuditContextFactory {
101
- create(input: RuntimeAuditToolInput):
102
- | RuntimeAuditCallContext
103
- | Promise<RuntimeAuditCallContext>;
108
+ create(
109
+ input: RuntimeAuditToolInput
110
+ ): RuntimeAuditCallContext | Promise<RuntimeAuditCallContext>;
104
111
  }
105
112
 
106
113
  /**
@@ -128,7 +135,10 @@ export interface HmacRuntimeAuditContextOptions {
128
135
  randomUUID?: () => string;
129
136
  }
130
137
 
131
- function optionalString(record: Record<string, unknown> | undefined, key: string): string | undefined {
138
+ function optionalString(
139
+ record: Record<string, unknown> | undefined,
140
+ key: string
141
+ ): string | undefined {
132
142
  const value = record?.[key];
133
143
  if (typeof value !== "string") return undefined;
134
144
  const trimmed = value.trim();
@@ -158,32 +168,38 @@ function bytesToHex(bytes: Uint8Array): string {
158
168
  * before emission, so transport/session capabilities never enter the journal.
159
169
  */
160
170
  export function createHmacRuntimeAuditContextFactory(
161
- options: HmacRuntimeAuditContextOptions,
171
+ options: HmacRuntimeAuditContextOptions
162
172
  ): RuntimeAuditContextFactory {
163
173
  if (options.keyId.trim().length === 0) {
164
174
  throw new TypeError("Audit reference keyId must be non-empty");
165
175
  }
166
- const secret = typeof options.secret === "string"
167
- ? encoder.encode(options.secret)
168
- : new Uint8Array(options.secret);
176
+ const secret =
177
+ typeof options.secret === "string"
178
+ ? encoder.encode(options.secret)
179
+ : new Uint8Array(options.secret);
169
180
  if (secret.byteLength < 32) {
170
- throw new TypeError("Audit reference secret must contain at least 32 bytes");
181
+ throw new TypeError(
182
+ "Audit reference secret must contain at least 32 bytes"
183
+ );
171
184
  }
172
185
  const randomUUID = options.randomUUID ?? (() => crypto.randomUUID());
173
186
  let keyPromise: ReturnType<typeof crypto.subtle.importKey> | undefined;
174
187
 
175
- const commitment = async (domain: string, value: string): Promise<`sha256:${string}`> => {
188
+ const commitment = async (
189
+ domain: string,
190
+ value: string
191
+ ): Promise<`sha256:${string}`> => {
176
192
  keyPromise ??= crypto.subtle.importKey(
177
193
  "raw",
178
194
  secret,
179
195
  { name: "HMAC", hash: "SHA-256" },
180
196
  false,
181
- ["sign"],
197
+ ["sign"]
182
198
  );
183
199
  const signature = await crypto.subtle.sign(
184
200
  "HMAC",
185
201
  await keyPromise,
186
- encoder.encode(`${domain}\0${value}`),
202
+ encoder.encode(`${domain}\0${value}`)
187
203
  );
188
204
  return `sha256:${bytesToHex(new Uint8Array(signature))}`;
189
205
  };
@@ -194,25 +210,38 @@ export function createHmacRuntimeAuditContextFactory(
194
210
  return {
195
211
  async create(input): Promise<RuntimeAuditCallContext> {
196
212
  const session = input.session;
197
- const rawInvocation = optionalString(session, "auditInvocationId") ?? randomUUID();
198
- const rawCorrelation = optionalString(session, "auditCorrelationId") ?? rawInvocation;
213
+ const rawInvocation =
214
+ optionalString(session, "auditInvocationId") ?? randomUUID();
215
+ const rawCorrelation =
216
+ optionalString(session, "auditCorrelationId") ?? rawInvocation;
199
217
  const rawCausation = optionalString(session, "auditCausationId");
200
218
  const sessionId = optionalString(session, "id");
201
- const actorDid = optionalString(session, "clientDid") ?? optionalString(session, "userDid");
202
-
203
- const [invocationId, correlationId, causationId, sessionCommitment] = await Promise.all([
204
- opaqueId("invocation", rawInvocation),
205
- opaqueId("correlation", rawCorrelation),
206
- rawCausation === undefined ? undefined : opaqueId("causation", rawCausation),
207
- sessionId === undefined
208
- ? undefined
209
- : commitment("org.kya-os.audit.session-ref.v1", sessionId),
210
- ]);
219
+ // A holder proved by request admission outranks clientDid, which the
220
+ // caller asserts, and userDid. agentDid is never read: it can fall back
221
+ // to the server's own DID and would attribute the call to the server.
222
+ const actorDid =
223
+ optionalString(session, "verifiedInvokerDid") ??
224
+ optionalString(session, "clientDid") ??
225
+ optionalString(session, "userDid");
226
+
227
+ const [invocationId, correlationId, causationId, sessionCommitment] =
228
+ await Promise.all([
229
+ opaqueId("invocation", rawInvocation),
230
+ opaqueId("correlation", rawCorrelation),
231
+ rawCausation === undefined
232
+ ? undefined
233
+ : opaqueId("causation", rawCausation),
234
+ sessionId === undefined
235
+ ? undefined
236
+ : commitment("org.kya-os.audit.session-ref.v1", sessionId),
237
+ ]);
211
238
 
212
239
  return {
213
240
  invocationId: bounded(invocationId),
214
241
  correlationId: bounded(correlationId),
215
- ...(causationId === undefined ? {} : { causationId: bounded(causationId) }),
242
+ ...(causationId === undefined
243
+ ? {}
244
+ : { causationId: bounded(causationId) }),
216
245
  ...(sessionCommitment === undefined
217
246
  ? {}
218
247
  : {
@@ -232,7 +261,11 @@ export function createHmacRuntimeAuditContextFactory(
232
261
  };
233
262
  }
234
263
 
235
- export type RuntimeToolTerminalPhase = "completed" | "failed" | "denied" | "challenged";
264
+ export type RuntimeToolTerminalPhase =
265
+ | "completed"
266
+ | "failed"
267
+ | "denied"
268
+ | "challenged";
236
269
 
237
270
  export interface RuntimeToolTerminal {
238
271
  phase: RuntimeToolTerminalPhase;
@@ -247,7 +280,7 @@ export class RuntimeToolAuditInvocation {
247
280
  constructor(
248
281
  private readonly config: RuntimeAuditConfig,
249
282
  private readonly toolName: string,
250
- readonly context: RuntimeAuditCallContext,
283
+ readonly context: RuntimeAuditCallContext
251
284
  ) {}
252
285
 
253
286
  async started(): Promise<AuditEmitResult> {
@@ -257,7 +290,9 @@ export class RuntimeToolAuditInvocation {
257
290
  ...this.eventContext(),
258
291
  action: {
259
292
  category: "tool.call",
260
- ...(this.config.includeToolNames ? { name: bounded(this.toolName) } : {}),
293
+ ...(this.config.includeToolNames
294
+ ? { name: bounded(this.toolName) }
295
+ : {}),
261
296
  },
262
297
  outcome: "unknown",
263
298
  evidence: [],
@@ -274,7 +309,9 @@ export class RuntimeToolAuditInvocation {
274
309
 
275
310
  async terminal(value: RuntimeToolTerminal): Promise<AuditEmitResult> {
276
311
  if (this.terminalRecorded) {
277
- throw new Error(`Terminal audit event already recorded for ${this.context.invocationId}`);
312
+ throw new Error(
313
+ `Terminal audit event already recorded for ${this.context.invocationId}`
314
+ );
278
315
  }
279
316
  this.terminalRecorded = true;
280
317
  return this.config.trail.record({
@@ -283,7 +320,9 @@ export class RuntimeToolAuditInvocation {
283
320
  ...this.eventContext(),
284
321
  action: {
285
322
  category: "tool.call",
286
- ...(this.config.includeToolNames ? { name: bounded(this.toolName) } : {}),
323
+ ...(this.config.includeToolNames
324
+ ? { name: bounded(this.toolName) }
325
+ : {}),
287
326
  },
288
327
  outcome: value.outcome,
289
328
  ...(value.reasonCode === undefined
@@ -300,21 +339,33 @@ export class RuntimeToolAuditInvocation {
300
339
  }
301
340
 
302
341
  results(terminal?: AuditEmitResult): readonly AuditEmitResult[] {
303
- if (this.startedResult === undefined) return terminal === undefined ? [] : [terminal];
304
- return terminal === undefined ? [this.startedResult] : [this.startedResult, terminal];
342
+ if (this.startedResult === undefined)
343
+ return terminal === undefined ? [] : [terminal];
344
+ return terminal === undefined
345
+ ? [this.startedResult]
346
+ : [this.startedResult, terminal];
305
347
  }
306
348
 
307
349
  private eventContext(): Pick<
308
350
  AuditTrailEventInput,
309
- "correlationId" | "causationId" | "session" | "actor" | "responsibleParty" | "authorization"
351
+ | "correlationId"
352
+ | "causationId"
353
+ | "session"
354
+ | "actor"
355
+ | "responsibleParty"
356
+ | "authorization"
310
357
  > {
311
358
  return {
312
359
  correlationId: bounded(this.context.correlationId),
313
360
  ...(this.context.causationId === undefined
314
361
  ? {}
315
362
  : { causationId: bounded(this.context.causationId) }),
316
- ...(this.context.session === undefined ? {} : { session: this.context.session }),
317
- ...(this.context.actor === undefined ? {} : { actor: this.context.actor }),
363
+ ...(this.context.session === undefined
364
+ ? {}
365
+ : { session: this.context.session }),
366
+ ...(this.context.actor === undefined
367
+ ? {}
368
+ : { actor: this.context.actor }),
318
369
  ...(this.context.responsibleParty === undefined
319
370
  ? {}
320
371
  : { responsibleParty: this.context.responsibleParty }),
@@ -327,7 +378,7 @@ export class RuntimeToolAuditInvocation {
327
378
 
328
379
  export async function beginRuntimeToolAudit(
329
380
  config: RuntimeAuditConfig,
330
- input: RuntimeAuditToolInput,
381
+ input: RuntimeAuditToolInput
331
382
  ): Promise<RuntimeToolAuditInvocation> {
332
383
  if (config.sourceId.trim().length === 0) {
333
384
  throw new TypeError("Audit sourceId must be non-empty");
@@ -335,13 +386,13 @@ export async function beginRuntimeToolAudit(
335
386
  const trailSourceId = config.trail.configuration?.sourceId;
336
387
  if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
337
388
  throw new TypeError(
338
- `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
389
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`
339
390
  );
340
391
  }
341
392
  const invocation = new RuntimeToolAuditInvocation(
342
393
  config,
343
394
  input.toolName,
344
- await config.context.create(input),
395
+ await config.context.create(input)
345
396
  );
346
397
  await invocation.started();
347
398
  return invocation;
@@ -355,7 +406,7 @@ export async function beginRuntimeToolAudit(
355
406
  */
356
407
  export async function recordRuntimeConsentAudit(
357
408
  config: RuntimeAuditConfig,
358
- input: RuntimeConsentAuditInput,
409
+ input: RuntimeConsentAuditInput
359
410
  ): Promise<AuditEmitResult> {
360
411
  if (config.sourceId.trim().length === 0) {
361
412
  throw new TypeError("Audit sourceId must be non-empty");
@@ -363,7 +414,7 @@ export async function recordRuntimeConsentAudit(
363
414
  const trailSourceId = config.trail.configuration?.sourceId;
364
415
  if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
365
416
  throw new TypeError(
366
- `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
417
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`
367
418
  );
368
419
  }
369
420
 
@@ -423,7 +474,7 @@ export async function recordRuntimeConsentAudit(
423
474
  /** Record a privacy-minimal delegation lifecycle event on the canonical trail. */
424
475
  export async function recordRuntimeDelegationAudit(
425
476
  config: RuntimeAuditConfig,
426
- input: RuntimeDelegationAuditInput,
477
+ input: RuntimeDelegationAuditInput
427
478
  ): Promise<AuditEmitResult> {
428
479
  if (config.sourceId.trim().length === 0) {
429
480
  throw new TypeError("Audit sourceId must be non-empty");
@@ -431,7 +482,7 @@ export async function recordRuntimeDelegationAudit(
431
482
  const trailSourceId = config.trail.configuration?.sourceId;
432
483
  if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
433
484
  throw new TypeError(
434
- `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
485
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`
435
486
  );
436
487
  }
437
488
  const context = await config.context.create({
@@ -498,7 +549,9 @@ interface RuntimeAuditEventReference {
498
549
  };
499
550
  }
500
551
 
501
- function auditEventReference(result: AuditEmitResult): RuntimeAuditEventReference {
552
+ function auditEventReference(
553
+ result: AuditEmitResult
554
+ ): RuntimeAuditEventReference {
502
555
  return {
503
556
  eventId: result.event.eventId,
504
557
  eventType: result.event.eventType,
@@ -525,11 +578,13 @@ export function attachRuntimeAuditMetadata<T>(
525
578
  sourceId: string,
526
579
  invocationId: string,
527
580
  auditResults: readonly AuditEmitResult[],
528
- requiredDeliveryError = false,
581
+ requiredDeliveryError = false
529
582
  ): T {
530
583
  if (!isRecord(result) || Array.isArray(result)) {
531
584
  if (requiredDeliveryError) {
532
- throw new Error("Required terminal audit delivery failed after tool execution");
585
+ throw new Error(
586
+ "Required terminal audit delivery failed after tool execution"
587
+ );
533
588
  }
534
589
  return result;
535
590
  }
@@ -540,16 +595,22 @@ export function attachRuntimeAuditMetadata<T>(
540
595
  const existingAudit = isRecord(existingMeta[RUNTIME_AUDIT_META_KEY])
541
596
  ? existingMeta[RUNTIME_AUDIT_META_KEY]
542
597
  : {};
543
- const degraded = requiredDeliveryError || auditResults.some((item) => item.status === "failed");
598
+ const degraded =
599
+ requiredDeliveryError ||
600
+ auditResults.some((item) => item.status === "failed");
544
601
  mutableResult["_meta"] = {
545
602
  ...existingMeta,
546
603
  [RUNTIME_AUDIT_META_KEY]: {
547
604
  ...existingAudit,
548
- status: degraded ? "degraded" : auditResults.at(-1)?.status ?? "unknown",
605
+ status: degraded
606
+ ? "degraded"
607
+ : (auditResults.at(-1)?.status ?? "unknown"),
549
608
  sourceId,
550
609
  invocationId,
551
610
  events: auditResults.map(auditEventReference),
552
- ...(requiredDeliveryError ? { reason: "AUDIT_TERMINAL_DELIVERY_FAILED" } : {}),
611
+ ...(requiredDeliveryError
612
+ ? { reason: "AUDIT_TERMINAL_DELIVERY_FAILED" }
613
+ : {}),
553
614
  },
554
615
  };
555
616
  if (requiredDeliveryError) mutableResult["isError"] = true;
@@ -574,23 +635,34 @@ export function terminalForToolResult(result: unknown): RuntimeToolTerminal {
574
635
  reasonCode: "AUTHORIZATION_REQUIRED",
575
636
  };
576
637
  }
577
- if (result.isError !== true) return { phase: "completed", outcome: "succeeded" };
638
+ if (result.isError !== true)
639
+ return { phase: "completed", outcome: "succeeded" };
578
640
  const metadata = isRecord(result._meta) ? result._meta : undefined;
579
- const errorType = typeof metadata?.errorType === "string" ? metadata.errorType : undefined;
580
- if (errorType === "authorization_required" || errorType === "oauth_required" ||
581
- isRecord(metadata?.needs_authorization)) {
641
+ const errorType =
642
+ typeof metadata?.errorType === "string" ? metadata.errorType : undefined;
643
+ if (
644
+ errorType === "authorization_required" ||
645
+ errorType === "oauth_required" ||
646
+ isRecord(metadata?.needs_authorization)
647
+ ) {
582
648
  return {
583
649
  phase: "challenged",
584
650
  outcome: "challenged",
585
651
  reasonCode: "AUTHORIZATION_REQUIRED",
586
652
  };
587
653
  }
588
- return { phase: "failed", outcome: "failed", reasonCode: "HANDLER_ERROR_RESULT" };
654
+ return {
655
+ phase: "failed",
656
+ outcome: "failed",
657
+ reasonCode: "HANDLER_ERROR_RESULT",
658
+ };
589
659
  }
590
660
 
591
661
  // Read by shape, like the name checks below, because the error may come from
592
662
  // another copy of this package. Only a known code counts as a denial.
593
- function delegationDenialCode(error: unknown): DelegationDenialCode | undefined {
663
+ function delegationDenialCode(
664
+ error: unknown
665
+ ): DelegationDenialCode | undefined {
594
666
  if (!isRecord(error) || !isRecord(error.denial)) return undefined;
595
667
  const code = error.denial.code;
596
668
  // Own keys only, so an inherited name such as "constructor" never matches.
@@ -600,20 +672,41 @@ function delegationDenialCode(error: unknown): DelegationDenialCode | undefined
600
672
  : undefined;
601
673
  }
602
674
 
675
+ const STATEFUL_DENIAL_CODES: ReadonlySet<DelegationDenialCode> = new Set([
676
+ "budget_exceeded",
677
+ "policy_denied",
678
+ ]);
679
+
603
680
  export function terminalForToolError(error: unknown): RuntimeToolTerminal {
681
+ if (error instanceof AmountLimitError) {
682
+ return {
683
+ phase: "denied",
684
+ outcome: "denied",
685
+ reasonCode: error.code.toUpperCase(),
686
+ };
687
+ }
604
688
  const name = error instanceof Error ? error.name : "UnknownError";
605
689
  const denialCode =
606
- name === "DelegationRequiredError" ? delegationDenialCode(error) : undefined;
690
+ name === "DelegationRequiredError"
691
+ ? delegationDenialCode(error)
692
+ : undefined;
607
693
  if (denialCode !== undefined) {
608
- // The verifier refused a presented grant: a denial, not a request for consent.
694
+ // A stateful policy refusal (a spent budget, an origin or IP rule) is a
695
+ // denial: a new grant would not change the answer. Any other verifier
696
+ // refusal of a presented grant (revoked, expired, another holder, too
697
+ // little scope) is a challenge: a new grant could fix it.
698
+ const stateful = STATEFUL_DENIAL_CODES.has(denialCode);
609
699
  return {
610
- phase: "denied",
611
- outcome: "denied",
700
+ phase: stateful ? "denied" : "challenged",
701
+ outcome: stateful ? "denied" : "challenged",
612
702
  reasonCode: denialCode.toUpperCase(),
613
703
  };
614
704
  }
615
- if (name === "DelegationRequiredError" || name === "OAuthRequiredError" ||
616
- name === "AuthRequiredError") {
705
+ if (
706
+ name === "DelegationRequiredError" ||
707
+ name === "OAuthRequiredError" ||
708
+ name === "AuthRequiredError"
709
+ ) {
617
710
  return {
618
711
  phase: "challenged",
619
712
  outcome: "challenged",