@apifuse/provider-sdk 2.2.0-beta.4 → 2.2.0-beta.7

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 (51) hide show
  1. package/AUTHORING.md +92 -0
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +5 -1
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-check.ts +26 -1
  6. package/bin/apifuse-pack-check.ts +14 -0
  7. package/bin/apifuse-submit-check.ts +433 -15
  8. package/bin/apifuse-sync-assets.ts +117 -0
  9. package/dist/cli/commands.d.ts +1 -1
  10. package/dist/cli/commands.js +8 -0
  11. package/dist/cli/create.d.ts +3 -0
  12. package/dist/cli/create.js +34 -35
  13. package/dist/cli/prompt-assets.d.ts +80 -0
  14. package/dist/cli/prompt-assets.js +743 -0
  15. package/dist/cli/templates/provider/AGENTS.md.tpl +17 -8
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.js +1 -0
  18. package/dist/runtime/executor.js +7 -0
  19. package/dist/runtime/secrets.d.ts +27 -0
  20. package/dist/runtime/secrets.js +51 -0
  21. package/dist/server/index.d.ts +1 -1
  22. package/dist/server/index.js +1 -1
  23. package/dist/server/self-test.d.ts +101 -0
  24. package/dist/server/self-test.js +670 -112
  25. package/dist/server/serve.d.ts +5 -0
  26. package/dist/server/serve.js +41 -1
  27. package/package.json +1 -1
  28. package/src/cli/commands.ts +10 -0
  29. package/src/cli/create.ts +42 -35
  30. package/src/cli/prompt-assets.ts +865 -0
  31. package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
  32. package/src/index.ts +5 -0
  33. package/src/runtime/executor.ts +8 -0
  34. package/src/runtime/secrets.ts +64 -0
  35. package/src/server/index.ts +5 -0
  36. package/src/server/self-test.ts +852 -127
  37. package/src/server/serve.ts +60 -1
  38. package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
  39. package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
  40. /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  41. /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  42. /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  43. /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  44. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  45. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
  46. /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  47. /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  48. /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  49. /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  50. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  51. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
+ import { TURN_KINDS } from "../auth-turn/index.js";
3
4
  import { Hono } from "hono";
4
5
  import { z } from "zod";
5
6
  import { resolveHealthCheckInputDateTokens } from "./self-test-input-tokens.js";
@@ -27,6 +28,36 @@ export const SelfTestRequestSchema = z.object({
27
28
  /** Credential material for requiresConnection cases; never persisted. */
28
29
  credentials: z.object({ inputs: z.record(z.string(), z.string()) }).optional(),
29
30
  });
31
+ /**
32
+ * Skip reason reported when a declared auth flow does not complete in a single
33
+ * continue (OTP, retry loop). Cross-repo contract: the health-monitor maps
34
+ * this exact string to `self_test_incapable`; never vary it.
35
+ */
36
+ export const SELF_TEST_AUTH_FLOW_MULTI_TURN_SKIP_REASON = "auth_flow_multi_turn";
37
+ /**
38
+ * A `retry` turn after credential submission: the flow REJECTED the
39
+ * configured inputs (bad password, exchange failure). Distinct from the
40
+ * multi-turn gap so monitoring surfaces it as a real credential outage, and
41
+ * memoized like multi-turn so the probe does not re-submit rejected
42
+ * credentials every cycle (lockout safety).
43
+ */
44
+ export const SELF_TEST_AUTH_FLOW_REJECTED_SKIP_REASON = "auth_flow_rejected";
45
+ /**
46
+ * Known interactive turn kinds that justify the memoized multi-turn skip —
47
+ * they mean a human must participate (OTP, challenge, redirect, …).
48
+ * `retry` is deliberately excluded: after a credential submission it means
49
+ * rejection, not interaction (see SELF_TEST_AUTH_FLOW_REJECTED_SKIP_REASON).
50
+ * Kinds outside TURN_KINDS entirely are treated as flow errors.
51
+ */
52
+ /**
53
+ * Post-submission /auth/continue statuses that mean the flow REJECTED the
54
+ * credentials (thrown AuthError -> 401, forbidden -> 403): memoized as
55
+ * `auth_flow_rejected`. Deliberately NOT 400 — the auth route maps generic
56
+ * ProviderErrors and Zod request errors there, which are often transient or
57
+ * fixable and must stay uncached retries (like 408/429/5xx).
58
+ */
59
+ const AUTH_REJECTION_HTTP_STATUSES = new Set([401, 403]);
60
+ const INTERACTIVE_TURN_KIND_SET = new Set(TURN_KINDS.filter((descriptor) => descriptor.rendering !== "terminal" && descriptor.kind !== "retry").map((descriptor) => descriptor.kind));
30
61
  function resolveSdkVersion() {
31
62
  try {
32
63
  const packageJsonUrl = new URL("../../package.json", import.meta.url);
@@ -130,6 +161,32 @@ export function createSelfTestInvoke(app) {
130
161
  return { status: response.status, data: body };
131
162
  };
132
163
  }
164
+ /** Binds the self-test auth-flow driver to a tenant app's /auth pipeline in-process. */
165
+ export function createSelfTestAuthFlowInvoke(app) {
166
+ return async ({ route, requestId, flowId, connectionId, externalRef, input, context }) => {
167
+ const response = await app.request(`/auth/${route}`, {
168
+ method: "POST",
169
+ headers: { "content-type": "application/json" },
170
+ body: JSON.stringify({
171
+ requestId,
172
+ flowId,
173
+ ...(connectionId ? { connectionId } : {}),
174
+ ...(externalRef ? { externalRef } : {}),
175
+ ...(input ? { input } : {}),
176
+ ...(context ? { context } : {}),
177
+ }),
178
+ });
179
+ const text = await response.text();
180
+ let body = text;
181
+ try {
182
+ body = text.length > 0 ? JSON.parse(text) : undefined;
183
+ }
184
+ catch {
185
+ // non-JSON transports keep the raw text as body
186
+ }
187
+ return { status: response.status, body };
188
+ };
189
+ }
133
190
  class SelfTestCaseTimeoutError extends Error {
134
191
  constructor(timeoutMs) {
135
192
  super(`Self-test case timed out after ${timeoutMs}ms`);
@@ -171,6 +228,21 @@ function upstreamErrorMessage(body) {
171
228
  const message = objectProperty(error, "message");
172
229
  return typeof message === "string" ? message : undefined;
173
230
  }
231
+ /**
232
+ * How long a memoized multi-turn flow outcome suppresses re-driving the auth
233
+ * flow. Generous on purpose: a multi-turn ceremony (OTP, device approval) is a
234
+ * provider property that changes on the timescale of releases, not probe
235
+ * cycles, and every re-drive is a REAL upstream login submission. The cache is
236
+ * in-process, so a pod restart also clears the entry.
237
+ */
238
+ export const SELF_TEST_MULTI_TURN_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;
239
+ /**
240
+ * Age bound for POSITIVE cached credentials. Expiry modes that never produce
241
+ * a 401/403 (a 200 login page, an assertion failure) would otherwise replay
242
+ * the same stale session until pod restart — one re-login per day is the
243
+ * upstream-safe recovery for them.
244
+ */
245
+ export const SELF_TEST_CREDENTIAL_MAX_AGE_MS = 24 * 60 * 60 * 1000;
174
246
  function resolveCaseTimeoutMs(execution, suite, healthCase) {
175
247
  const providerDefault = (execution.provider.healthProbe ?? execution.provider.healthMonitor)
176
248
  ?.defaultProbeTimeoutMs;
@@ -180,160 +252,640 @@ function resolveCaseTimeoutMs(execution, suite, healthCase) {
180
252
  providerDefault ??
181
253
  DEFAULT_CASE_TIMEOUT_MS);
182
254
  }
183
- function buildSelfTestConnection(execution, operationId, suite) {
255
+ function credentialSessionCacheKey(providerId, inputs) {
256
+ const canonical = JSON.stringify(Object.keys(inputs)
257
+ .sort()
258
+ .map((key) => [key, inputs[key]]));
259
+ return `${providerId}:${createHash("sha256").update(canonical).digest("hex")}`;
260
+ }
261
+ function registerSensitiveValues(execution, values) {
262
+ for (const value of values) {
263
+ if (typeof value === "string" &&
264
+ value.length > 0 &&
265
+ !execution.sensitiveValues.includes(value)) {
266
+ execution.sensitiveValues.push(value);
267
+ }
268
+ }
269
+ }
270
+ function parseAuthFlowResponse(result) {
271
+ const errorEnvelope = objectProperty(result.body, "error");
272
+ if (result.status < 200 || result.status >= 300 || errorEnvelope !== undefined) {
273
+ const message = objectProperty(errorEnvelope, "message");
274
+ return {
275
+ ok: false,
276
+ code: "auth_flow_failed",
277
+ message: typeof message === "string"
278
+ ? message
279
+ : `Auth flow request failed with status ${result.status}`,
280
+ httpStatus: result.status,
281
+ };
282
+ }
283
+ const turnValue = objectProperty(result.body, "data");
284
+ const turnKind = objectProperty(turnValue, "kind");
285
+ if (typeof turnKind !== "string") {
286
+ return {
287
+ ok: false,
288
+ code: "auth_flow_failed",
289
+ message: "Auth flow returned an unrecognized turn.",
290
+ httpStatus: result.status,
291
+ };
292
+ }
293
+ const contextPatch = objectProperty(result.body, "contextPatch");
294
+ return {
295
+ ok: true,
296
+ turn: {
297
+ kind: turnKind,
298
+ data: objectProperty(turnValue, "data"),
299
+ expectedInput: objectProperty(turnValue, "expectedInput"),
300
+ },
301
+ ...(contextPatch && typeof contextPatch === "object" && !Array.isArray(contextPatch)
302
+ ? { contextPatch: contextPatch }
303
+ : {}),
304
+ };
305
+ }
306
+ function applyAuthFlowContextPatch(base, patch) {
307
+ if (!patch)
308
+ return base;
309
+ const next = { ...base };
310
+ for (const [key, value] of Object.entries(patch)) {
311
+ if (value === null) {
312
+ delete next[key];
313
+ }
314
+ else {
315
+ next[key] = value;
316
+ }
317
+ }
318
+ return next;
319
+ }
320
+ /**
321
+ * Extracts the completed credential from a complete turn's data payload — the
322
+ * same `data.credential` record the gateway persists as connection secrets in
323
+ * production (`persistCredential` → credential-service `UpdateCredential`).
324
+ */
325
+ function completedCredentialFromTurn(turnData) {
326
+ const credential = objectProperty(turnData, "credential");
327
+ if (!credential || typeof credential !== "object" || Array.isArray(credential)) {
328
+ return undefined;
329
+ }
330
+ const secrets = {};
331
+ for (const [key, value] of Object.entries(credential)) {
332
+ if (typeof value === "string")
333
+ secrets[key] = value;
334
+ }
335
+ return Object.keys(secrets).length > 0 ? secrets : undefined;
336
+ }
337
+ /**
338
+ * Drives the provider's declared auth flow exactly like production does:
339
+ * `flow.start()` then a single `flow.continue(credentialInputs)`. Anything
340
+ * other than a complete turn is a visible multi-turn gap, never a fabricated
341
+ * probe failure.
342
+ */
343
+ /**
344
+ * Fields an input-prompt turn actually requests. The canonical auth-turn
345
+ * shape carries the JSON schema DIRECTLY on `expectedInput` (`ctx.auth
346
+ * .nextForm`/`defineCredentialsAuth`, the committed fixtures); some providers
347
+ * nest it as `expectedInput.schema`. Both are honored. `null` when the turn
348
+ * declares no schema (legacy/loose flows keep full-input semantics).
349
+ */
350
+ function turnRequestedFields(turn) {
351
+ const expectedInput = turn.expectedInput;
352
+ if (!expectedInput || typeof expectedInput !== "object" || Array.isArray(expectedInput)) {
353
+ return null;
354
+ }
355
+ const schemaOf = (candidate) => {
356
+ const properties = candidate && typeof candidate === "object"
357
+ ? candidate.properties
358
+ : undefined;
359
+ if (!properties || typeof properties !== "object" || Array.isArray(properties)) {
360
+ return null;
361
+ }
362
+ const requiredRaw = candidate && typeof candidate === "object"
363
+ ? candidate.required
364
+ : undefined;
365
+ const required = Array.isArray(requiredRaw)
366
+ ? requiredRaw.filter((field) => typeof field === "string")
367
+ : [];
368
+ return { properties: Object.keys(properties), required };
369
+ };
370
+ return (schemaOf(expectedInput) ?? schemaOf(expectedInput.schema));
371
+ }
372
+ async function materializeFlowCredential(execution, inputs, options = {}) {
373
+ const authFlow = execution.authFlow;
374
+ if (!authFlow) {
375
+ return {
376
+ kind: "flow_error",
377
+ code: "auth_flow_unavailable",
378
+ message: "Provider declares a credentials auth flow but the self-test host has no auth-flow driver.",
379
+ };
380
+ }
381
+ const flowId = `self-test-${randomUUID()}`;
382
+ // The login must ride the SAME proxy/connection affinity the probe will
383
+ // use (createAuthFlowContext keys affinity on connectionId) — otherwise
384
+ // IP/session-bound upstreams see the cookie arrive from a different
385
+ // session and reject it.
386
+ const started = parseAuthFlowResponse(await authFlow({
387
+ route: "start",
388
+ requestId: `${execution.requestId}-auth-start-${randomUUID()}`,
389
+ flowId,
390
+ ...(options.connectionId ? { connectionId: options.connectionId } : {}),
391
+ ...(options.externalRef ? { externalRef: options.externalRef } : {}),
392
+ }));
393
+ if (!started.ok) {
394
+ return { kind: "flow_error", code: started.code, message: started.message };
395
+ }
396
+ let turn = started.turn;
397
+ const flowContext = applyAuthFlowContextPatch({}, started.contextPatch);
398
+ if (turn.kind === "abort") {
399
+ // Terminal turn: continuing after an abort would replay credentials into
400
+ // a flow that already refused to proceed. Not memoized (flow errors are
401
+ // never cached) — an abort can be transient upstream maintenance.
402
+ return {
403
+ kind: "flow_error",
404
+ code: "auth_flow_aborted",
405
+ message: "Auth flow aborted before requesting input.",
406
+ };
407
+ }
408
+ if (turn.kind !== "complete") {
409
+ // Validate the start turn BEFORE submitting credentials: an unknown
410
+ // kind may be a provider typo or a stage that must not receive the
411
+ // probe inputs. `retry` counts as an input prompt at this stage.
412
+ if (turn.kind !== "retry" && !INTERACTIVE_TURN_KIND_SET.has(turn.kind)) {
413
+ return {
414
+ kind: "flow_error",
415
+ code: "auth_flow_unexpected_turn",
416
+ message: `Auth flow start returned an unrecognized turn kind "${turn.kind}".`,
417
+ };
418
+ }
419
+ // Auto-continue ONLY into input prompts (form/retry). Other known
420
+ // interactive stages (redirect, poll, pending, challenge, message,
421
+ // multi_choice) are valid flows that are NOT asking for the credential
422
+ // inputs — posting the password there submits it to the wrong stage.
423
+ // They are a genuine headless gap: the memoized multi-turn skip.
424
+ if (turn.kind !== "form" && turn.kind !== "retry") {
425
+ return { kind: "skip", skipReason: SELF_TEST_AUTH_FLOW_MULTI_TURN_SKIP_REASON };
426
+ }
427
+ // Submit ONLY what the turn asks for: a first stage of a multi-step
428
+ // login may request a subset (or different fields entirely) — posting
429
+ // the full inputs would send secrets to the wrong stage. Only the
430
+ // schema's REQUIRED fields are mandatory (defineCredentialsAuth
431
+ // encodes optional fields by omitting them from `required`); a turn
432
+ // whose required fields we do not hold is a headless gap (multi-turn).
433
+ // A turn with no declared schema keeps full-input semantics.
434
+ const requestedFields = turnRequestedFields(turn);
435
+ let submitInputs = { ...inputs };
436
+ if (requestedFields !== null) {
437
+ if (requestedFields.required.some((field) => inputs[field] === undefined)) {
438
+ return { kind: "skip", skipReason: SELF_TEST_AUTH_FLOW_MULTI_TURN_SKIP_REASON };
439
+ }
440
+ submitInputs = Object.fromEntries(requestedFields.properties
441
+ .filter((field) => inputs[field] !== undefined)
442
+ .map((field) => [field, inputs[field]]));
443
+ }
444
+ // The case deadline may have fired while start() was still running.
445
+ // Never submit real credentials into a flow whose case already
446
+ // reported self_test_timeout — a late continue is a real upstream
447
+ // login/OTP attempt nobody is waiting for.
448
+ if (options.isAbandoned?.() === true) {
449
+ return {
450
+ kind: "flow_error",
451
+ code: "self_test_timeout",
452
+ message: "Case deadline passed before credential submission; flow abandoned.",
453
+ };
454
+ }
455
+ const continued = parseAuthFlowResponse(await authFlow({
456
+ route: "continue",
457
+ requestId: `${execution.requestId}-auth-continue-${randomUUID()}`,
458
+ flowId,
459
+ ...(options.connectionId ? { connectionId: options.connectionId } : {}),
460
+ ...(options.externalRef ? { externalRef: options.externalRef } : {}),
461
+ input: submitInputs,
462
+ ...(Object.keys(flowContext).length > 0 ? { context: flowContext } : {}),
463
+ }));
464
+ if (!continued.ok) {
465
+ // Providers built with defineCredentialsAuth cannot return a retry
466
+ // turn — a rejected password THROWS and /auth/continue answers with
467
+ // an auth-shaped 401/403. That is a credential REJECTION (memoized,
468
+ // so the probe never hammers a locked-out login); every other
469
+ // status stays an uncached transient retry.
470
+ if (AUTH_REJECTION_HTTP_STATUSES.has(continued.httpStatus)) {
471
+ return { kind: "skip", skipReason: SELF_TEST_AUTH_FLOW_REJECTED_SKIP_REASON };
472
+ }
473
+ return { kind: "flow_error", code: continued.code, message: continued.message };
474
+ }
475
+ turn = continued.turn;
476
+ }
477
+ if (turn.kind === "abort") {
478
+ return {
479
+ kind: "flow_error",
480
+ code: "auth_flow_aborted",
481
+ message: "Auth flow aborted after credential submission.",
482
+ };
483
+ }
484
+ if (turn.kind === "retry") {
485
+ // A retry turn AFTER submission is a credential rejection, not an
486
+ // interactive gap — surfaced distinctly so monitoring can treat it as
487
+ // a real outage, and memoized by the caller (lockout safety).
488
+ return { kind: "skip", skipReason: SELF_TEST_AUTH_FLOW_REJECTED_SKIP_REASON };
489
+ }
490
+ if (turn.kind !== "complete") {
491
+ // Only KNOWN interactive kinds are a genuine "cannot complete headless"
492
+ // multi-turn gap (memoized by the caller). An unknown kind is ambiguous
493
+ // — it may encode a transient provider failure — so it reports as a
494
+ // flow error, which is never memoized, instead of freezing the signal.
495
+ if (!INTERACTIVE_TURN_KIND_SET.has(turn.kind)) {
496
+ return {
497
+ kind: "flow_error",
498
+ code: "auth_flow_unexpected_turn",
499
+ message: `Auth flow returned an unrecognized turn kind "${turn.kind}".`,
500
+ };
501
+ }
502
+ return { kind: "skip", skipReason: SELF_TEST_AUTH_FLOW_MULTI_TURN_SKIP_REASON };
503
+ }
504
+ const credential = completedCredentialFromTurn(turn.data);
505
+ if (!credential) {
506
+ return {
507
+ kind: "flow_error",
508
+ code: "auth_flow_invalid_credential",
509
+ message: "Auth flow completed without a string-valued credential payload.",
510
+ };
511
+ }
512
+ // Redaction contract: flow-issued secrets are registered BEFORE any probe
513
+ // output can be built from them.
514
+ registerSensitiveValues(execution, Object.values(credential));
515
+ return { credential };
516
+ }
517
+ async function resolveSelfTestConnection(execution, operationId, suite, options = {}) {
184
518
  if (!suite.requiresConnection)
185
- return {};
519
+ return { kind: "connection" };
186
520
  const inputs = execution.credentials ?? {};
187
521
  const declaredFields = Object.keys((execution.provider.healthProbe ?? execution.provider.healthMonitor)?.credentialInputs ?? {});
188
522
  for (const field of declaredFields) {
189
523
  if (!inputs[field]) {
190
- return { skipReason: `credential_missing:${field}` };
524
+ return { kind: "skip", skipReason: `credential_missing:${field}` };
191
525
  }
192
526
  }
193
527
  if (declaredFields.length === 0 && Object.keys(inputs).length === 0) {
194
- return { skipReason: "credential_missing:credentials" };
528
+ return { kind: "skip", skipReason: "credential_missing:credentials" };
529
+ }
530
+ // The connection id seeds proxy/connection affinity in the provider
531
+ // context, so it must be STABLE per (provider, credentialInputs): a cached
532
+ // session replayed under a per-request id would ride a different proxy/IP
533
+ // each cycle and upstreams would treat the cookie as stale or suspicious.
534
+ // The id carries only a hash of the inputs, never the inputs themselves.
535
+ //
536
+ // Providers declaring `proxy.session.affinity: "operation"` pin the PROBE's
537
+ // proxy to `${providerId}/${operationId}` regardless of connection id — so
538
+ // the login must ride that exact key, and the session cache splits per
539
+ // operation (one shared cookie would otherwise hop between per-operation
540
+ // proxies).
541
+ const operationAffinity = typeof execution.provider.proxy === "object" &&
542
+ execution.provider.proxy?.session?.affinity === "operation";
543
+ const credentialKey = credentialSessionCacheKey(execution.provider.id, inputs);
544
+ const affinityKey = operationAffinity ? `${credentialKey}:${operationId}` : credentialKey;
545
+ // ONE id for the auth flow AND the probe connection: providers may bind
546
+ // the issued credential to FlowContext.connectionId and later compare it
547
+ // against ctx.request.connectionId. Operation-affinity providers use the
548
+ // probe's exact proxy key (providerId/operationId); everyone else uses the
549
+ // stable per-credential hash.
550
+ const connectionId = operationAffinity
551
+ ? `${execution.provider.id}/${operationId}`
552
+ : `self-test-${createHash("sha256").update(affinityKey).digest("hex").slice(0, 22)}`;
553
+ const buildConnection = (secrets) => ({
554
+ id: connectionId,
555
+ mode: "credentials",
556
+ secrets: { ...secrets },
557
+ metadata: { purpose: "provider-self-test", operationId },
558
+ externalRef: `${execution.provider.id}-${operationId}-self-test`,
559
+ });
560
+ const auth = execution.provider.auth;
561
+ if (auth?.mode !== "credentials" || !auth.flow) {
562
+ // Providers without a declared credentials flow keep raw-input semantics
563
+ // — and the pre-existing per-request connection id: there is no session
564
+ // to keep on one affinity, and a stable id would silently pin every
565
+ // cycle of a connection-affinity proxy to the same upstream session.
566
+ return {
567
+ kind: "connection",
568
+ connection: {
569
+ ...buildConnection(inputs),
570
+ id: `self-test-${execution.requestId}`,
571
+ },
572
+ credentialSource: "inputs",
573
+ };
574
+ }
575
+ const cacheKey = affinityKey;
576
+ const cached = execution.sessionCache.get(cacheKey);
577
+ // DR-7 upstream-account safety: a memoized multi-turn outcome
578
+ // short-circuits to the auth_flow_multi_turn skip WITHOUT re-driving
579
+ // flow.start()/flow.continue() — every re-drive is a real upstream login
580
+ // submission (OTP sends, lockout risk), and the probe scheduler would
581
+ // otherwise repeat it every cycle forever. Changed credentialInputs hash
582
+ // to a different key and re-attempt immediately; otherwise the entry
583
+ // expires after a generous TTL (or process restart) so a provider whose
584
+ // flow becomes single-turn again is eventually re-probed.
585
+ if (cached?.kind === "multi_turn" || cached?.kind === "rejected") {
586
+ if (Date.now() - cached.cachedAtMs < SELF_TEST_MULTI_TURN_RETRY_AFTER_MS) {
587
+ return {
588
+ kind: "skip",
589
+ skipReason: cached.kind === "rejected"
590
+ ? SELF_TEST_AUTH_FLOW_REJECTED_SKIP_REASON
591
+ : SELF_TEST_AUTH_FLOW_MULTI_TURN_SKIP_REASON,
592
+ };
593
+ }
594
+ execution.sessionCache.delete(cacheKey);
595
+ }
596
+ if (options.forceLogin !== true && cached?.kind === "credential") {
597
+ if (Date.now() - cached.cachedAtMs >= SELF_TEST_CREDENTIAL_MAX_AGE_MS) {
598
+ // Age-bounded: expiry modes that never 401 (login-page 200s,
599
+ // assertion failures) must not replay one stale session forever.
600
+ execution.sessionCache.delete(cacheKey);
601
+ }
602
+ else {
603
+ registerSensitiveValues(execution, Object.values(cached.credential));
604
+ return {
605
+ kind: "connection",
606
+ connection: buildConnection(cached.credential),
607
+ credentialSource: "cache",
608
+ cacheKey,
609
+ };
610
+ }
611
+ }
612
+ const materialized = await materializeFlowCredential(execution, inputs, {
613
+ ...(options.isAbandoned !== undefined ? { isAbandoned: options.isAbandoned } : {}),
614
+ connectionId,
615
+ externalRef: `${execution.provider.id}-${operationId}-self-test`,
616
+ });
617
+ if (!("credential" in materialized)) {
618
+ // Only the multi-turn SKIP is negative-cached. Flow ERRORS
619
+ // (auth_flow_unavailable / auth_flow_failed / invalid credential
620
+ // payloads, or a thrown start/continue) are never memoized: they are
621
+ // typically transient upstream or host failures, so each cycle may
622
+ // retry — permanently caching an error would silently freeze the
623
+ // signal on a blip, while retrying a FAILED request is not a repeated
624
+ // successful login submission.
625
+ if (materialized.kind === "skip" && options.isAbandoned?.() !== true) {
626
+ if (materialized.skipReason === SELF_TEST_AUTH_FLOW_MULTI_TURN_SKIP_REASON) {
627
+ execution.sessionCache.set(cacheKey, { kind: "multi_turn", cachedAtMs: Date.now() });
628
+ }
629
+ else if (materialized.skipReason === SELF_TEST_AUTH_FLOW_REJECTED_SKIP_REASON) {
630
+ execution.sessionCache.set(cacheKey, { kind: "rejected", cachedAtMs: Date.now() });
631
+ }
632
+ }
633
+ return materialized;
195
634
  }
635
+ // A flow that outlived the case deadline still completes here (the timeout
636
+ // only races the promise, it cannot cancel it). The case already reported
637
+ // self_test_timeout — caching this credential would let the next probe
638
+ // reuse a login whose latency just failed the case, hiding the failure.
639
+ if (options.isAbandoned?.() === true) {
640
+ return {
641
+ kind: "flow_error",
642
+ code: "self_test_timeout",
643
+ message: "Auth flow completed after the case deadline; credential discarded.",
644
+ };
645
+ }
646
+ execution.sessionCache.set(cacheKey, {
647
+ kind: "credential",
648
+ credential: materialized.credential,
649
+ cachedAtMs: Date.now(),
650
+ });
196
651
  return {
197
- connection: {
198
- id: `self-test-${execution.requestId}`,
199
- mode: "credentials",
200
- secrets: { ...inputs },
201
- metadata: { purpose: "provider-self-test", operationId },
202
- externalRef: `${execution.provider.id}-${operationId}-self-test`,
203
- },
652
+ kind: "connection",
653
+ connection: buildConnection(materialized.credential),
654
+ credentialSource: "flow",
655
+ cacheKey,
204
656
  };
205
657
  }
658
+ /** A failed probe whose HTTP status is auth-shaped invalidates a cached session once. */
659
+ function isAuthFailureCaseResult(result) {
660
+ return result.status === "failed" && (result.httpStatus === 401 || result.httpStatus === 403);
661
+ }
206
662
  async function executeSelfTestCase(execution, operationId, suite, healthCase) {
207
- const { provider, invoke, sensitiveValues } = execution;
208
- const redact = (text) => redactSelfTestText(text, sensitiveValues);
209
- const startedAt = new Date().toISOString();
210
- const startedAtMs = performance.now();
211
- const finish = (partial) => ({
212
- operationId,
213
- caseName: healthCase.name,
214
- startedAt,
215
- finishedAt: new Date().toISOString(),
216
- responseTimeMs: partial.responseTimeMs ?? Math.max(0, Math.round(performance.now() - startedAtMs)),
217
- ...partial,
218
- });
663
+ const { provider, invoke } = execution;
664
+ // execution.sensitiveValues may grow while the case runs (flow-issued
665
+ // secrets); redact always reads the live array.
666
+ const redact = (text) => redactSelfTestText(text, execution.sensitiveValues);
219
667
  const defaultLabel = redact(healthCase.description ?? healthCase.name);
668
+ const timeoutMs = resolveCaseTimeoutMs(execution, suite, healthCase);
669
+ // One deadline for the WHOLE case: connection materialization (auth flow),
670
+ // the probe, and the one-shot auth retry all draw from the same budget —
671
+ // a 30s case must never take ~4×30s across its stages.
672
+ const caseDeadlineAtMs = performance.now() + timeoutMs;
673
+ const remainingCaseTimeoutMs = () => Math.max(1, Math.ceil(caseDeadlineAtMs - performance.now()));
674
+ const beginCase = () => {
675
+ const startedAt = new Date().toISOString();
676
+ const startedAtMs = performance.now();
677
+ return {
678
+ startedAtMs,
679
+ finish: (partial) => ({
680
+ operationId,
681
+ caseName: healthCase.name,
682
+ startedAt,
683
+ finishedAt: new Date().toISOString(),
684
+ responseTimeMs: partial.responseTimeMs ?? Math.max(0, Math.round(performance.now() - startedAtMs)),
685
+ ...partial,
686
+ }),
687
+ };
688
+ };
689
+ const caseScope = beginCase();
220
690
  if (healthCase.enabled && healthCase.enabled() === false) {
221
- return finish({
691
+ return caseScope.finish({
222
692
  status: "skipped",
223
693
  label: defaultLabel,
224
694
  skipReason: "disabled",
225
695
  });
226
696
  }
227
- const connectionResolution = buildSelfTestConnection(execution, operationId, suite);
228
- if ("skipReason" in connectionResolution) {
229
- return finish({
230
- status: "skipped",
697
+ const resolveConnection = async (forceLogin) => {
698
+ // The timeout only races the flow promise — it cannot cancel it. Once
699
+ // the deadline fires, the still-running resolution is marked abandoned
700
+ // so its late completion cannot write the session cache.
701
+ let abandoned = false;
702
+ try {
703
+ return await withCaseTimeout(() => resolveSelfTestConnection(execution, operationId, suite, {
704
+ forceLogin,
705
+ isAbandoned: () => abandoned,
706
+ }), remainingCaseTimeoutMs());
707
+ }
708
+ catch (error) {
709
+ abandoned = true;
710
+ return {
711
+ kind: "flow_error",
712
+ code: error instanceof SelfTestCaseTimeoutError ? "self_test_timeout" : "auth_flow_failed",
713
+ message: error instanceof Error ? error.message : String(error),
714
+ };
715
+ }
716
+ };
717
+ const nonConnectionResult = (resolution) => {
718
+ if (resolution.kind === "skip") {
719
+ return caseScope.finish({
720
+ status: "skipped",
721
+ label: defaultLabel,
722
+ skipReason: resolution.skipReason,
723
+ });
724
+ }
725
+ return caseScope.finish({
726
+ status: "error",
231
727
  label: defaultLabel,
232
- skipReason: connectionResolution.skipReason,
728
+ error: { code: resolution.code, message: redact(resolution.message) },
233
729
  });
234
- }
235
- const connection = connectionResolution.connection;
236
- const timeoutMs = resolveCaseTimeoutMs(execution, suite, healthCase);
237
- try {
238
- return await withCaseTimeout(async () => {
239
- const resolvedInput = resolveHealthCheckInputDateTokens(healthCase.input);
240
- const preparedInput = healthCase.prepareInput
241
- ? await healthCase.prepareInput({
242
- providerId: provider.id,
730
+ };
731
+ const runProbeAttempt = async (connection) => {
732
+ // gateway.execute keeps its contract — EVERY helper status is returned
733
+ // to the prepareInput hook (it may branch on 401 itself). The last
734
+ // auth-shaped helper status is only RECORDED: if the hook then throws,
735
+ // the case fails WITH that status so stale-session recovery triggers.
736
+ let prepareAuthStatus = null;
737
+ // Share the OUTER case scope: startedAt/responseTimeMs must cover the
738
+ // WHOLE case — auth-flow materialization included — not just the final
739
+ // operation attempt, or a slow login reads as a fast healthy case.
740
+ const { startedAtMs, finish } = caseScope;
741
+ try {
742
+ return await withCaseTimeout(async () => {
743
+ const resolvedInput = resolveHealthCheckInputDateTokens(healthCase.input);
744
+ const preparedInput = healthCase.prepareInput
745
+ ? await healthCase.prepareInput({
746
+ providerId: provider.id,
747
+ operationId,
748
+ input: resolvedInput,
749
+ ...(connection ? { connectionId: connection.id } : {}),
750
+ gateway: {
751
+ execute: async (foreignProviderId, gatewayOperationId, gatewayInput) => {
752
+ if (foreignProviderId !== provider.id) {
753
+ throw new Error(`Self-test prepareInput may only invoke provider "${provider.id}" operations (requested "${foreignProviderId}").`);
754
+ }
755
+ const startedGatewayMs = performance.now();
756
+ const executed = await invoke({
757
+ operationId: gatewayOperationId,
758
+ input: gatewayInput,
759
+ connection,
760
+ requestId: `${execution.requestId}-prepare-${randomUUID()}`,
761
+ });
762
+ if (executed.status === 401 || executed.status === 403) {
763
+ prepareAuthStatus = executed.status;
764
+ }
765
+ return {
766
+ status: executed.status,
767
+ duration: performance.now() - startedGatewayMs,
768
+ data: executed.data,
769
+ meta: executed.meta,
770
+ };
771
+ },
772
+ },
773
+ })
774
+ : resolvedInput;
775
+ const executed = await invoke({
243
776
  operationId,
244
- input: resolvedInput,
245
- ...(connection ? { connectionId: connection.id } : {}),
246
- gateway: {
247
- execute: async (foreignProviderId, gatewayOperationId, gatewayInput) => {
248
- if (foreignProviderId !== provider.id) {
249
- throw new Error(`Self-test prepareInput may only invoke provider "${provider.id}" operations (requested "${foreignProviderId}").`);
250
- }
251
- const startedGatewayMs = performance.now();
252
- const executed = await invoke({
253
- operationId: gatewayOperationId,
254
- input: gatewayInput,
255
- connection,
256
- requestId: `${execution.requestId}-prepare-${randomUUID()}`,
257
- });
258
- return {
259
- status: executed.status,
260
- duration: performance.now() - startedGatewayMs,
261
- data: executed.data,
262
- meta: executed.meta,
263
- };
777
+ input: preparedInput,
778
+ connection,
779
+ requestId: `${execution.requestId}-${randomUUID()}`,
780
+ });
781
+ const durationMs = performance.now() - startedAtMs;
782
+ if (executed.status < 200 || executed.status >= 300) {
783
+ return finish({
784
+ status: "failed",
785
+ label: defaultLabel,
786
+ httpStatus: executed.status,
787
+ error: {
788
+ code: upstreamErrorCode(executed.data) ?? "operation_failed",
789
+ message: redact(upstreamErrorMessage(executed.data) ??
790
+ `Operation invocation failed with status ${executed.status}`),
264
791
  },
265
- },
266
- })
267
- : resolvedInput;
268
- const executed = await invoke({
269
- operationId,
270
- input: preparedInput,
271
- connection,
272
- requestId: `${execution.requestId}-${randomUUID()}`,
273
- });
274
- const durationMs = performance.now() - startedAtMs;
275
- if (executed.status < 200 || executed.status >= 300) {
792
+ });
793
+ }
794
+ const assertionContext = {
795
+ status: executed.status,
796
+ data: executed.data,
797
+ durationMs,
798
+ ...(executed.meta ? { meta: executed.meta } : {}),
799
+ };
800
+ let assertionResult;
801
+ try {
802
+ assertionResult = await healthCase.assertions(assertionContext);
803
+ }
804
+ catch (assertionError) {
805
+ return finish({
806
+ status: "failed",
807
+ label: defaultLabel,
808
+ httpStatus: executed.status,
809
+ assertion: {
810
+ passed: false,
811
+ message: redact(assertionError instanceof Error ? assertionError.message : String(assertionError)),
812
+ },
813
+ });
814
+ }
815
+ const statusValue = objectProperty(assertionResult, "status");
816
+ const overrideStatus = statusValue === "ok" || statusValue === "degraded" ? statusValue : undefined;
817
+ const labelValue = objectProperty(assertionResult, "label");
818
+ const overrideLabel = typeof labelValue === "string" ? redact(labelValue) : undefined;
276
819
  return finish({
277
- status: "failed",
278
- label: defaultLabel,
820
+ status: overrideStatus ?? "ok",
821
+ label: overrideLabel ?? defaultLabel,
279
822
  httpStatus: executed.status,
280
- error: {
281
- code: upstreamErrorCode(executed.data) ?? "operation_failed",
282
- message: redact(upstreamErrorMessage(executed.data) ??
283
- `Operation invocation failed with status ${executed.status}`),
284
- },
823
+ assertion: { passed: true },
824
+ });
825
+ }, remainingCaseTimeoutMs());
826
+ }
827
+ catch (error) {
828
+ if (error instanceof SelfTestCaseTimeoutError) {
829
+ return finish({
830
+ status: "error",
831
+ label: defaultLabel,
832
+ error: { code: "self_test_timeout", message: redact(error.message) },
285
833
  });
286
834
  }
287
- const assertionContext = {
288
- status: executed.status,
289
- data: executed.data,
290
- durationMs,
291
- ...(executed.meta ? { meta: executed.meta } : {}),
292
- };
293
- let assertionResult;
294
- try {
295
- assertionResult = await healthCase.assertions(assertionContext);
296
- }
297
- catch (assertionError) {
835
+ if (prepareAuthStatus !== null) {
298
836
  return finish({
299
837
  status: "failed",
300
838
  label: defaultLabel,
301
- httpStatus: executed.status,
839
+ httpStatus: prepareAuthStatus,
302
840
  assertion: {
303
841
  passed: false,
304
- message: redact(assertionError instanceof Error ? assertionError.message : String(assertionError)),
842
+ message: redact(error instanceof Error ? error.message : String(error)),
305
843
  },
306
844
  });
307
845
  }
308
- const statusValue = objectProperty(assertionResult, "status");
309
- const overrideStatus = statusValue === "ok" || statusValue === "degraded" ? statusValue : undefined;
310
- const labelValue = objectProperty(assertionResult, "label");
311
- const overrideLabel = typeof labelValue === "string" ? redact(labelValue) : undefined;
312
- return finish({
313
- status: overrideStatus ?? "ok",
314
- label: overrideLabel ?? defaultLabel,
315
- httpStatus: executed.status,
316
- assertion: { passed: true },
317
- });
318
- }, timeoutMs);
319
- }
320
- catch (error) {
321
- if (error instanceof SelfTestCaseTimeoutError) {
322
846
  return finish({
323
847
  status: "error",
324
848
  label: defaultLabel,
325
- error: { code: "self_test_timeout", message: redact(error.message) },
849
+ error: {
850
+ code: "self_test_execution_error",
851
+ message: redact(error instanceof Error ? error.message : String(error)),
852
+ },
326
853
  });
327
854
  }
328
- return finish({
329
- status: "error",
330
- label: defaultLabel,
331
- error: {
332
- code: "self_test_execution_error",
333
- message: redact(error instanceof Error ? error.message : String(error)),
334
- },
335
- });
855
+ };
856
+ const resolution = await resolveConnection(false);
857
+ if (resolution.kind !== "connection") {
858
+ return nonConnectionResult(resolution);
859
+ }
860
+ let result = await runProbeAttempt(resolution.connection);
861
+ // One-shot session recovery: a cached credential that fails the probe with
862
+ // an auth-shaped status is invalidated, the flow re-runs ONCE, and the
863
+ // probe retries once. Fresh (just-materialized) credentials never retry.
864
+ if (resolution.credentialSource === "cache" &&
865
+ resolution.cacheKey !== undefined &&
866
+ isAuthFailureCaseResult(result)) {
867
+ execution.sessionCache.delete(resolution.cacheKey);
868
+ const retryResolution = await resolveConnection(true);
869
+ if (retryResolution.kind !== "connection") {
870
+ return nonConnectionResult(retryResolution);
871
+ }
872
+ result = await runProbeAttempt(retryResolution.connection);
873
+ // The retry's fresh credential is subject to the same eviction rule
874
+ // as a first-attempt fresh credential (below).
875
+ if (retryResolution.cacheKey !== undefined && isAuthFailureCaseResult(result)) {
876
+ execution.sessionCache.delete(retryResolution.cacheKey);
877
+ }
878
+ return result;
879
+ }
880
+ // A FRESH credential the probe just rejected is known-bad: evict it so the
881
+ // next cycle logs in anew instead of replaying a guaranteed-stale session
882
+ // once before recovering. (No retry here — fresh credentials never retry.)
883
+ if (resolution.credentialSource === "flow" &&
884
+ resolution.cacheKey !== undefined &&
885
+ isAuthFailureCaseResult(result)) {
886
+ execution.sessionCache.delete(resolution.cacheKey);
336
887
  }
888
+ return result;
337
889
  }
338
890
  function selectCases(provider, request) {
339
891
  const singleCase = request.operationId !== undefined && request.caseName !== undefined;
@@ -420,6 +972,10 @@ export function createSelfTestApp(provider, options) {
420
972
  const app = new Hono();
421
973
  const planDigest = computeSelfTestPlanDigest(provider);
422
974
  const requestBudgetMs = resolveRequestBudgetMs(options);
975
+ // In-process flow-credential session cache (providerId + credentialInputs
976
+ // hash → materialized credential). Lives as long as the app so consecutive
977
+ // probe cycles never log in to the upstream more than once per session.
978
+ const sessionCache = new Map();
423
979
  let busy = false;
424
980
  app.notFound((c) => c.json({ error: { code: "not_found", message: "Not found" } }, 404));
425
981
  app.get(SELF_TEST_HEALTHZ_PATH, (c) => c.json({ ok: true }));
@@ -486,6 +1042,7 @@ export function createSelfTestApp(provider, options) {
486
1042
  const execution = {
487
1043
  provider,
488
1044
  invoke: options.invoke,
1045
+ ...(options.authFlow ? { authFlow: options.authFlow } : {}),
489
1046
  requestId: request.requestId,
490
1047
  credentials: request.credentials?.inputs,
491
1048
  requestTimeoutMs: request.timeoutMs,
@@ -493,6 +1050,7 @@ export function createSelfTestApp(provider, options) {
493
1050
  env: options.env,
494
1051
  credentialInputs: request.credentials?.inputs,
495
1052
  }),
1053
+ sessionCache,
496
1054
  };
497
1055
  const deadline = performance.now() + requestBudgetMs;
498
1056
  const results = [];