diff --git a/docs/contributing/architecture/integrations.md b/docs/contributing/architecture/integrations.md index 8521bd7fdb..25de2749ba 100644 --- a/docs/contributing/architecture/integrations.md +++ b/docs/contributing/architecture/integrations.md @@ -109,6 +109,16 @@ materialized secret's `allowed_hosts` against the token host before the request placeholder resolution. Platform-lane destinations are operator-pinned rows, so no user-secret allowlist applies. +Reconnectable caller-errors (`IntegrationTokenRefreshCallerError`: missing +refresh token, provider HTTP 4xx / `invalid_grant`, missing secrets, +host-approval gaps, invalid connection config) best-effort dispatch +`integration.auth.failed` to the owning user's packages that declare the topic. +Every classified attempt emits; the platform does not coalesce repeats. Provider +HTTP 5xx and missing connections do not emit. The payload is metadata-first +(connection name, lane, reason, optional provider error fields, trusted +`reconnect_url`) and never includes token or secret values. See +[Package subscriptions](../../guides/package-subscriptions.md). + On 401, `createAuthenticatedFetch` calls `integration_token_refresh` then retries with a `{{secret:…}}` placeholder `Authorization` header, so raw tokens never enter the sandbox heap. Package code that triggers refresh through diff --git a/docs/contributing/packages-and-manifests.md b/docs/contributing/packages-and-manifests.md index a19c9a7d3a..9b9134d4f7 100644 --- a/docs/contributing/packages-and-manifests.md +++ b/docs/contributing/packages-and-manifests.md @@ -358,6 +358,15 @@ emit (recursion guard). See [Package subscriptions](../guides/package-subscriptions.md) and [Run records](./architecture/run-records.md). +For reconnectable OAuth refresh failures, `integration.auth.failed` dispatches +best-effort from host-side `refreshIntegrationTokens` +(`createAuthenticatedFetch` 401 retry and explicit `integration_token_refresh`). +The payload is metadata-first (connection name, lane, reason, optional provider +error fields, and a trusted `reconnect_url`); it omits token and secret values. +Every classified attempt emits. Provider HTTP 5xx and missing connections do not +emit. See [Package subscriptions](../guides/package-subscriptions.md) and +[OAuth integrations](./architecture/integrations.md). + Operator system-inbox mail (`system:email` owner) dispatches the separate `email.system-message.received` topic to packages saved by users who hold the admin role at dispatch time, only when the message is accepted. Quarantined diff --git a/docs/guides/README.md b/docs/guides/README.md index 4d263a2bcb..3f0294adcf 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -13,25 +13,25 @@ content: ## Platform guides -| File | Topic | -| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| [what-is-kody.md](./what-is-kody.md) | Pre-account capability tour and discovery-interview notes; needs no account or MCP connection | -| [how-kody-works.md](./how-kody-works.md) | Factory loop as a conversation: ask what your favorite bot shipped, save an export, daily email only when something shipped | -| [google-oauth.md](./google-oauth.md) | Interactive transcript: agent walks a naive user through Lane B Google OAuth for Gmail inbox reading | -| [quick-example.md](./quick-example.md) | **Start here** after a host authorizes: fork a zero-auth example, invoke the owned package, offer optional triggers | -| [first-win.md](./first-win.md) | Optional email → reply → memories loop (not the onboarding Step 2 climax) | -| [package-authoring.md](./package-authoring.md) | General package-authoring guidance, including the README Intent section | -| [package-lifecycle.md](./package-lifecycle.md) | Choose reuse, one-off execute, community fork when close, direct job schedules, or a new durable package | -| [integration-bootstrap.md](./integration-bootstrap.md) | **Start here** for third-party integrations; after the smoke test, prefer a trusted community fork before building | -| [openapi-integrations.md](./openapi-integrations.md) | OpenAPI discover → summarize → scaffold or curated `openapi:` binding (`openapi_integrations`) | -| [secret-backed-integration.md](./secret-backed-integration.md) | Default recipe for non-OAuth integrations that use one or more saved secrets | -| [integration-backed-app-happy-path.md](./integration-backed-app-happy-path.md) | Default package app pattern after integration smoke test passes | -| [package-service-pattern.md](./package-service-pattern.md) | General package-service pattern for native long-lived runtimes inside Kody | -| [package-subscriptions.md](./package-subscriptions.md) | Package subscription manifest shape, discovery, and email / repo lifecycle / run.error.recorded / admin topic payload guidance | -| [platform-friction.md](./platform-friction.md) | Agent self-improvement loop for Kody capability, package, memory, and guide friction | -| [oauth.md](./oauth.md) | **Start here** for third-party OAuth (`/connect/oauth`, redirect URI, params) | -| [account-secret-setup.md](./account-secret-setup.md) | `/account/secrets/new` URL parameters and policies | -| [account-package-invocation-token-setup.md](./account-package-invocation-token-setup.md) | `/account/package-invocation-tokens/new` URL parameters and bearer-token safety policy | +| File | Topic | +| ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [what-is-kody.md](./what-is-kody.md) | Pre-account capability tour and discovery-interview notes; needs no account or MCP connection | +| [how-kody-works.md](./how-kody-works.md) | Factory loop as a conversation: ask what your favorite bot shipped, save an export, daily email only when something shipped | +| [google-oauth.md](./google-oauth.md) | Interactive transcript: agent walks a naive user through Lane B Google OAuth for Gmail inbox reading | +| [quick-example.md](./quick-example.md) | **Start here** after a host authorizes: fork a zero-auth example, invoke the owned package, offer optional triggers | +| [first-win.md](./first-win.md) | Optional email → reply → memories loop (not the onboarding Step 2 climax) | +| [package-authoring.md](./package-authoring.md) | General package-authoring guidance, including the README Intent section | +| [package-lifecycle.md](./package-lifecycle.md) | Choose reuse, one-off execute, community fork when close, direct job schedules, or a new durable package | +| [integration-bootstrap.md](./integration-bootstrap.md) | **Start here** for third-party integrations; after the smoke test, prefer a trusted community fork before building | +| [openapi-integrations.md](./openapi-integrations.md) | OpenAPI discover → summarize → scaffold or curated `openapi:` binding (`openapi_integrations`) | +| [secret-backed-integration.md](./secret-backed-integration.md) | Default recipe for non-OAuth integrations that use one or more saved secrets | +| [integration-backed-app-happy-path.md](./integration-backed-app-happy-path.md) | Default package app pattern after integration smoke test passes | +| [package-service-pattern.md](./package-service-pattern.md) | General package-service pattern for native long-lived runtimes inside Kody | +| [package-subscriptions.md](./package-subscriptions.md) | Package subscription manifest shape, discovery, and email / repo lifecycle / run.error.recorded / integration.auth.failed / admin topic payload guidance | +| [platform-friction.md](./platform-friction.md) | Agent self-improvement loop for Kody capability, package, memory, and guide friction | +| [oauth.md](./oauth.md) | **Start here** for third-party OAuth (`/connect/oauth`, redirect URI, params) | +| [account-secret-setup.md](./account-secret-setup.md) | `/account/secrets/new` URL parameters and policies | +| [account-package-invocation-token-setup.md](./account-package-invocation-token-setup.md) | `/account/package-invocation-tokens/new` URL parameters and bearer-token safety policy | ## Provider guides diff --git a/docs/guides/oauth.md b/docs/guides/oauth.md index 00cea62154..f9859b16eb 100644 --- a/docs/guides/oauth.md +++ b/docs/guides/oauth.md @@ -43,7 +43,9 @@ client ID / client secret form) is skipped and token exchange runs server-side with the operator's credentials. List the available built-in apps with `integration_platform_app_list`. All integrations refresh host-side through `createAuthenticatedFetch`, which calls `integration_token_refresh` on 401 and -retries with a secret placeholder — raw tokens never enter the sandbox. Use +retries with a secret placeholder — raw tokens never enter the sandbox. +Reconnectable refresh failures dispatch `integration.auth.failed` to packages +that subscribe (see [package subscriptions](./package-subscriptions.md)). Use `refreshAccessToken` only for auth that cannot use an Authorization header (WebSockets, SDK constructors, query-param tokens); it still runs in-sandbox for user-owned apps and throws for built-ins. The rest of this guide applies to diff --git a/docs/guides/package-subscriptions.md b/docs/guides/package-subscriptions.md index 65606d4d51..d23add3c78 100644 --- a/docs/guides/package-subscriptions.md +++ b/docs/guides/package-subscriptions.md @@ -5,9 +5,9 @@ summary: Use package.json#kody.subscriptions for package-owned event handlers; discover subscribers with package_subscriptions_list; smoke-test handlers with package_subscription_dispatch; follow metadata-first email, run.error.recorded - activity notifiers, consent-gated admin-only platform.feedback.submitted - notification guidance, and admin-only status.incident.opened / - status.incident.resolved operator telemetry. + activity notifiers, integration.auth.failed reconnect notifiers, consent-gated + admin-only platform.feedback.submitted notification guidance, and admin-only + status.incident.opened / status.incident.resolved operator telemetry. category: platform --- @@ -460,6 +460,58 @@ never emit. Failed `execute` calls do persist and do emit. Use this topic for notifier packages that email, write to Sheets, spawn an agent, or otherwise react when something in the user's account fails. +## `integration.auth.failed` + +When host-side OAuth token refresh fails with reconnectable caller state — +missing refresh token, provider HTTP 4xx / `invalid_grant`, missing secrets, +host-approval gaps, or invalid connection config — Kody dispatches +`integration.auth.failed` to packages saved by that same user that declare the +topic. Every classified attempt emits. The platform does not coalesce repeats; +notifier packages decide how often to ping. Provider HTTP 5xx and missing +connections do not emit. + +Delivery is best-effort after the refresh caller error is classified — there is +no Queue / DLQ for this topic in v1. Failures during subscriber discovery or +package-invocation infrastructure are logged and do not change the refresh error +the caller sees. + +Handlers receive a metadata-first payload: + +```ts +type IntegrationAuthFailedEvent = { + event: 'integration.auth.failed' + event_id: string + integration: { + name: string + lane: 'user' | 'platform' + account_label: string | null + provider: string | null + platform_app_slug: string | null + } + reason: + | 'missing_refresh_token' + | 'provider_rejected' + | 'missing_secret' + | 'host_not_approved' + | 'invalid_config' + provider: { + error: string | null + error_description: string | null + http_status: number | null + } + reconnect_url: string + occurred_at: string +} +``` + +`reconnect_url` is built from the trusted deployment origin and links to +`/connect/oauth?provider=`. The event deliberately omits token values, +secret values, client secrets, and secret names. A short-lived access token that +refreshes cleanly never emits. + +Use this topic for notifier packages that post to Discord, email, or otherwise +ask the owner to reconnect a dead grant. + ## `repo.pushed` When Cloudflare Artifacts reports commits pushed to a Kody-managed Artifacts diff --git a/docs/use/packages.md b/docs/use/packages.md index 3fba4a5cf8..e5d4b32821 100644 --- a/docs/use/packages.md +++ b/docs/use/packages.md @@ -487,7 +487,7 @@ Use the built-in `package_subscriptions_list` capability to discover the signed-in user's saved package subscriptions, optionally filtered by exact topic. This is the generic discovery step before building fan-out, debugging why an event did or did not dispatch, or checking which packages subscribe to -`email.message.received` or `run.error.recorded`. +`email.message.received`, `run.error.recorded`, or `integration.auth.failed`. For accepted stored inbound email, the topic is `email.message.received`. Quarantined inbound email dispatches `email.message.quarantined` instead. Both @@ -508,6 +508,13 @@ metadata-first (run id, surface, identifiers, truncated error fields, and an needed. See [Activity](./activity.md) and the [package subscriptions guide](../guides/package-subscriptions.md). +When host-side OAuth token refresh fails with reconnectable caller state, Kody +dispatches `integration.auth.failed` to your packages that declare that topic. +The payload is metadata-first (connection name, lane, reason, optional provider +error fields, and a trusted `reconnect_url`). Every classified attempt emits; +notifier packages decide how often to ping. See the +[package subscriptions guide](../guides/package-subscriptions.md). + Artifacts-backed plain repos, packages, and job sources also emit `repo.pushed`, `repo.created`, and `repo.deleted` when Cloudflare Artifacts reports those lifecycle events. Session workspace branch pushes (`sessions/`) do not fan diff --git a/docs/use/synthetic-event-dispatch.md b/docs/use/synthetic-event-dispatch.md index b604a8f8b9..5c6e5b3e9b 100644 --- a/docs/use/synthetic-event-dispatch.md +++ b/docs/use/synthetic-event-dispatch.md @@ -66,7 +66,8 @@ intended owner-scoped package. adds `synthetic: true`). Shape depends on the topic: - **Platform-owned topics** (`email.message.received`, `run.error.recorded`, - `repo.pushed`, …) — use the metadata-first payloads documented in the + `integration.auth.failed`, `repo.pushed`, …) — use the metadata-first payloads + documented in the [package subscriptions guide](../guides/package-subscriptions.md). Include only fields your handler reads. - **Package-emitted topics** (`@scope/topic.name`) — use the @@ -108,6 +109,34 @@ Example minimal `run.error.recorded` fixture: } ``` +Example minimal `integration.auth.failed` fixture: + +```json +{ + "kody_id": "integration-auth-notifier", + "topic": "integration.auth.failed", + "params": { + "event": "integration.auth.failed", + "event_id": "00000000-0000-4000-8000-000000000001", + "integration": { + "name": "google", + "lane": "platform", + "account_label": null, + "provider": "google", + "platform_app_slug": "google" + }, + "reason": "provider_rejected", + "provider": { + "error": "invalid_grant", + "error_description": "Token has been expired or revoked.", + "http_status": 400 + }, + "reconnect_url": "https://kody.codes/connect/oauth?provider=google", + "occurred_at": "2026-08-18T17:00:00.000Z" + } +} +``` + ### Stored-mail replay (`email_message_id`) For email topics, pass a stored message id instead of hand-building metadata: diff --git a/packages/worker/src/integrations/package-subscriptions.node.test.ts b/packages/worker/src/integrations/package-subscriptions.node.test.ts new file mode 100644 index 0000000000..0bd92e213b --- /dev/null +++ b/packages/worker/src/integrations/package-subscriptions.node.test.ts @@ -0,0 +1,256 @@ +import { expect, test, vi } from 'vitest' +import { consoleWarn } from '#worker/test-support/console-spies.ts' + +const mocks = vi.hoisted(() => ({ + invokePackageSubscription: vi.fn(async () => ({ status: 200, body: {} })), + listSavedPackagesByUserId: vi.fn(), + loadPackageManifestBySourceId: vi.fn(), +})) + +vi.mock('#worker/package-invocations/service.ts', () => ({ + invokePackageSubscription: mocks.invokePackageSubscription, +})) + +vi.mock('#worker/package-registry/repo.ts', () => ({ + listSavedPackagesByUserId: mocks.listSavedPackagesByUserId, +})) + +vi.mock('#worker/package-registry/source.ts', () => ({ + loadPackageManifestBySourceId: mocks.loadPackageManifestBySourceId, +})) + +const { + dispatchIntegrationAuthFailedSubscriptionEvents, + integrationAuthFailedTopic, +} = await import('./package-subscriptions.ts') + +function createEnv() { + return { + APP_DB: {}, + BUNDLE_ARTIFACTS_KV: {}, + APP_BASE_URL: 'https://example.com', + } as Env +} + +function subscribedManifest(input: { + name: string + kodyId: string + handler?: string +}) { + return { + manifest: { + name: input.name, + kody: { + id: input.kodyId, + description: 'Auth notifier', + subscriptions: { + [integrationAuthFailedTopic]: { + handler: input.handler ?? './src/on-integration-auth-failed.ts', + }, + }, + }, + }, + } +} + +test('integration.auth.failed fans out only to owning-user packages with a lean payload', async () => { + const savedPackage = { + id: 'package-1', + userId: 'user-1', + sourceId: 'source-1', + kodyId: 'auth-notifier', + name: '@user/auth-notifier', + } + mocks.listSavedPackagesByUserId.mockResolvedValueOnce([savedPackage]) + mocks.loadPackageManifestBySourceId.mockResolvedValueOnce( + subscribedManifest({ + name: '@user/auth-notifier', + kodyId: 'auth-notifier', + }), + ) + const env = createEnv() + + const results = await dispatchIntegrationAuthFailedSubscriptionEvents({ + env, + userId: 'user-1', + eventId: 'event-1', + occurredAt: '2026-08-18T17:00:00.000Z', + integration: { + name: 'google', + lane: 'platform', + account_label: 'Work', + provider: 'google', + platform_app_slug: 'google', + }, + reason: 'provider_rejected', + provider: { + error: 'invalid_grant', + error_description: 'Token has been expired or revoked.', + http_status: 400, + }, + }) + + expect(results).toHaveLength(1) + expect(mocks.listSavedPackagesByUserId).toHaveBeenCalledWith(env.APP_DB, { + userId: 'user-1', + }) + expect(mocks.invokePackageSubscription).toHaveBeenCalledWith( + expect.objectContaining({ + savedPackage, + topic: integrationAuthFailedTopic, + idempotencyKey: `integration-auth-failed:event-1:package-1`, + source: 'integrations', + params: { + event: integrationAuthFailedTopic, + event_id: 'event-1', + integration: { + name: 'google', + lane: 'platform', + account_label: 'Work', + provider: 'google', + platform_app_slug: 'google', + }, + reason: 'provider_rejected', + provider: { + error: 'invalid_grant', + error_description: 'Token has been expired or revoked.', + http_status: 400, + }, + reconnect_url: 'https://example.com/connect/oauth?provider=google', + occurred_at: '2026-08-18T17:00:00.000Z', + }, + }), + ) + const params = mocks.invokePackageSubscription.mock.calls[0]?.[0]?.params as + | Record + | undefined + expect(params).not.toHaveProperty('access_token') + expect(params).not.toHaveProperty('refresh_token') + expect(params).not.toHaveProperty('client_secret') +}) + +test('integration.auth.failed never throws on discovery or handler failures', async () => { + consoleWarn.mockImplementation(() => {}) + mocks.invokePackageSubscription.mockReset() + mocks.listSavedPackagesByUserId.mockReset() + mocks.loadPackageManifestBySourceId.mockReset() + const env = createEnv() + + mocks.listSavedPackagesByUserId.mockRejectedValueOnce( + new Error('D1 unavailable'), + ) + await expect( + dispatchIntegrationAuthFailedSubscriptionEvents({ + env, + userId: 'user-1', + eventId: 'event-2', + occurredAt: '2026-08-18T17:00:00.000Z', + integration: { + name: 'google', + lane: 'user', + account_label: null, + provider: 'google', + platform_app_slug: null, + }, + reason: 'missing_refresh_token', + provider: { + error: null, + error_description: null, + http_status: null, + }, + }), + ).resolves.toEqual([]) + expect(mocks.invokePackageSubscription).not.toHaveBeenCalled() + expect(consoleWarn).toHaveBeenCalledWith( + 'integration.auth.failed package subscription discovery incomplete', + expect.objectContaining({ + eventId: 'event-2', + integrationName: 'google', + errorCount: 1, + }), + ) + const discoveryWarn = consoleWarn.mock.calls.find( + (call) => + call[0] === + 'integration.auth.failed package subscription discovery incomplete', + )?.[1] as Record | undefined + expect(discoveryWarn).not.toHaveProperty('userId') + + const matchingPackage = { + id: 'package-1', + userId: 'user-1', + sourceId: 'source-1', + kodyId: 'auth-notifier', + name: '@user/auth-notifier', + } + const brokenPackage = { + id: 'package-2', + userId: 'user-1', + sourceId: 'source-2', + kodyId: 'broken', + name: '@user/broken', + } + const sibling = { + id: 'package-3', + userId: 'user-1', + sourceId: 'source-3', + kodyId: 'notifier-b', + name: '@user/notifier-b', + } + mocks.listSavedPackagesByUserId.mockResolvedValueOnce([ + matchingPackage, + brokenPackage, + sibling, + ]) + mocks.loadPackageManifestBySourceId + .mockResolvedValueOnce( + subscribedManifest({ + name: '@user/auth-notifier', + kodyId: 'auth-notifier', + }), + ) + .mockRejectedValueOnce(new Error('manifest unavailable')) + .mockResolvedValueOnce( + subscribedManifest({ + name: '@user/notifier-b', + kodyId: 'notifier-b', + }), + ) + mocks.invokePackageSubscription + .mockRejectedValueOnce(new Error('handler boom')) + .mockResolvedValueOnce({ status: 200, body: { ok: true } }) + + await expect( + dispatchIntegrationAuthFailedSubscriptionEvents({ + env, + userId: 'user-1', + eventId: 'event-3', + occurredAt: '2026-08-18T17:00:00.000Z', + integration: { + name: 'google', + lane: 'platform', + account_label: null, + provider: 'google', + platform_app_slug: 'google', + }, + reason: 'provider_rejected', + provider: { + error: 'invalid_grant', + error_description: null, + http_status: 400, + }, + }), + ).resolves.toEqual([null, { status: 200, body: { ok: true } }]) + expect(mocks.invokePackageSubscription).toHaveBeenCalledTimes(2) + expect(consoleWarn).toHaveBeenCalledWith( + 'integration.auth.failed package subscription invoke failed', + expect.objectContaining({ + eventId: 'event-3', + error: expect.any(Error), + }), + ) + expect(consoleWarn).toHaveBeenCalledWith( + 'Failed to load package manifest for integration.auth.failed subscription', + expect.objectContaining({ packageId: 'package-2' }), + ) +}) diff --git a/packages/worker/src/integrations/package-subscriptions.ts b/packages/worker/src/integrations/package-subscriptions.ts new file mode 100644 index 0000000000..7b18be428a --- /dev/null +++ b/packages/worker/src/integrations/package-subscriptions.ts @@ -0,0 +1,221 @@ +import { getAppBaseUrl } from '#worker/app-base-url.ts' +import { runWithDynamicWorkerEvaluationBudget } from '#mcp/executor.ts' +import { readPreExecutionPackageInvocationInfrastructureCode } from '#worker/package-invocations/admin-package-subscriptions.ts' +import { invokePackageSubscription } from '#worker/package-invocations/service.ts' +import { listPackageSubscriptions } from '#worker/package-registry/manifest.ts' +import { listSavedPackagesByUserId } from '#worker/package-registry/repo.ts' +import { loadPackageManifestBySourceId } from '#worker/package-registry/source.ts' +import { type SavedPackageRecord } from '#worker/package-registry/types.ts' +import { type IntegrationAuthFailedReason } from './token-refresh.ts' + +export const integrationAuthFailedTopic = 'integration.auth.failed' + +export type IntegrationAuthFailedSubscriptionEnvelope = { + event: typeof integrationAuthFailedTopic + event_id: string + integration: { + name: string + lane: 'user' | 'platform' + account_label: string | null + provider: string | null + platform_app_slug: string | null + } + reason: IntegrationAuthFailedReason + provider: { + error: string | null + error_description: string | null + http_status: number | null + } + reconnect_url: string + occurred_at: string +} + +type LoadedAuthFailedSubscription = { + savedPackage: SavedPackageRecord + subscription: ReturnType[number] +} + +export function buildIntegrationAuthFailedReconnectUrl(input: { + baseUrl: string + integrationName: string +}) { + return `${input.baseUrl}/connect/oauth?provider=${encodeURIComponent(input.integrationName)}` +} + +function buildSubscriptionIdempotencyKey(input: { + eventId: string + packageId: string +}) { + return `integration-auth-failed:${input.eventId}:${input.packageId}` +} + +function buildEventPayload(input: { + baseUrl: string + eventId: string + occurredAt: string + integration: IntegrationAuthFailedSubscriptionEnvelope['integration'] + reason: IntegrationAuthFailedReason + provider: IntegrationAuthFailedSubscriptionEnvelope['provider'] +}): IntegrationAuthFailedSubscriptionEnvelope { + return { + event: integrationAuthFailedTopic, + event_id: input.eventId, + integration: input.integration, + reason: input.reason, + provider: input.provider, + reconnect_url: buildIntegrationAuthFailedReconnectUrl({ + baseUrl: input.baseUrl, + integrationName: input.integration.name, + }), + occurred_at: input.occurredAt, + } +} + +async function loadMatchingAuthFailedSubscriptions(input: { + env: Pick + baseUrl: string + userId: string +}) { + let savedPackages: Array + try { + savedPackages = await listSavedPackagesByUserId(input.env.APP_DB, { + userId: input.userId, + }) + } catch (error) { + const missingTable = + error instanceof Error && + error.message.includes('no such table: saved_packages') + return { + subscriptions: [] as Array, + discoveryErrors: missingTable ? [] : [error], + } + } + const settled = await Promise.allSettled( + savedPackages.map(async (savedPackage) => { + const loaded = await loadPackageManifestBySourceId({ + env: input.env as Env, + baseUrl: input.baseUrl, + userId: input.userId, + sourceId: savedPackage.sourceId, + }) + const subscription = listPackageSubscriptions(loaded.manifest).find( + (candidate) => candidate.topic === integrationAuthFailedTopic, + ) + if (!subscription) return null + return { + savedPackage, + subscription, + } satisfies LoadedAuthFailedSubscription + }), + ) + const subscriptions: Array = [] + const discoveryErrors: Array = [] + for (const [index, result] of settled.entries()) { + if (result.status === 'fulfilled') { + if (result.value) subscriptions.push(result.value) + continue + } + const savedPackage = savedPackages[index] + console.warn( + 'Failed to load package manifest for integration.auth.failed subscription', + { + sourceId: savedPackage?.sourceId, + packageId: savedPackage?.id, + error: result.reason, + }, + ) + discoveryErrors.push(result.reason) + } + return { subscriptions, discoveryErrors } +} + +/** + * Fan a reconnectable OAuth refresh failure out to the owning user's packages + * that declare `integration.auth.failed`. Best-effort: discovery and invocation + * infrastructure failures are logged, never thrown — the refresh caller must + * still receive the original error. Sibling handler terminal failures are + * isolated via `Promise.allSettled`. + * + * Every classified caller-error emits. The platform does not coalesce repeats; + * notifier packages decide how often to ping. + */ +export async function dispatchIntegrationAuthFailedSubscriptionEvents(input: { + env: Pick + userId: string + eventId: string + occurredAt: string + integration: IntegrationAuthFailedSubscriptionEnvelope['integration'] + reason: IntegrationAuthFailedReason + provider: IntegrationAuthFailedSubscriptionEnvelope['provider'] + waitUntil?: (promise: Promise) => void +}) { + const baseUrl = getAppBaseUrl({ env: input.env }) + const { subscriptions, discoveryErrors } = + await loadMatchingAuthFailedSubscriptions({ + env: input.env, + baseUrl, + userId: input.userId, + }) + const eventPayload = buildEventPayload({ + baseUrl, + eventId: input.eventId, + occurredAt: input.occurredAt, + integration: input.integration, + reason: input.reason, + provider: input.provider, + }) + const settled = await runWithDynamicWorkerEvaluationBudget( + async () => + await Promise.allSettled( + subscriptions.map(async ({ savedPackage }) => { + const response = await invokePackageSubscription({ + env: input.env as Env, + baseUrl, + savedPackage, + topic: integrationAuthFailedTopic, + params: eventPayload as Record, + idempotencyKey: buildSubscriptionIdempotencyKey({ + eventId: input.eventId, + packageId: savedPackage.id, + }), + source: 'integrations', + waitUntil: input.waitUntil, + }) + const retryableCode = + readPreExecutionPackageInvocationInfrastructureCode(response) + if (retryableCode) { + throw new Error( + `Retryable package invocation infrastructure response: ${retryableCode}.`, + ) + } + return response + }), + ), + ) + for (const result of settled) { + if (result.status === 'rejected') { + console.warn( + 'integration.auth.failed package subscription invoke failed', + { + eventId: input.eventId, + integrationName: input.integration.name, + error: result.reason, + }, + ) + } + } + if (discoveryErrors.length > 0) { + console.warn( + 'integration.auth.failed package subscription discovery incomplete', + { + eventId: input.eventId, + integrationName: input.integration.name, + errorCount: discoveryErrors.length, + error: discoveryErrors[0], + }, + ) + } + return settled.map((result) => + result.status === 'fulfilled' ? result.value : null, + ) +} diff --git a/packages/worker/src/integrations/token-refresh.node.test.ts b/packages/worker/src/integrations/token-refresh.node.test.ts index 82acf2b4ec..0f8d545233 100644 --- a/packages/worker/src/integrations/token-refresh.node.test.ts +++ b/packages/worker/src/integrations/token-refresh.node.test.ts @@ -10,11 +10,22 @@ import { createD1FromSqlite } from '#worker/test-support/create-d1-from-sqlite.t import { createInMemoryUserMeterEnv } from '#worker/test-support/user-meter.ts' import { upsertPlatformOauthApp } from './platform-apps.ts' import { upsertIntegration, upsertPlatformIntegration } from './service.ts' -import { + +const mocks = vi.hoisted(() => ({ + dispatchIntegrationAuthFailedSubscriptionEvents: vi.fn(async () => []), +})) + +vi.mock('./package-subscriptions.ts', () => ({ + dispatchIntegrationAuthFailedSubscriptionEvents: + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + integrationAuthFailedTopic: 'integration.auth.failed', +})) + +const { IntegrationTokenRefreshCallerError, integrationTokenRefreshCallerMarker, refreshIntegrationTokens, -} from './token-refresh.ts' +} = await import('./token-refresh.ts') const migrationsDirectory = new URL('../../migrations/', import.meta.url) @@ -131,10 +142,29 @@ test('platform-lane refresh uses the decrypted shared client secret and persists storageContext, }) expect(refresh.found && refresh.value).toBe('rotated-refresh-token') + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).not.toHaveBeenCalled() } finally { vi.unstubAllGlobals() } + mocks.dispatchIntegrationAuthFailedSubscriptionEvents.mockClear() + await expect( + refreshIntegrationTokens({ + env, + userId, + name: 'missing-connection', + }), + ).rejects.toSatisfy( + (error: unknown) => + error instanceof IntegrationTokenRefreshCallerError && + error.reason === 'not_found', + ) + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).not.toHaveBeenCalled() + await upsertPlatformIntegration({ env, userId: 'user-no-refresh', @@ -142,6 +172,7 @@ test('platform-lane refresh uses the decrypted shared client secret and persists scopes: [], accessTokenSecretName: 'githubAccessToken', }) + mocks.dispatchIntegrationAuthFailedSubscriptionEvents.mockClear() await expect( refreshIntegrationTokens({ env, @@ -151,10 +182,23 @@ test('platform-lane refresh uses the decrypted shared client secret and persists ).rejects.toSatisfy( (error: unknown) => error instanceof IntegrationTokenRefreshCallerError && + error.reason === 'missing_refresh_token' && error.message.includes('does not define a refresh token secret name') && error.message.includes('/connect/oauth?provider=github') && error.message.includes(integrationTokenRefreshCallerMarker), ) + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-no-refresh', + reason: 'missing_refresh_token', + integration: expect.objectContaining({ + name: 'github', + lane: 'platform', + }), + }), + ) }) test('provider HTTP status classifies refresh failures as caller errors or Sentry-visible Errors', async () => { @@ -203,23 +247,51 @@ test('provider HTTP status classifies refresh failures as caller errors or Sentr headers: { 'Content-Type': 'application/json' }, }), ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ access_token: '' }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ) vi.stubGlobal('fetch', fetchMock) try { + mocks.dispatchIntegrationAuthFailedSubscriptionEvents.mockClear() + const waitUntil = vi.fn() await expect( refreshIntegrationTokens({ env, userId, name: 'google', + waitUntil, }), ).rejects.toSatisfy( (error: unknown) => error instanceof IntegrationTokenRefreshCallerError && + error.reason === 'provider_rejected' && + error.providerError === 'invalid_grant' && + error.httpStatus === 400 && error.message.includes('HTTP 400') && error.message.includes('invalid_grant') && error.message.includes('/connect/oauth?provider=google') && error.message.includes(integrationTokenRefreshCallerMarker), ) + expect(waitUntil).toHaveBeenCalledTimes(1) + await waitUntil.mock.calls[0]?.[0] + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).toHaveBeenCalledWith( + expect.objectContaining({ + userId, + reason: 'provider_rejected', + provider: { + error: 'invalid_grant', + error_description: 'Token has been expired or revoked.', + http_status: 400, + }, + }), + ) + mocks.dispatchIntegrationAuthFailedSubscriptionEvents.mockClear() await expect( refreshIntegrationTokens({ env, @@ -232,6 +304,30 @@ test('provider HTTP status classifies refresh failures as caller errors or Sentr !(error instanceof IntegrationTokenRefreshCallerError) && error.message.includes('HTTP 503'), ) + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).not.toHaveBeenCalled() + + mocks.dispatchIntegrationAuthFailedSubscriptionEvents.mockClear() + await expect( + refreshIntegrationTokens({ + env, + userId, + name: 'google', + }), + ).rejects.toSatisfy( + (error: unknown) => + error instanceof IntegrationTokenRefreshCallerError && + error.reason === 'provider_rejected' && + error.message.includes('did not return an access_token'), + ) + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).toHaveBeenCalledWith( + expect.objectContaining({ + reason: 'provider_rejected', + }), + ) } finally { vi.unstubAllGlobals() } @@ -289,17 +385,30 @@ test('user-lane refresh resolves the client secret from the user secret store', const fetchMock = stubTokenEndpoint({ access_token: 'fresh-google-token' }) try { + mocks.dispatchIntegrationAuthFailedSubscriptionEvents.mockClear() await expect( refreshIntegrationTokens({ env, userId, name: 'google' }), ).rejects.toSatisfy( (error: unknown) => error instanceof IntegrationTokenRefreshCallerError && + error.reason === 'host_not_approved' && error.message.includes( 'Secret "googleRefreshToken" is not approved for host "oauth2.googleapis.com"', ) && error.message.includes(integrationTokenRefreshCallerMarker), ) expect(fetchMock).not.toHaveBeenCalled() + expect( + mocks.dispatchIntegrationAuthFailedSubscriptionEvents, + ).toHaveBeenCalledWith( + expect.objectContaining({ + reason: 'host_not_approved', + integration: expect.objectContaining({ + name: 'google', + lane: 'user', + }), + }), + ) await approveSecretHosts(env, userId, 'googleRefreshToken', [ 'oauth2.googleapis.com', diff --git a/packages/worker/src/integrations/token-refresh.ts b/packages/worker/src/integrations/token-refresh.ts index 866a6b624d..8b7580e1be 100644 --- a/packages/worker/src/integrations/token-refresh.ts +++ b/packages/worker/src/integrations/token-refresh.ts @@ -6,12 +6,36 @@ import { } from './oauth-token-exchange.ts' import { getPlatformOauthAppClientSecret } from './platform-apps.ts' import { getJoinedIntegration } from './service.ts' +import { type JoinedIntegration } from './types.ts' export type IntegrationTokenRefreshResult = { refreshedAt: string refreshTokenRotated: boolean } +export const integrationAuthFailedReasons = [ + 'missing_refresh_token', + 'provider_rejected', + 'missing_secret', + 'host_not_approved', + 'invalid_config', +] as const + +export type IntegrationAuthFailedReason = + (typeof integrationAuthFailedReasons)[number] + +export type IntegrationTokenRefreshCallerReason = + | IntegrationAuthFailedReason + | 'not_found' + +export type IntegrationAuthFailedSnapshot = { + name: string + lane: 'user' | 'platform' + accountLabel: string | null + provider: string | null + platformAppSlug: string | null +} + /** * Caller-clearable token-refresh failures: missing refresh token on the * connection, revoked/expired provider grant (HTTP 4xx), host-approval gaps, @@ -19,9 +43,37 @@ export type IntegrationTokenRefreshResult = { * `McpCallerError` so agents get a clear next step and Sentry stays quiet. */ export class IntegrationTokenRefreshCallerError extends Error { - constructor(message: string, options?: ErrorOptions) { - super(message, options) + readonly reason: IntegrationTokenRefreshCallerReason + readonly providerError: string | null + readonly providerErrorDescription: string | null + readonly httpStatus: number | null + readonly integration: IntegrationAuthFailedSnapshot | null + + constructor( + message: string, + options: ErrorOptions & { + reason: IntegrationTokenRefreshCallerReason + providerError?: string | null + providerErrorDescription?: string | null + httpStatus?: number | null + integration?: IntegrationAuthFailedSnapshot | null + }, + ) { + const { + reason, + providerError, + providerErrorDescription, + httpStatus, + integration, + ...errorOptions + } = options + super(message, errorOptions) this.name = 'IntegrationTokenRefreshCallerError' + this.reason = reason + this.providerError = providerError ?? null + this.providerErrorDescription = providerErrorDescription ?? null + this.httpStatus = httpStatus ?? null + this.integration = integration ?? null } } @@ -38,7 +90,16 @@ export function isIntegrationTokenRefreshCallerMessage(message: string) { return message.includes(integrationTokenRefreshCallerMarker) } -function callerRefreshError(message: string, options?: ErrorOptions) { +function callerRefreshError( + message: string, + options: ErrorOptions & { + reason: IntegrationTokenRefreshCallerReason + providerError?: string | null + providerErrorDescription?: string | null + httpStatus?: number | null + integration?: IntegrationAuthFailedSnapshot | null + }, +) { return new IntegrationTokenRefreshCallerError( `${message} ${integrationTokenRefreshCallerMarker}`, options, @@ -49,19 +110,84 @@ function connectOauthPath(integrationName: string) { return `/connect/oauth?provider=${encodeURIComponent(integrationName)}` } -function formatProviderTokenError(payload: Record | null) { - if (!payload) return null +function snapshotJoinedIntegration( + joined: JoinedIntegration, +): IntegrationAuthFailedSnapshot { + return { + name: joined.connection.name, + lane: joined.lane, + accountLabel: joined.connection.accountLabel, + provider: joined.app.provider, + platformAppSlug: joined.connection.platformAppSlug, + } +} + +function readProviderTokenError(payload: Record | null) { + if (!payload) { + return { error: null, description: null } + } const error = typeof payload.error === 'string' ? payload.error.trim().slice(0, 80) : '' const description = typeof payload.error_description === 'string' ? payload.error_description.trim().slice(0, 200) : '' + return { + error: error || null, + description: description || null, + } +} + +function formatProviderTokenError(payload: Record | null) { + const { error, description } = readProviderTokenError(payload) if (!error && !description) return null if (error && description) return `${error}: ${description}` return error || description } +async function emitIntegrationAuthFailedEvent(input: { + env: Env + userId: string + error: IntegrationTokenRefreshCallerError + waitUntil?: (promise: Promise) => void +}) { + const snapshot = input.error.integration + if (!snapshot) return + if (input.error.reason === 'not_found') return + try { + const { dispatchIntegrationAuthFailedSubscriptionEvents } = + await import('./package-subscriptions.ts') + await dispatchIntegrationAuthFailedSubscriptionEvents({ + env: input.env, + userId: input.userId, + eventId: crypto.randomUUID(), + occurredAt: new Date().toISOString(), + integration: { + name: snapshot.name, + lane: snapshot.lane, + account_label: snapshot.accountLabel, + provider: snapshot.provider, + platform_app_slug: snapshot.platformAppSlug, + }, + reason: input.error.reason, + provider: { + error: input.error.providerError, + error_description: input.error.providerErrorDescription, + http_status: input.error.httpStatus, + }, + waitUntil: input.waitUntil, + }) + } catch (error) { + console.warn( + 'integration.auth.failed package subscription dispatch failed', + { + integrationName: snapshot.name, + error, + }, + ) + } +} + /** * Host-side OAuth token refresh. Runs entirely in the Worker: the refresh * token and client secret are materialized here (never in the sandbox), the @@ -71,12 +197,42 @@ function formatProviderTokenError(payload: Record | null) { * This is the only refresh path for platform-app connections, whose shared * client secret has no user-facing secret name by design. User-lane * connections may also refresh here (`integration_token_refresh`). + * + * Reconnectable caller-errors emit `integration.auth.failed` once per attempt. + * The platform does not swallow repeats. */ export async function refreshIntegrationTokens(input: { env: Env userId: string userEmail?: string | undefined name: string + waitUntil?: (promise: Promise) => void +}): Promise { + try { + return await refreshIntegrationTokensOrThrow(input) + } catch (error) { + if (error instanceof IntegrationTokenRefreshCallerError) { + const pending = emitIntegrationAuthFailedEvent({ + env: input.env, + userId: input.userId, + error, + waitUntil: input.waitUntil, + }) + if (input.waitUntil) { + input.waitUntil(pending) + } else { + await pending + } + } + throw error + } +} + +async function refreshIntegrationTokensOrThrow(input: { + env: Env + userId: string + userEmail?: string | undefined + name: string }): Promise { const joined = await getJoinedIntegration({ env: input.env, @@ -84,26 +240,45 @@ export async function refreshIntegrationTokens(input: { name: input.name, }) if (!joined) { - throw callerRefreshError(`Integration "${input.name}" was not found.`) + throw callerRefreshError(`Integration "${input.name}" was not found.`, { + reason: 'not_found', + }) } const { app, connection } = joined + const integration = snapshotJoinedIntegration(joined) const reconnectPath = connectOauthPath(connection.name) + const fail = ( + message: string, + options: { + reason: IntegrationAuthFailedReason + providerError?: string | null + providerErrorDescription?: string | null + httpStatus?: number | null + }, + ) => + callerRefreshError(message, { + ...options, + integration, + }) const clientId = app.clientId.trim() if (!clientId) { - throw callerRefreshError( + throw fail( `Integration "${connection.name}" does not define a client id. Reconnect at ${reconnectPath}.`, + { reason: 'invalid_config' }, ) } const refreshTokenSecretName = connection.refreshTokenSecretName?.trim() ?? '' if (!refreshTokenSecretName) { - throw callerRefreshError( + throw fail( `Integration "${connection.name}" does not define a refresh token secret name. This connection cannot refresh; reconnect at ${reconnectPath} if the provider issues a refresh token, or stop calling integration_token_refresh for this integration.`, + { reason: 'missing_refresh_token' }, ) } const accessTokenSecretName = connection.accessTokenSecretName.trim() if (!accessTokenSecretName) { - throw callerRefreshError( + throw fail( `Integration "${connection.name}" does not define an access token secret name. Reconnect at ${reconnectPath}.`, + { reason: 'missing_secret' }, ) } @@ -115,9 +290,9 @@ export async function refreshIntegrationTokens(input: { // rows, so no user-secret allowlist applies. const tokenHost = safeParseHost(app.tokenUrl) if (!tokenHost) { - throw callerRefreshError( - `Integration "${connection.name}" has an invalid token URL.`, - ) + throw fail(`Integration "${connection.name}" has an invalid token URL.`, { + reason: 'invalid_config', + }) } const assertUserSecretAllowedForTokenHost = ( secretName: string, @@ -125,8 +300,9 @@ export async function refreshIntegrationTokens(input: { ) => { if (joined.lane !== 'user') return if (allowedHosts.includes(tokenHost)) return - throw callerRefreshError( + throw fail( `Secret "${secretName}" is not approved for host "${tokenHost}". Approve the host on /account/secrets before refreshing this integration.`, + { reason: 'host_not_approved' }, ) } @@ -138,8 +314,9 @@ export async function refreshIntegrationTokens(input: { storageContext, }) if (!refreshTokenSecret.found || !refreshTokenSecret.value) { - throw callerRefreshError( + throw fail( `Refresh token secret "${refreshTokenSecretName}" was not found. Reconnect at ${reconnectPath}.`, + { reason: 'missing_refresh_token' }, ) } assertUserSecretAllowedForTokenHost( @@ -162,8 +339,9 @@ export async function refreshIntegrationTokens(input: { const clientSecretSecretName = joined.app.clientSecretSecretName?.trim() ?? '' if (!clientSecretSecretName) { - throw callerRefreshError( + throw fail( `Integration "${connection.name}" uses confidential flow but does not define a client secret secret name.`, + { reason: 'missing_secret' }, ) } const resolved = await resolveSecret({ @@ -190,8 +368,9 @@ export async function refreshIntegrationTokens(input: { } } if (!clientSecret) { - throw callerRefreshError( + throw fail( `Client secret for integration "${connection.name}" was not found.`, + { reason: 'missing_secret' }, ) } } @@ -225,23 +404,35 @@ export async function refreshIntegrationTokens(input: { unknown > | null if (!response.ok) { + const provider = readProviderTokenError(payload) const providerDetail = formatProviderTokenError(payload) const detailSuffix = providerDetail ? ` (${providerDetail})` : '' // Provider 4xx is almost always revoked/expired grant or bad client // state the user (or operator) clears by reconnecting — not a platform // defect worth a Sentry issue. 5xx stays a plain Error for visibility. if (response.status >= 400 && response.status < 500) { - throw callerRefreshError( + throw fail( `Token refresh was rejected for integration "${connection.name}" with HTTP ${response.status}${detailSuffix}. Reconnect at ${reconnectPath}.`, + { + reason: 'provider_rejected', + providerError: provider.error, + providerErrorDescription: provider.description, + httpStatus: response.status, + }, ) } throw new Error( `Token refresh failed for integration "${connection.name}" with HTTP ${response.status}${detailSuffix}.`, ) } - if (!payload || typeof payload.access_token !== 'string') { - throw callerRefreshError( + if ( + !payload || + typeof payload.access_token !== 'string' || + payload.access_token.length === 0 + ) { + throw fail( `Token refresh for integration "${connection.name}" did not return an access_token. Reconnect at ${reconnectPath}.`, + { reason: 'provider_rejected' }, ) } diff --git a/packages/worker/src/mcp/capabilities/integrations/integration-token-refresh.ts b/packages/worker/src/mcp/capabilities/integrations/integration-token-refresh.ts index 4c48903bd1..abf583a74e 100644 --- a/packages/worker/src/mcp/capabilities/integrations/integration-token-refresh.ts +++ b/packages/worker/src/mcp/capabilities/integrations/integration-token-refresh.ts @@ -53,6 +53,7 @@ export const integrationTokenRefreshCapability = defineDomainCapability( userId: user.userId, userEmail: user.email, name: args.name, + waitUntil: ctx.waitUntil, }) return { ok: true as const, diff --git a/packages/worker/src/mcp/capabilities/packages/package-subscription-dispatch.ts b/packages/worker/src/mcp/capabilities/packages/package-subscription-dispatch.ts index a4873c5a40..b23c09f4af 100644 --- a/packages/worker/src/mcp/capabilities/packages/package-subscription-dispatch.ts +++ b/packages/worker/src/mcp/capabilities/packages/package-subscription-dispatch.ts @@ -115,6 +115,7 @@ export const packageSubscriptionDispatchCapability = defineDomainCapability( 'synthetic', 'replay', 'email.message.received', + 'integration.auth.failed', 'test', 'smoke', 'simulate',