From 7d99d3ce705d7cc1be7289687c0d93b41271c817 Mon Sep 17 00:00:00 2001 From: Sawyer Date: Thu, 17 Sep 2026 11:17:53 -0700 Subject: [PATCH] feat(workflows)!: credential expiry sweep is a scheduled workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the hub-owned periodic loop apps/hub/src/credential-expiry-sweep.ts with workflows/credential-expiry, a schedule-triggered workflow package in the publishable shape every other workflows/* package uses. It reads the stock GET /api/tenants/:tenantId/credentials with the run bearer and mails a reconnect notice for any active credential past its own expiresAt. The pure decision logic (findDueCredentialExpiries) moves from @corbits/notify — which needs @intx/db/postgres and can never be a dependency of installable workflow data — into the new package, generalized across every provider rather than a curated SWEPT_PROVIDER_LABELS list. The old sweep's native mcp: OAuth-refresh path is a hub-only concern (it mutates a stored credential's secret directly, which no stock tenant route exposes to a workflow run) and is out of scope for this port. --- .changeset/first-publishable-release.md | 1 + apps/hub/src/credential-expiry-sweep.ts | 559 ---------------- apps/hub/src/index.ts | 33 +- apps/hub/test/credential-expiry-sweep.test.ts | 631 ------------------ bun.lock | 17 + packages/notify/src/credential-expiry.ts | 63 -- packages/notify/src/index.ts | 5 - scripts/checks/report-error-baseline.txt | 1 - tsconfig.build.json | 3 + workflows/credential-expiry/LICENSE | 176 +++++ workflows/credential-expiry/README.md | 69 ++ workflows/credential-expiry/package.json | 48 ++ workflows/credential-expiry/src/client.ts | 120 ++++ .../credential-expiry/src/decide.test.ts | 35 +- workflows/credential-expiry/src/decide.ts | 53 ++ workflows/credential-expiry/src/index.ts | 164 +++++ workflows/credential-expiry/src/tool.ts | 84 +++ workflows/credential-expiry/tsconfig.json | 15 + workflows/credential-expiry/tsconfig.src.json | 12 + 19 files changed, 786 insertions(+), 1303 deletions(-) delete mode 100644 apps/hub/src/credential-expiry-sweep.ts delete mode 100644 apps/hub/test/credential-expiry-sweep.test.ts delete mode 100644 packages/notify/src/credential-expiry.ts create mode 100644 workflows/credential-expiry/LICENSE create mode 100644 workflows/credential-expiry/README.md create mode 100644 workflows/credential-expiry/package.json create mode 100644 workflows/credential-expiry/src/client.ts rename packages/notify/test/credential-expiry.test.ts => workflows/credential-expiry/src/decide.test.ts (71%) create mode 100644 workflows/credential-expiry/src/decide.ts create mode 100644 workflows/credential-expiry/src/index.ts create mode 100644 workflows/credential-expiry/src/tool.ts create mode 100644 workflows/credential-expiry/tsconfig.json create mode 100644 workflows/credential-expiry/tsconfig.src.json diff --git a/.changeset/first-publishable-release.md b/.changeset/first-publishable-release.md index c9b491d09e..98f4b2b4e6 100644 --- a/.changeset/first-publishable-release.md +++ b/.changeset/first-publishable-release.md @@ -9,6 +9,7 @@ "@corbits/code-review-workflow": minor "@corbits/collateral-generation-workflow": minor "@corbits/connections-tools": minor +"@corbits/credential-expiry-workflow": minor "@corbits/diligence-brief-workflow": minor "@corbits/echo-workflow": minor "@corbits/error-sink": minor diff --git a/apps/hub/src/credential-expiry-sweep.ts b/apps/hub/src/credential-expiry-sweep.ts deleted file mode 100644 index 8cc0f8c8bd..0000000000 --- a/apps/hub/src/credential-expiry-sweep.ts +++ /dev/null @@ -1,559 +0,0 @@ -// A periodic loop covering two different OAuth-expiry stories under one -// sweep. The original (CL-5988, Hugging Face): a consumer PKCE flow that -// documents no silent-renewal or refresh-token grant, so a credential's -// `metadata.expiresAt` (set at connect time by `completeCredentialSetup`) -// is the only signal a background sweep has, and the only thing this -// sweep can do is mail a human a reconnect nudge. The second (CL-6207, -// any OAuth-connected MCP server): the MCP SDK's own `auth()` -// orchestrator refreshes natively when handed a stored `refresh_token`, -// so a `mcp:` `oauth_token` credential nearing its real `expiresAt` -// column gets refreshed in place instead — the reconnect nudge is now a -// last resort, sent only when that refresh itself fails. -// -// This mirrors the hub's native schedule poller shape: the decision of -// *which* Hugging-Face-style credentials are due lives in -// `@corbits/notify` (`findDueCredentialExpiries`), pure and unit-tested -// there; `CredentialExpirySweepStore` is a store-behind-an-interface -// seam, so this loop's own claim/refresh/mail orchestration is testable -// against an in-memory store without a live Postgres. -// -// Interchange's inference reactor already fails a credential-category -// error over to the next configured source with no changes here — for -// the still-unrefreshable case, this sweep exists only to tell a human -// the failover is happening and how to stop it (reconnect, or drop in a -// durable fine-grained PAT instead). -import { and, eq, inArray, isNotNull } from "drizzle-orm"; -import { type } from "arktype"; -import { credential, principal, provider } from "@intx/db/schema"; -import type { DB } from "@intx/db"; -import { getLogger } from "@intx/log"; -import { reportError } from "@corbits/error-sink"; -import { - deliverCredentialMail, - findDueCredentialExpiries, - type CredentialExpiredNotification, - type ExpiringCredential, - type NotifyDeliveryDeps, -} from "@corbits/notify"; -import { pushSourceUpdates, type SidecarRouter } from "@intx/hub-sessions"; -import { credentialAad, type CredentialCipher } from "@intx/types"; -import { MCP_STREAMABLE_HTTP_PROVIDER_KEY } from "@corbits/credential-providers"; -import { - mcpSlugOf, - refreshMcpOAuthTokens, - type McpOAuthRefreshResult, -} from "@corbits/connections"; -import type { - OAuthClientInformationMixed, - OAuthTokens, -} from "@modelcontextprotocol/sdk/shared/auth.js"; - -const POLL_INTERVAL_MS = 5 * 60 * 1000; -// How far ahead of its stored `expiresAt` an MCP oauth_token credential -// is refreshed — a token expiring before the *next* tick is refreshed -// this tick, so a live session never sees the gap. -const MCP_REFRESH_LEAD_MS = POLL_INTERVAL_MS; -const MCP_OAUTH_CLIENT_NAME = "Corbits Hub"; -const log = getLogger(["hub", "credential-expiry-sweep"]); - -// Mail-first-claim-after (see `mailThenClaimExpiry`) leaves a still-due -// credential `active` for as long as it keeps failing to notify anyone — -// on purpose, so a transient mail outage or a not-yet-provisioned -// recipient gets more than one tick to resolve. Left unbounded, though, -// `active` stops meaning "usable": the credential is genuinely dead at -// the provider, and the rest of the system (anything selecting an -// `active` credential to actually use) would keep trusting a row that -// will never work again. Past these ages the sweep gives up on ever -// notifying anyone and claims the expiry anyway, so the stored status -// stops asserting something false — reported loudly, since nobody was -// told. -// -// The two failure shapes get different budgets: a mail outage is a -// transient, systemic condition most likely to resolve within a day if -// it's going to resolve at all, while a credential with zero active -// recipients is more often a slow-moving tenant-provisioning gap (a new -// tenant, a departed user being replaced) that deserves more real-world -// time before writing off the notification as unreachable. -const MAX_UNMAILED_CREDENTIAL_AGE_MS = 24 * 60 * 60 * 1000; -const MAX_UNOWNED_CREDENTIAL_AGE_MS = 7 * 24 * 60 * 60 * 1000; - -// The OAuth-connected providers whose tokens expire, and how to name -// each in the notification. A second such provider generalizes this -// list, never a second parallel sweep. -export const SWEPT_PROVIDER_LABELS: Readonly> = { - huggingface: "Hugging Face", -}; - -const CredentialMetadata = type({ "expiresAt?": "string" }); -const McpCredentialMetadata = type({ - url: "string", - "name?": "string", - "clientInformation?": "unknown", -}); - -function mcpOAuthCallbackUrl( - hubUrl: string, - tenantId: string, - slug: string, -): string { - return new URL( - `/api/tenants/${tenantId}/mcp-servers/oauth/${slug}/callback`, - hubUrl, - ).toString(); -} - -export type RefreshableMcpCredential = { - readonly credentialId: string; - readonly tenantId: string; - readonly slug: string; - readonly name: string; - readonly serverUrl: string; - readonly tokens: OAuthTokens; - readonly clientInformation?: OAuthClientInformationMixed; - readonly recipients: readonly { tenantId: string; principalId: string }[]; - /** The credential's real `expiresAt` column — when it became due for - * this reconnect-nudge fallback, used to bound how long an unmailed - * expiry is left `active` (see `MAX_UNMAILED_CREDENTIAL_AGE_MS`). */ - readonly expiresAt: Date; -}; - -export type CredentialExpirySweepStore = { - /** Every `active` credential on a swept provider, with its parsed - * expiry (if any) and the recipients a reconnect nudge would reach. */ - loadActiveCandidates(): Promise; - /** Conditionally moves one credential from `active` to `expired`. - * Returns whether this call won the claim — `false` means another - * caller (a racing replica) already claimed this exact expiry. */ - claimExpiry(credentialId: string, now: Date): Promise; - /** Every `active`, refresh-capable `mcp:` `oauth_token` - * credential whose stored `expiresAt` is at or before `cutoff`. */ - loadRefreshableMcpCandidates( - cutoff: Date, - ): Promise; - /** Persists a successful refresh's new token pair and re-pushes live - * inference sources for the credential's tenant, mirroring the - * credentials PATCH route's own post-rotation behavior. Returns - * whether the row was still `active` to update — `false` means - * another replica already claimed it as expired. */ - applyMcpRefresh( - credentialId: string, - tenantId: string, - tokens: OAuthTokens, - ): Promise; -}; - -export function createDrizzleCredentialExpirySweepStore( - db: DB["db"], - credentialCipher: CredentialCipher, - sidecarRouter: SidecarRouter, -): CredentialExpirySweepStore { - return { - async loadActiveCandidates() { - const sweptProviderNames = Object.keys(SWEPT_PROVIDER_LABELS); - const rows = await db - .select({ - id: credential.id, - tenantId: credential.tenantId, - status: credential.status, - metadata: credential.metadata, - providerName: provider.name, - }) - .from(credential) - .innerJoin(provider, eq(provider.id, credential.providerId)) - .where( - and( - eq(credential.status, "active"), - inArray(provider.name, sweptProviderNames), - ), - ); - if (rows.length === 0) return []; - - const tenantIds = [...new Set(rows.map((row) => row.tenantId))]; - const recipientRows = await db - .select({ tenantId: principal.tenantId, principalId: principal.id }) - .from(principal) - .where( - and( - inArray(principal.tenantId, tenantIds), - eq(principal.kind, "user"), - eq(principal.status, "active"), - ), - ); - const recipientsByTenant = new Map< - string, - { tenantId: string; principalId: string }[] - >(); - for (const row of recipientRows) { - const list = recipientsByTenant.get(row.tenantId) ?? []; - list.push(row); - recipientsByTenant.set(row.tenantId, list); - } - - return rows.map((row) => { - const parsedMetadata = CredentialMetadata(row.metadata ?? {}); - const expiresAt = - parsedMetadata instanceof type.errors - ? undefined - : parsedMetadata.expiresAt; - return { - credentialId: row.id, - tenantId: row.tenantId, - providerId: row.providerName, - providerLabel: - SWEPT_PROVIDER_LABELS[row.providerName] ?? row.providerName, - status: row.status, - expiresAt, - recipients: recipientsByTenant.get(row.tenantId) ?? [], - }; - }); - }, - async claimExpiry(credentialId, now) { - const claimed = await db - .update(credential) - .set({ status: "expired", updatedAt: now }) - .where( - and(eq(credential.id, credentialId), eq(credential.status, "active")), - ) - .returning({ id: credential.id }); - return claimed.length > 0; - }, - async loadRefreshableMcpCandidates(cutoff) { - const rows = await db - .select({ - id: credential.id, - tenantId: credential.tenantId, - secret: credential.secret, - refreshSecret: credential.refreshSecret, - expiresAt: credential.expiresAt, - metadata: credential.metadata, - providerName: provider.name, - apiBaseUrl: provider.apiBaseUrl, - }) - .from(credential) - .innerJoin(provider, eq(provider.id, credential.providerId)) - .where( - and( - eq(credential.status, "active"), - eq(credential.type, "oauth_token"), - eq(provider.plugin, MCP_STREAMABLE_HTTP_PROVIDER_KEY), - isNotNull(credential.refreshSecret), - ), - ); - - const due = rows.filter( - (row): row is typeof row & { expiresAt: Date } => - row.expiresAt !== null && row.expiresAt.getTime() <= cutoff.getTime(), - ); - if (due.length === 0) return []; - - const tenantIds = [...new Set(due.map((row) => row.tenantId))]; - const recipientRows = await db - .select({ tenantId: principal.tenantId, principalId: principal.id }) - .from(principal) - .where( - and( - inArray(principal.tenantId, tenantIds), - eq(principal.kind, "user"), - eq(principal.status, "active"), - ), - ); - const recipientsByTenant = new Map< - string, - { tenantId: string; principalId: string }[] - >(); - for (const row of recipientRows) { - const list = recipientsByTenant.get(row.tenantId) ?? []; - list.push(row); - recipientsByTenant.set(row.tenantId, list); - } - - const candidates: RefreshableMcpCredential[] = []; - for (const row of due) { - // `refreshSecret` is guaranteed non-null by `isNotNull` above; - // a row that fails to parse its own metadata (missing `url`) is - // a stored-data bug, not a transient condition — skip it loudly - // rather than guess at a server URL. - const parsedMetadata = McpCredentialMetadata(row.metadata ?? {}); - if (parsedMetadata instanceof type.errors) { - log.warn`mcp oauth credential ${row.id} has unparseable metadata, skipping refresh: ${parsedMetadata.summary}`; - continue; - } - const accessToken = await credentialCipher.decrypt( - row.secret, - credentialAad(row.id, "secret"), - ); - const refreshToken = await credentialCipher.decrypt( - row.refreshSecret as string, - credentialAad(row.id, "refreshSecret"), - ); - candidates.push({ - credentialId: row.id, - tenantId: row.tenantId, - slug: mcpSlugOf(row.providerName), - name: parsedMetadata.name ?? row.providerName, - serverUrl: row.apiBaseUrl ?? parsedMetadata.url, - expiresAt: row.expiresAt, - tokens: { - access_token: accessToken, - token_type: "bearer", - refresh_token: refreshToken, - }, - ...(parsedMetadata.clientInformation !== undefined - ? { - clientInformation: - parsedMetadata.clientInformation as OAuthClientInformationMixed, - } - : {}), - recipients: recipientsByTenant.get(row.tenantId) ?? [], - }); - } - return candidates; - }, - async applyMcpRefresh(credentialId, tenantId, tokens) { - const now = new Date(); - const encryptedSecret = await credentialCipher.encrypt( - tokens.access_token, - credentialAad(credentialId, "secret"), - ); - const encryptedRefreshSecret = - tokens.refresh_token === undefined - ? undefined - : await credentialCipher.encrypt( - tokens.refresh_token, - credentialAad(credentialId, "refreshSecret"), - ); - const updated = await db - .update(credential) - .set({ - secret: encryptedSecret, - ...(encryptedRefreshSecret !== undefined - ? { refreshSecret: encryptedRefreshSecret } - : {}), - ...(tokens.expires_in !== undefined - ? { expiresAt: new Date(now.getTime() + tokens.expires_in * 1000) } - : {}), - updatedAt: now, - }) - .where( - and(eq(credential.id, credentialId), eq(credential.status, "active")), - ) - .returning({ id: credential.id }); - if (updated.length === 0) return false; - - void pushSourceUpdates(db, sidecarRouter, tenantId, credentialCipher); - return true; - }, - }; -} - -export type CredentialExpirySweepDeps = { - store: CredentialExpirySweepStore; - notify: NotifyDeliveryDeps; - /** The hub's own base URL — reconstructs the exact `/callback` route an - * MCP oauth_token credential's client was registered against, so a - * refresh that needs a fresh dynamic client registration lands on the - * same redirect URI the original connect used. */ - hubUrl: string; - /** Re-invokes the MCP SDK's `auth()` orchestrator non-interactively. - * Defaults to the real `@corbits/connections` implementation; - * overridable so a test can stub the authorization server round trip. */ - refreshMcpTokens?: typeof refreshMcpOAuthTokens; - /** Injectable for deterministic tests; defaults to `Date.now`-backed wall time. */ - now?: () => Date; -}; - -/** - * Mail a credential-expiry reconnect nudge, then claim the credential as - * `expired` only once that mail has gone out (or is already out — a - * `credential-expired` event dedupes on `credentialId` alone, so a - * redelivery from a retried tick is a harmless no-op, never a second - * mail). Claiming is deliberately the LAST step: `active` is the durable - * "still needs a decision" state, and this function leaves a credential - * `active` whenever that decision (mail sent, credential marked expired) - * did not fully land, so the next tick's own due-scan is the retry — - * no separate retry queue is needed. A thrown mail error is reported - * and swallowed here (never `active` → `expired` with the notification - * lost), and never propagates out to abort sibling candidates in the - * same tick. - * - * That "stay active and retry" grace is bounded by `dueSince` (see - * `MAX_UNMAILED_CREDENTIAL_AGE_MS` / `MAX_UNOWNED_CREDENTIAL_AGE_MS`): - * once a credential has been due for longer than its budget with the - * notification still unsent, this claims the expiry anyway rather than - * asserting `active` forever for a credential that is genuinely dead at - * the provider — reported loudly, since giving up here means nobody was - * ever told. - */ -async function mailThenClaimExpiry( - deps: CredentialExpirySweepDeps, - now: Date, - target: { - readonly credentialId: string; - readonly tenantId: string; - readonly recipients: readonly { tenantId: string; principalId: string }[]; - readonly dueSince: Date; - }, - event: CredentialExpiredNotification, -): Promise { - const ageMs = now.getTime() - target.dueSince.getTime(); - - if (target.recipients.length === 0) { - if (ageMs < MAX_UNOWNED_CREDENTIAL_AGE_MS) { - log.warn`credential ${target.credentialId} has no active recipient to notify; leaving it active until one exists`; - return; - } - reportError( - new Error( - "credential expiry never had an active recipient to notify; claiming it as expired unnotified", - ), - { - operation: "credential-expiry-sweep.abandon-unowned", - tenantId: target.tenantId, - extra: { - credentialId: target.credentialId, - dueSince: target.dueSince.toISOString(), - }, - }, - ); - await deps.store.claimExpiry(target.credentialId, now); - return; - } - - try { - await deliverCredentialMail(deps.notify, event); - } catch (err) { - if (ageMs < MAX_UNMAILED_CREDENTIAL_AGE_MS) { - reportError(err, { - operation: "credential-expiry-sweep.deliver", - tenantId: target.tenantId, - extra: { credentialId: target.credentialId }, - }); - return; - } - reportError(err, { - operation: "credential-expiry-sweep.abandon-unmailed", - tenantId: target.tenantId, - extra: { - credentialId: target.credentialId, - dueSince: target.dueSince.toISOString(), - }, - }); - await deps.store.claimExpiry(target.credentialId, now); - return; - } - const claimed = await deps.store.claimExpiry(target.credentialId, now); - // False means another replica already claimed this exact expiry - // between the mail attempt and this claim — not an error. - if (!claimed) return; -} - -/** - * One sweep: mail-then-claim every Hugging-Face-style credential expiry - * due at `now`, then refresh (or, on refresh failure, mail-then-claim) - * every MCP oauth_token credential nearing its own real expiry. Exported - * (rather than kept as a closure) so a test can drive a single, - * deterministic pass without waiting on `setInterval`. - */ -export async function tickCredentialExpirySweep( - deps: CredentialExpirySweepDeps, -): Promise { - const now = (deps.now ?? (() => new Date()))(); - const refreshMcpTokens = deps.refreshMcpTokens ?? refreshMcpOAuthTokens; - - const candidates = await deps.store.loadActiveCandidates(); - const due = findDueCredentialExpiries(candidates, now); - - for (const { credential: expiring, event } of due) { - // Guaranteed defined and parseable for anything `findDueCredentialExpiries` - // returned; `now` is an unreachable fallback, never a real fallback value. - const dueSince = - expiring.expiresAt !== undefined ? new Date(expiring.expiresAt) : now; - await mailThenClaimExpiry( - deps, - now, - { - credentialId: expiring.credentialId, - tenantId: expiring.tenantId, - recipients: expiring.recipients, - dueSince, - }, - event, - ); - } - - const refreshable = await deps.store.loadRefreshableMcpCandidates( - new Date(now.getTime() + MCP_REFRESH_LEAD_MS), - ); - for (const candidate of refreshable) { - const result: McpOAuthRefreshResult = await refreshMcpTokens({ - serverUrl: candidate.serverUrl, - tokens: candidate.tokens, - ...(candidate.clientInformation !== undefined - ? { clientInformation: candidate.clientInformation } - : {}), - callbackUrl: mcpOAuthCallbackUrl( - deps.hubUrl, - candidate.tenantId, - candidate.slug, - ), - clientName: MCP_OAUTH_CLIENT_NAME, - }); - - if (result.ok) { - await deps.store.applyMcpRefresh( - candidate.credentialId, - candidate.tenantId, - result.tokens, - ); - continue; - } - - log.warn`mcp oauth refresh failed for credential ${candidate.credentialId} ("${candidate.name}"): ${result.message}`; - await mailThenClaimExpiry( - deps, - now, - { - credentialId: candidate.credentialId, - tenantId: candidate.tenantId, - recipients: candidate.recipients, - dueSince: candidate.expiresAt, - }, - { - kind: "credential-expired", - tenantId: candidate.tenantId, - credentialId: candidate.credentialId, - providerId: `mcp:${candidate.slug}`, - providerLabel: candidate.name, - recipients: [...candidate.recipients], - createdAt: now.toISOString(), - }, - ); - } -} - -export function createCredentialExpirySweep(deps: CredentialExpirySweepDeps) { - let tickInFlight = false; - - async function tick(): Promise { - if (tickInFlight) return; - tickInFlight = true; - try { - await tickCredentialExpirySweep(deps); - } catch (err) { - log.error`credential expiry sweep failed: ${ - err instanceof Error ? err.message : String(err) - }`; - } finally { - tickInFlight = false; - } - } - - const interval = setInterval(() => void tick(), POLL_INTERVAL_MS); - if (typeof interval.unref === "function") interval.unref(); - - return { - stop(): void { - clearInterval(interval); - }, - }; -} diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index f8ed4dcabe..86d33c5f1e 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -222,7 +222,6 @@ import { createProviderHealthPort, createProviderHealthStore, } from "@corbits/connections/provider-health"; -import { createHubNotifyDeliveryDeps } from "./notify-delivery"; import { createWorkflowAuthorRegistry, createWorkflowAuthorRoutes, @@ -231,10 +230,6 @@ import { WorkflowAuthorError, type WorkflowDeployer, } from "@corbits/workflows"; -import { - createCredentialExpirySweep, - createDrizzleCredentialExpirySweepStore, -} from "./credential-expiry-sweep"; import { createDrizzleServingRefreshStore, createTenantServingRefresh, @@ -2256,29 +2251,10 @@ export async function createHub(config: HubConfig) { }), ); // Notify-to-reconnect for an OAuth-connected credential whose token - // expired (Hugging Face today — see docs/onboarding-huggingface-connect.md): - // a light periodic sweep over `@corbits/notify`'s pure - // `findDueCredentialExpiries`, mailing through the hub's notify delivery - // deps (`createHubNotifyDeliveryDeps`). `createInMemoryNotifyDispatchStore`/`createSinkRegistry()` - // mean external sink fan-out (Slack, email) is a no-op until a sink is - // registered — the mailbox row itself is what a person sees in their - // inbox. Requires `@corbits/mailbox`'s and `@corbits/notify`'s own - // migrations applied against `DATABASE_URL`, same as any other - // consumer of this delivery adapter. - const notifyHost = new URL(config.baseUrl).host; - const credentialExpirySweep = createCredentialExpirySweep({ - store: createDrizzleCredentialExpirySweepStore( - db, - credentialCipher, - sidecarRouter, - ), - hubUrl: config.baseUrl, - notify: createHubNotifyDeliveryDeps({ - mailboxDb, - bus: mailboxBus, - host: notifyHost, - }), - }); + // expired (Hugging Face today — see docs/onboarding-huggingface-connect.md) + // is now `workflows/credential-expiry` (CL-8181), a schedule-triggered + // workflow deployed like any other Routine rather than a hub-owned + // periodic loop. // Reopen a snoozed inbox item once its `until` has passed (CL-7208) — a // light periodic sweep over `@corbits/inbox`'s own snooze table, on the @@ -2362,7 +2338,6 @@ export async function createHub(config: HubConfig) { relaunchSweepSeries += 1; clearTimeout(relaunchSweepTimer); chatOrchestrator.dispose(); - credentialExpirySweep.stop(); inboxUnsnoozeSweep.stop(); cronEmitter.stop(); await insightsUsage.close(); diff --git a/apps/hub/test/credential-expiry-sweep.test.ts b/apps/hub/test/credential-expiry-sweep.test.ts deleted file mode 100644 index c4cbfc634c..0000000000 --- a/apps/hub/test/credential-expiry-sweep.test.ts +++ /dev/null @@ -1,631 +0,0 @@ -// The sweep's own orchestration — claim, mail, skip a no-recipient -// expiry, never double-claim, and (CL-6207) refresh-or-fail-loudly an -// MCP oauth_token credential — against an in-memory store. Which -// Hugging-Face-style credentials are due is `@corbits/notify`'s own -// tested concern (`findDueCredentialExpiries`); this only checks the -// loop calls it correctly and behaves once a claim or refresh decision -// comes back. -import { describe, expect, test } from "bun:test"; -import { - createInMemoryNotifyDispatchStore, - createSinkRegistry, - type NotifyDeliveryDeps, -} from "@corbits/notify"; -import { - tickCredentialExpirySweep, - type CredentialExpirySweepStore, - type RefreshableMcpCredential, -} from "../src/credential-expiry-sweep"; -import type { ExpiringCredential } from "@corbits/notify"; -import type { McpOAuthRefreshResult } from "@corbits/connections"; - -const HUB_URL = "http://hub.test"; - -type MutableExpiringCredential = { - -readonly [K in keyof ExpiringCredential]: ExpiringCredential[K]; -}; - -function credential( - overrides: Partial = {}, -): MutableExpiringCredential { - return { - credentialId: "cred_1", - tenantId: "tnt_1", - providerId: "huggingface", - providerLabel: "Hugging Face", - status: "active", - expiresAt: "2026-08-13T11:00:00.000Z", - recipients: [{ tenantId: "tnt_1", principalId: "prn_1" }], - ...overrides, - }; -} - -/** A raw row shape covering both credential kinds this sweep looks at — - * only an `oauth_token` row with a `refreshSecret` should ever surface - * through `loadRefreshableMcpCandidates`, mirroring the real Drizzle - * store's `eq(credential.type, "oauth_token")` + `isNotNull(refreshSecret)` - * filter. */ -type McpCredentialRow = { - credentialId: string; - tenantId: string; - slug: string; - name: string; - serverUrl: string; - type: "api_key" | "oauth_token"; - refreshSecret: string | undefined; - accessToken: string; - status: "active" | "expired"; - recipients: readonly { tenantId: string; principalId: string }[]; - expiresAt: Date; -}; - -function mcpCredential( - overrides: Partial = {}, -): McpCredentialRow { - return { - credentialId: "cred_mcp_1", - tenantId: "tnt_1", - slug: "granola", - name: "Granola", - serverUrl: "https://mcp.granola.example/mcp", - type: "oauth_token", - refreshSecret: "refresh_old", - accessToken: "access_old", - status: "active", - recipients: [{ tenantId: "tnt_1", principalId: "prn_1" }], - expiresAt: new Date("2026-08-13T11:00:00.000Z"), - ...overrides, - }; -} - -function inMemoryStore( - candidates: MutableExpiringCredential[], - mcpRows: McpCredentialRow[] = [], -): CredentialExpirySweepStore & { - claims: string[]; - mcpClaims: string[]; - mcpRefreshes: { - credentialId: string; - accessToken: string; - refreshSecret: string | undefined; - }[]; -} { - const claims: string[] = []; - const mcpClaims: string[] = []; - const mcpRefreshes: { - credentialId: string; - accessToken: string; - refreshSecret: string | undefined; - }[] = []; - return { - claims, - mcpClaims, - mcpRefreshes, - async loadActiveCandidates() { - return candidates.filter((c) => c.status === "active"); - }, - async claimExpiry(credentialId) { - // Emulate a conditional DB update: only succeeds once per credential. - const found = candidates.find( - (c) => c.credentialId === credentialId && c.status === "active", - ); - if (found) { - claims.push(credentialId); - found.status = "expired"; - return true; - } - const foundMcp = mcpRows.find( - (r) => r.credentialId === credentialId && r.status === "active", - ); - if (!foundMcp) return false; - mcpClaims.push(credentialId); - foundMcp.status = "expired"; - return true; - }, - async loadRefreshableMcpCandidates(): Promise< - readonly RefreshableMcpCredential[] - > { - return mcpRows - .filter( - (r) => - r.status === "active" && - r.type === "oauth_token" && - r.refreshSecret !== undefined, - ) - .map((r) => ({ - credentialId: r.credentialId, - tenantId: r.tenantId, - slug: r.slug, - name: r.name, - serverUrl: r.serverUrl, - expiresAt: r.expiresAt, - tokens: { - access_token: r.accessToken, - token_type: "bearer", - refresh_token: r.refreshSecret, - }, - recipients: r.recipients, - })); - }, - async applyMcpRefresh(credentialId, _tenantId, tokens) { - const found = mcpRows.find( - (r) => r.credentialId === credentialId && r.status === "active", - ); - if (!found) return false; - mcpRefreshes.push({ - credentialId, - accessToken: tokens.access_token, - refreshSecret: tokens.refresh_token, - }); - found.accessToken = tokens.access_token; - found.refreshSecret = tokens.refresh_token; - return true; - }, - }; -} - -function notifyDeps(): NotifyDeliveryDeps & { - mailed: { tenantId: string; principalId: string }[]; -} { - const mailed: { tenantId: string; principalId: string }[] = []; - return { - mailed, - mail: async (items, opts) => - items.map((item, index) => { - const id = `mail-${index}`; - mailed.push({ tenantId: item.tenantId, principalId: item.principalId }); - opts?.enqueue?.({ id, item }); - return { messageKey: item.externalId, id }; - }), - addressing: { - inbox: (recipient) => `${recipient.principalId}@inbox.invalid`, - from: (kind) => `${kind}@notify.invalid`, - }, - dispatch: createInMemoryNotifyDispatchStore(), - sinks: createSinkRegistry(), - }; -} - -/** A notify deps whose `mail` throws — simulates a Postgres blip after a - * credential has already been found due for expiry. */ -function throwingNotifyDeps(error: Error): NotifyDeliveryDeps & { - mailed: { tenantId: string; principalId: string }[]; -} { - return { - mailed: [], - mail: async () => { - throw error; - }, - addressing: { - inbox: (recipient) => `${recipient.principalId}@inbox.invalid`, - from: (kind) => `${kind}@notify.invalid`, - }, - dispatch: createInMemoryNotifyDispatchStore(), - sinks: createSinkRegistry(), - }; -} - -/** A notify deps whose `mail` always dedupes — simulates a retry tick - * re-mailing a credential whose notification already went out. */ -function dedupingNotifyDeps(): NotifyDeliveryDeps & { - mailed: { tenantId: string; principalId: string }[]; -} { - return { - mailed: [], - mail: async (items) => - items.map((item) => ({ messageKey: item.externalId, id: null })), - addressing: { - inbox: (recipient) => `${recipient.principalId}@inbox.invalid`, - from: (kind) => `${kind}@notify.invalid`, - }, - dispatch: createInMemoryNotifyDispatchStore(), - sinks: createSinkRegistry(), - }; -} - -const now = new Date("2026-08-13T12:00:00.000Z"); - -describe("tickCredentialExpirySweep", () => { - test("claims a due credential and mails its recipients", async () => { - const store = inMemoryStore([credential()]); - const notify = notifyDeps(); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual(["cred_1"]); - expect(notify.mailed).toEqual([ - { tenantId: "tnt_1", principalId: "prn_1" }, - ]); - }); - - test("a credential with no active recipients is never claimed, staying due for a later tick", async () => { - const store = inMemoryStore([credential({ recipients: [] })]); - const notify = notifyDeps(); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual([]); - expect(notify.mailed).toEqual([]); - }); - - test("a mail failure leaves the credential unclaimed instead of expiring it silently", async () => { - const store = inMemoryStore([credential()]); - const notify = throwingNotifyDeps(new Error("postgres blip")); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual([]); - - // The next tick sees it still `active` and can finish the job. - const retryNotify = notifyDeps(); - await tickCredentialExpirySweep({ - store, - notify: retryNotify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual(["cred_1"]); - expect(retryNotify.mailed).toEqual([ - { tenantId: "tnt_1", principalId: "prn_1" }, - ]); - }); - - test("a mail that dedupes (already sent by a prior tick) still claims the credential", async () => { - const store = inMemoryStore([credential()]); - const notify = dedupingNotifyDeps(); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual(["cred_1"]); - }); - - test("one candidate's mail failure does not abandon the rest of the tick", async () => { - const store = inMemoryStore([ - credential({ credentialId: "cred_1" }), - credential({ credentialId: "cred_2" }), - ]); - const mailed: { tenantId: string; principalId: string }[] = []; - const notify: NotifyDeliveryDeps = { - mail: async (items, opts) => { - if (items[0]?.externalId === "cred_1") { - throw new Error("postgres blip"); - } - return items.map((item, index) => { - const id = `mail-${index}`; - mailed.push({ - tenantId: item.tenantId, - principalId: item.principalId, - }); - opts?.enqueue?.({ id, item }); - return { messageKey: item.externalId, id }; - }); - }, - addressing: { - inbox: (recipient) => `${recipient.principalId}@inbox.invalid`, - from: (kind) => `${kind}@notify.invalid`, - }, - dispatch: createInMemoryNotifyDispatchStore(), - sinks: createSinkRegistry(), - }; - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual(["cred_2"]); - expect(mailed).toEqual([{ tenantId: "tnt_1", principalId: "prn_1" }]); - }); - - test("a credential not yet expired is neither claimed nor mailed", async () => { - const store = inMemoryStore([ - credential({ expiresAt: "2026-08-13T13:00:00.000Z" }), - ]); - const notify = notifyDeps(); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual([]); - expect(notify.mailed).toEqual([]); - }); - - test("a claim that loses the race (another replica already won) is never mailed", async () => { - const store = inMemoryStore([credential()]); - // Simulate another replica claiming first, between load and claim. - await store.claimExpiry("cred_1", now); - store.claims.length = 0; - const notify = notifyDeps(); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual([]); - expect(notify.mailed).toEqual([]); - }); - - test("a credential with no recipient past the unowned-age bound is claimed anyway, unnotified", async () => { - // 8 days before `now` — past MAX_UNOWNED_CREDENTIAL_AGE_MS (7 days). - const store = inMemoryStore([ - credential({ - recipients: [], - expiresAt: "2026-08-05T00:00:00.000Z", - }), - ]); - const notify = notifyDeps(); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual(["cred_1"]); - expect(notify.mailed).toEqual([]); - }); - - test("a mail failure past the unmailed-age bound is claimed anyway, unnotified", async () => { - // 36 hours before `now` — past MAX_UNMAILED_CREDENTIAL_AGE_MS (24h). - const store = inMemoryStore([ - credential({ expiresAt: "2026-08-11T00:00:00.000Z" }), - ]); - const notify = throwingNotifyDeps(new Error("postgres blip")); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - now: () => now, - }); - - expect(store.claims).toEqual(["cred_1"]); - expect(notify.mailed).toEqual([]); - }); -}); - -describe("tickCredentialExpirySweep — MCP oauth_token refresh (CL-6207)", () => { - test("an expiring mcp oauth credential is refreshed via the SDK and persisted, never mailed", async () => { - const store = inMemoryStore([], [mcpCredential()]); - const notify = notifyDeps(); - let calledWith: - | Parameters< - NonNullable< - Parameters[0]["refreshMcpTokens"] - > - >[0] - | undefined; - const refreshMcpTokens = async ( - args: Parameters< - NonNullable< - Parameters[0]["refreshMcpTokens"] - > - >[0], - ): Promise => { - calledWith = args; - return { - ok: true, - tokens: { - access_token: "access_new", - token_type: "bearer", - refresh_token: "refresh_new", - expires_in: 3600, - }, - }; - }; - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(calledWith?.serverUrl).toBe("https://mcp.granola.example/mcp"); - expect(calledWith?.tokens.refresh_token).toBe("refresh_old"); - expect(calledWith?.callbackUrl).toBe( - `${HUB_URL}/api/tenants/tnt_1/mcp-servers/oauth/granola/callback`, - ); - expect(store.mcpRefreshes).toEqual([ - { - credentialId: "cred_mcp_1", - accessToken: "access_new", - refreshSecret: "refresh_new", - }, - ]); - expect(store.mcpClaims).toEqual([]); - expect(notify.mailed).toEqual([]); - }); - - test("a failed refresh is claimed and mailed as a reconnect nudge, never swallowed", async () => { - const store = inMemoryStore([], [mcpCredential()]); - const notify = notifyDeps(); - const refreshMcpTokens = async (): Promise => ({ - ok: false, - message: "invalid_grant: refresh token revoked", - }); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(store.mcpClaims).toEqual(["cred_mcp_1"]); - expect(store.mcpRefreshes).toEqual([]); - expect(notify.mailed).toEqual([ - { tenantId: "tnt_1", principalId: "prn_1" }, - ]); - }); - - test("a failed refresh with no active recipients is never claimed, staying due for a later tick", async () => { - const store = inMemoryStore([], [mcpCredential({ recipients: [] })]); - const notify = notifyDeps(); - const refreshMcpTokens = async (): Promise => ({ - ok: false, - message: "invalid_grant: refresh token revoked", - }); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(store.mcpClaims).toEqual([]); - expect(notify.mailed).toEqual([]); - }); - - test("a failed refresh whose reconnect mail also fails leaves the credential unclaimed", async () => { - const store = inMemoryStore([], [mcpCredential()]); - const notify = throwingNotifyDeps(new Error("postgres blip")); - const refreshMcpTokens = async (): Promise => ({ - ok: false, - message: "invalid_grant: refresh token revoked", - }); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(store.mcpClaims).toEqual([]); - - const retryNotify = notifyDeps(); - await tickCredentialExpirySweep({ - store, - notify: retryNotify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(store.mcpClaims).toEqual(["cred_mcp_1"]); - expect(retryNotify.mailed).toEqual([ - { tenantId: "tnt_1", principalId: "prn_1" }, - ]); - }); - - test("an api_key mcp credential is never a refresh candidate", async () => { - const store = inMemoryStore( - [], - [ - mcpCredential({ - credentialId: "cred_api_key", - type: "api_key", - refreshSecret: undefined, - }), - ], - ); - const notify = notifyDeps(); - let refreshCalled = false; - const refreshMcpTokens = async (): Promise => { - refreshCalled = true; - return { ok: true, tokens: { access_token: "x", token_type: "bearer" } }; - }; - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(refreshCalled).toBe(false); - expect(store.mcpRefreshes).toEqual([]); - expect(store.mcpClaims).toEqual([]); - }); - - test("a failed refresh with no recipient past the unowned-age bound is claimed anyway, unnotified", async () => { - // 8 days before `now` — past MAX_UNOWNED_CREDENTIAL_AGE_MS (7 days). - const store = inMemoryStore( - [], - [ - mcpCredential({ - recipients: [], - expiresAt: new Date("2026-08-05T00:00:00.000Z"), - }), - ], - ); - const notify = notifyDeps(); - const refreshMcpTokens = async (): Promise => ({ - ok: false, - message: "invalid_grant: refresh token revoked", - }); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(store.mcpClaims).toEqual(["cred_mcp_1"]); - expect(notify.mailed).toEqual([]); - }); - - test("a failed refresh whose reconnect mail keeps failing past the unmailed-age bound is claimed anyway", async () => { - // 36 hours before `now` — past MAX_UNMAILED_CREDENTIAL_AGE_MS (24h). - const store = inMemoryStore( - [], - [mcpCredential({ expiresAt: new Date("2026-08-11T00:00:00.000Z") })], - ); - const notify = throwingNotifyDeps(new Error("postgres blip")); - const refreshMcpTokens = async (): Promise => ({ - ok: false, - message: "invalid_grant: refresh token revoked", - }); - - await tickCredentialExpirySweep({ - store, - notify, - hubUrl: HUB_URL, - refreshMcpTokens, - now: () => now, - }); - - expect(store.mcpClaims).toEqual(["cred_mcp_1"]); - expect(notify.mailed).toEqual([]); - }); -}); diff --git a/bun.lock b/bun.lock index d356ea64a9..9f61fade0e 100644 --- a/bun.lock +++ b/bun.lock @@ -1763,6 +1763,21 @@ "@intx/workflow": "0.3.0", }, }, + "workflows/credential-expiry": { + "name": "@corbits/credential-expiry-workflow", + "version": "0.0.1", + "dependencies": { + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + "peerDependencies": { + "@intx/agent": "0.3.0", + "@intx/workflow": "0.3.0", + }, + }, "workflows/diligence-brief": { "name": "@corbits/diligence-brief-workflow", "version": "0.0.1", @@ -2142,6 +2157,8 @@ "@corbits/context-menu": ["@corbits/context-menu@workspace:packages/context-menu"], + "@corbits/credential-expiry-workflow": ["@corbits/credential-expiry-workflow@workspace:workflows/credential-expiry"], + "@corbits/credential-providers": ["@corbits/credential-providers@workspace:packages/credential-providers"], "@corbits/diligence-brief-workflow": ["@corbits/diligence-brief-workflow@workspace:workflows/diligence-brief"], diff --git a/packages/notify/src/credential-expiry.ts b/packages/notify/src/credential-expiry.ts deleted file mode 100644 index 7dbb6636d6..0000000000 --- a/packages/notify/src/credential-expiry.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Pure decision layer for the "notify to reconnect" fallback the -// CL-5988 research settled on: an OAuth-connected provider (Hugging -// Face today) documents no silent-renewal or refresh-token grant for -// its consumer PKCE flow, so a stored credential's `metadata.expiresAt` -// is the only signal a periodic sweep has that a token has gone stale. -// This module only decides which stored credentials just crossed that -// line as of a given instant; it touches no database and sends no -// mail. The caller (a periodic sweep, e.g. apps/hub's -// credential-expiry-sweep.ts) is responsible for loading candidates, -// marking each due credential `expired` so a later tick doesn't -// re-decide it, and mailing the paired event via `deliverCredentialMail`. -import type { CredentialExpiredNotification, NotifyRecipient } from "./events"; - -export type ExpiringCredential = { - readonly credentialId: string; - readonly tenantId: string; - readonly providerId: string; - readonly providerLabel: string; - readonly status: "active" | "expired" | "revoked" | "error"; - /** ISO instant from the credential's `metadata.expiresAt`; `undefined` - * when the credential carries no expiry (a durable key or PAT). */ - readonly expiresAt: string | undefined; - readonly recipients: readonly NotifyRecipient[]; -}; - -export type DueCredentialExpiry = { - readonly credential: ExpiringCredential; - readonly event: CredentialExpiredNotification; -}; - -/** - * Which of `candidates` just crossed their stored expiry as of `now`: - * still `active` (an already-`expired`/`revoked`/`error` row was - * handled by an earlier tick or another path, and is never re-decided - * here), carries a parseable `expiresAt`, and that instant is at or - * before `now`. Order is preserved from `candidates`. - */ -export function findDueCredentialExpiries( - candidates: readonly ExpiringCredential[], - now: Date, -): readonly DueCredentialExpiry[] { - const due: DueCredentialExpiry[] = []; - for (const candidate of candidates) { - if (candidate.status !== "active") continue; - if (candidate.expiresAt === undefined) continue; - const expiresAt = new Date(candidate.expiresAt); - if (Number.isNaN(expiresAt.getTime())) continue; - if (expiresAt.getTime() > now.getTime()) continue; - due.push({ - credential: candidate, - event: { - kind: "credential-expired", - tenantId: candidate.tenantId, - credentialId: candidate.credentialId, - providerId: candidate.providerId, - providerLabel: candidate.providerLabel, - recipients: [...candidate.recipients], - createdAt: now.toISOString(), - }, - }); - } - return due; -} diff --git a/packages/notify/src/index.ts b/packages/notify/src/index.ts index 076e60dbfe..c4e14bae31 100644 --- a/packages/notify/src/index.ts +++ b/packages/notify/src/index.ts @@ -14,11 +14,6 @@ export { RunFailureNotification, parseNotificationEvent, } from "./events"; -export { - findDueCredentialExpiries, - type DueCredentialExpiry, - type ExpiringCredential, -} from "./credential-expiry"; export { applyNotifyMigrations, notifyMigrations, diff --git a/scripts/checks/report-error-baseline.txt b/scripts/checks/report-error-baseline.txt index 207f03ceb0..325b266322 100644 --- a/scripts/checks/report-error-baseline.txt +++ b/scripts/checks/report-error-baseline.txt @@ -19,7 +19,6 @@ # `occurrence` is this evidence string's 1-based rank among matches in # the same file — line numbers aren't used as the key because they # drift as unrelated code around a catch changes. -apps/hub/src/credential-expiry-sweep.ts 1 log.error`credential expiry sweep failed: ${ apps/hub/src/grant-allowance.ts 1 return null; apps/hub/src/index.ts 1 email = undefined; apps/hub/src/index.ts 1 sidecarAllocationLog.error`Sidecar allocation reconciliation failed: ${error instanceof Error ? error.message : String(error)}`; diff --git a/tsconfig.build.json b/tsconfig.build.json index c568adfceb..d1bfe5f52e 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -238,6 +238,9 @@ { "path": "./workflows/collateral-generation/tsconfig.src.json" }, + { + "path": "./workflows/credential-expiry/tsconfig.src.json" + }, { "path": "./workflows/diligence-brief/tsconfig.src.json" }, diff --git a/workflows/credential-expiry/LICENSE b/workflows/credential-expiry/LICENSE new file mode 100644 index 0000000000..c6487f4fdf --- /dev/null +++ b/workflows/credential-expiry/LICENSE @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/workflows/credential-expiry/README.md b/workflows/credential-expiry/README.md new file mode 100644 index 0000000000..70c944e631 --- /dev/null +++ b/workflows/credential-expiry/README.md @@ -0,0 +1,69 @@ +# @corbits/credential-expiry-workflow + +A schedule-triggered workflow that checks this tenant's credentials once +a day and mails a reconnect notice for any credential that is `active` +but past its own `expiresAt`. Replaces the hub-owned periodic loop +`apps/hub/src/credential-expiry-sweep.ts` (CL-8181): the same decision +runs as a deployed Routine instead of inside the hub process. + +## What it does + +One step, one agent: it calls `credential_expiry_check` (this package's +own read-only tool) exactly once. That tool reads the stock +`GET /api/tenants/:tenantId/credentials` (paired with `/providers` for +display names) with the run's own bearer, and +`findDueCredentialExpiries` (`./src/decide.ts`) decides which rows are +`active` and already past their own `expiresAt`. The step's reply is +the reconnect notice itself — one sentence when nothing is due, or a +short notice naming each due credential — delivered as mail by the host +the same way `@corbits/heartbeat-workflow` and +`@corbits/workbench-digest-workflow` deliver theirs. No separate +mail-send tool exists in this repo yet. + +## Scope note + +The hub sweep this replaces also refreshed `mcp:` OAuth tokens in +place before ever mailing anyone (CL-6207). That native-refresh path +mutates a stored credential's secret directly, which no stock tenant +route exposes to a workflow run, so it stays a hub concern and is not +carried over here — this workflow only reads and reports. + +## Usage + +```ts +import { + buildCredentialExpiryWorkflow, + serializeCredentialExpiryWorkflow, +} from "@corbits/credential-expiry-workflow"; + +const definition = buildCredentialExpiryWorkflow({ + inferencePreferences: [{ provider: "anthropic", model: "claude-haiku" }], + turnTimeoutMs: 60_000, +}); + +const json = serializeCredentialExpiryWorkflow(definition); +``` + +See [`workflows/README.md`](../README.md#status-note) for what +registration/automatable/seeded mean. + +## Deploy from the npm registry + +Once published, deploy this workflow definition to a tenant by name and +version pin: + +``` +POST /api/tenants/:id/workflows/deployments +{ + "source": { "kind": "registry", "registry": "npm" }, + "entry": "./src/index.ts", + "pin": "@corbits/credential-expiry-workflow@0.0.1", + "sourceOfferingIds": ["", ...], + "defaultSourceOfferingId": "" +} +``` + +`entry` is the package's `interchange.workflow` module path; `pin` is +`"@corbits/credential-expiry-workflow@0.0.1"` or a semver range on the +same name. The hub installs, probes, gates, and freezes the definition +from the registry tarball before creating the deployment. diff --git a/workflows/credential-expiry/package.json b/workflows/credential-expiry/package.json new file mode 100644 index 0000000000..dc6388b3d6 --- /dev/null +++ b/workflows/credential-expiry/package.json @@ -0,0 +1,48 @@ +{ + "name": "@corbits/credential-expiry-workflow", + "description": "Scheduled workflow that checks this tenant's credentials and mails a reconnect notice for any active credential past its own expiresAt, replacing the hub-owned credential-expiry sweep", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "corbits": { + "workflow": { + "assetName": "credential-expiry", + "displayName": "Credential expiry check", + "automatable": true + } + }, + "interchange": { + "workflow": "./src/index.ts" + }, + "exports": { + ".": "./src/index.ts" + }, + "files": [ + "src", + "LICENSE", + "README.md" + ], + "repository": { + "type": "git", + "url": "https://github.com/corbitsdev/workbench.git", + "directory": "workflows/credential-expiry" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "arktype": "catalog:" + }, + "peerDependencies": { + "@intx/agent": "0.3.0", + "@intx/workflow": "0.3.0" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/workflows/credential-expiry/src/client.ts b/workflows/credential-expiry/src/client.ts new file mode 100644 index 0000000000..5105e2d72a --- /dev/null +++ b/workflows/credential-expiry/src/client.ts @@ -0,0 +1,120 @@ +// A minimal client for the one stock Interchange surface this tool +// reads: `GET /api/tenants/:tenantId/credentials` and `/providers`, with +// the workflow run's own bearer (sidecar token plus run address), the +// same pairing `@corbits/connections-tools`' `listConnectedProviders` +// uses (`packages/connections-tools/src/client.ts`) — this package +// cannot depend on that one directly (a workflow ships as its own npm +// tarball; `@corbits/connections-tools` is not part of that surface), +// so the fetch/paginate shape is duplicated rather than imported. +import { type } from "arktype"; + +import type { ExpiringCredential } from "./decide"; + +export interface CredentialExpiryClientConfig { + /** The hub's plain HTTP origin. */ + readonly hubConnectionsUrl: string; + readonly tenantId: string; + readonly sidecarToken: string; + readonly address: string; + /** Override for tests; defaults to the global `fetch`. */ + readonly fetchImpl?: typeof fetch; +} + +const ProvidersPage = type({ + data: type({ id: "string", name: "string" }).array(), + "nextCursor?": "string | null", +}); + +const CredentialsPage = type({ + data: type({ + id: "string", + providerId: "string", + name: "string", + status: "'active'|'expired'|'revoked'|'error'", + "expiresAt?": "string | null", + }).array(), + "nextCursor?": "string | null", +}); + +const PAGE_LIMIT = 100; + +function authHeaders( + config: CredentialExpiryClientConfig, +): Record { + return { + authorization: `Bearer ${config.sidecarToken}`, + "x-workflow-run-address": config.address, + }; +} + +function tenantBase(config: CredentialExpiryClientConfig): string { + return `${config.hubConnectionsUrl}/api/tenants/${encodeURIComponent(config.tenantId)}`; +} + +/** Walks every page: a truncated first page would read as "nothing is + * expiring," a wrong answer rather than a slow one. */ +async function readAllPages( + config: CredentialExpiryClientConfig, + path: string, + what: string, + parse: ( + body: unknown, + ) => + | { data: readonly T[]; nextCursor?: string | null | undefined } + | type.errors, +): Promise { + const doFetch = config.fetchImpl ?? fetch; + const items: T[] = []; + let cursor: string | undefined; + for (;;) { + const params = new URLSearchParams({ limit: String(PAGE_LIMIT) }); + if (cursor !== undefined) params.set("cursor", cursor); + const response = await doFetch( + `${tenantBase(config)}${path}?${params.toString()}`, + { headers: authHeaders(config) }, + ); + if (!response.ok) { + throw new Error( + `${what} failed: ${response.status} ${response.statusText}`, + ); + } + const parsed = parse(await response.json()); + if (parsed instanceof type.errors) { + throw new Error( + `${what} came back in an unexpected shape: ${parsed.summary}`, + ); + } + items.push(...parsed.data); + const next = parsed.nextCursor; + if (next === undefined || next === null) return items; + cursor = next; + } +} + +/** + * Every credential this tenant holds, paired with its owning provider's + * display name. Throws on any transport, HTTP, or shape failure — + * never fabricates a result, matching `listConnectedProviders`. + */ +export async function fetchTenantCredentials( + config: CredentialExpiryClientConfig, +): Promise { + const [providers, credentials] = await Promise.all([ + readAllPages(config, "/providers", "Listing providers", (body) => + ProvidersPage(body), + ), + readAllPages(config, "/credentials", "Listing credentials", (body) => + CredentialsPage(body), + ), + ]); + const providerNameById = new Map( + providers.map((provider) => [provider.id, provider.name]), + ); + return credentials.map((row) => ({ + credentialId: row.id, + name: row.name, + providerLabel: providerNameById.get(row.providerId) ?? row.providerId, + status: row.status, + expiresAt: row.expiresAt, + })); +} diff --git a/packages/notify/test/credential-expiry.test.ts b/workflows/credential-expiry/src/decide.test.ts similarity index 71% rename from packages/notify/test/credential-expiry.test.ts rename to workflows/credential-expiry/src/decide.test.ts index e4e006cd71..a5f68b0d7e 100644 --- a/packages/notify/test/credential-expiry.test.ts +++ b/workflows/credential-expiry/src/decide.test.ts @@ -1,7 +1,14 @@ +// Moved from packages/notify/test/credential-expiry.test.ts (CL-8181): +// the pure decision logic now lives in this workflow package instead of +// the hub-owned `@corbits/notify` (which needs `@intx/db`/`postgres` and +// can never be a dependency of installable workflow data), and its +// candidate shape dropped `tenantId`/`providerId`/`recipients` — fields +// only the DB-backed sweep needed — for the stock credential row this +// workflow's own tool fetches instead. import { describe, expect, test } from "bun:test"; -import { findDueCredentialExpiries } from "../src/credential-expiry"; -import type { ExpiringCredential } from "../src/credential-expiry"; +import { findDueCredentialExpiries } from "./decide"; +import type { ExpiringCredential } from "./decide"; const now = new Date("2026-08-13T12:00:00.000Z"); @@ -10,12 +17,10 @@ function credential( ): ExpiringCredential { return { credentialId: "cred_1", - tenantId: "tnt_1", - providerId: "huggingface", - providerLabel: "Hugging Face", + name: "Hugging Face", + providerLabel: "huggingface", status: "active", expiresAt: "2026-08-13T11:00:00.000Z", - recipients: [{ tenantId: "tnt_1", principalId: "prn_1" }], ...overrides, }; } @@ -24,15 +29,7 @@ describe("findDueCredentialExpiries", () => { test("an active credential past its expiry is due", () => { const due = findDueCredentialExpiries([credential()], now); expect(due).toHaveLength(1); - expect(due[0]?.event).toEqual({ - kind: "credential-expired", - tenantId: "tnt_1", - credentialId: "cred_1", - providerId: "huggingface", - providerLabel: "Hugging Face", - recipients: [{ tenantId: "tnt_1", principalId: "prn_1" }], - createdAt: now.toISOString(), - }); + expect(due[0]?.credential).toEqual(credential()); }); test("a credential expiring exactly at now is due", () => { @@ -59,6 +56,14 @@ describe("findDueCredentialExpiries", () => { expect(due).toHaveLength(0); }); + test("a null expiresAt (the stock route's shape for 'none') is never due", () => { + const due = findDueCredentialExpiries( + [credential({ expiresAt: null })], + now, + ); + expect(due).toHaveLength(0); + }); + test("an already-expired credential is not re-decided", () => { const due = findDueCredentialExpiries( [credential({ status: "expired" })], diff --git a/workflows/credential-expiry/src/decide.ts b/workflows/credential-expiry/src/decide.ts new file mode 100644 index 0000000000..798d42fa0c --- /dev/null +++ b/workflows/credential-expiry/src/decide.ts @@ -0,0 +1,53 @@ +// Pure decision layer for the reconnect-notice sweep (CL-8181): given the +// stock-shaped credential rows this workflow's own tool fetches from +// `GET /api/tenants/:tenantId/credentials`, decide which are `active` +// and already past their own `expiresAt`. Ported from the hub's +// `credential-expiry-sweep.ts` (CL-5988), which decided the same thing +// over DB rows and one specific provider's `metadata.expiresAt`; this +// workflow reads the credential's real `expiresAt` column through the +// stock route instead, so the decision generalizes across every +// provider rather than a curated `SWEPT_PROVIDER_LABELS` list. +// +// Touches no network and sends no mail — the caller (`./tool.ts`) is +// responsible for fetching candidates and turning a due credential into +// a reconnect notice. + +export type CredentialStatus = "active" | "expired" | "revoked" | "error"; + +export type ExpiringCredential = { + readonly credentialId: string; + readonly name: string; + readonly providerLabel: string; + readonly status: CredentialStatus; + /** ISO instant from the credential's own `expiresAt` column; + * `undefined`/`null` for a durable credential with no expiry. */ + readonly expiresAt: string | null | undefined; +}; + +export type DueCredentialExpiry = { + readonly credential: ExpiringCredential; +}; + +/** + * Which of `candidates` are `active` and past their own `expiresAt` as + * of `now`. An already `expired`/`revoked`/`error` row is never + * re-decided here, and an unparseable or absent `expiresAt` is skipped + * rather than guessed at. Order is preserved from `candidates`. + */ +export function findDueCredentialExpiries( + candidates: readonly ExpiringCredential[], + now: Date, +): readonly DueCredentialExpiry[] { + const due: DueCredentialExpiry[] = []; + for (const candidate of candidates) { + if (candidate.status !== "active") continue; + if (candidate.expiresAt === null || candidate.expiresAt === undefined) { + continue; + } + const expiresAt = new Date(candidate.expiresAt); + if (Number.isNaN(expiresAt.getTime())) continue; + if (expiresAt.getTime() > now.getTime()) continue; + due.push({ credential: candidate }); + } + return due; +} diff --git a/workflows/credential-expiry/src/index.ts b/workflows/credential-expiry/src/index.ts new file mode 100644 index 0000000000..2021b26798 --- /dev/null +++ b/workflows/credential-expiry/src/index.ts @@ -0,0 +1,164 @@ +// The credential-expiry workflow (CL-8181): on a schedule, check this +// tenant's credentials and mail a reconnect notice for each one that is +// active but past its own `expiresAt`. Replaces the hub-owned periodic +// loop `apps/hub/src/credential-expiry-sweep.ts` — that loop's own +// decision logic now lives in `./decide.ts` (moved rather than +// reimplemented; it needs no DB and no mail infrastructure to stay +// correct), and this definition is deployed like any other scheduled +// Routine instead of running inside the hub process for every tenant at +// once. +// +// Scope narrows on the port: the old sweep also refreshed +// `mcp:` OAuth tokens in place before ever mailing anyone +// (CL-6207) — that native-refresh path stays a hub concern (it mutates +// a stored credential's secret directly, which no stock tenant route +// exposes to a workflow run) and is not carried over here. This +// workflow only reads and reports, exactly as CL-8181 scopes it. +// +// Zero DB, one HTTP read: `credential_expiry_check` (`./tool.ts`) reads +// the stock `GET /api/tenants/:tenantId/credentials` (paired with +// `/providers` for display names) with the run's own bearer, then +// `findDueCredentialExpiries` decides which are due. The step's reply +// is the reconnect notice itself, delivered as mail by the host the +// same way `@corbits/heartbeat-workflow` and +// `@corbits/workbench-digest-workflow` deliver theirs — no separate +// mail-send tool exists in this repo yet. + +import { defineAgent } from "@intx/agent"; +import type { AgentDefinition, InferencePreference } from "@intx/agent"; +import { defineWorkflow, step } from "@intx/workflow"; +import type { WorkflowDefinition } from "@intx/workflow"; + +import { CREDENTIAL_EXPIRY_CHECK_TOOL_NAME } from "./tool"; + +export const CREDENTIAL_EXPIRY_WORKFLOW_ID = "wf_credential_expiry"; +export const CREDENTIAL_EXPIRY_STEP_ID = "credential-expiry-check"; + +/** Daily at 08:00 UTC — ahead of `workbench-digest`'s 09:00 slot, so a + * reconnect notice for the day lands before the day's own digest. */ +export const CREDENTIAL_EXPIRY_SCHEDULE_CRON = "0 8 * * *"; + +export const CREDENTIAL_EXPIRY_SYSTEM_PROMPT = [ + "You are a scheduled credential-expiry check for this workbench's " + + "tenant. Nobody is watching this run happen — write for the tenant " + + "owner reading it later, cold.", + `Call \`${CREDENTIAL_EXPIRY_CHECK_TOOL_NAME}\` exactly once. It returns a \`due\` list of credentials that are active but past their own expiry.`, + "If `due` is empty, reply with exactly one plain sentence saying every " + + "connected credential is current — no other text.", + "If `due` is non-empty, reply with a short reconnect notice: one " + + "opening sentence, then one bullet per due credential naming its " + + "`name` (or `providerLabel` if `name` is empty) and the `expiresAt` " + + "instant it passed, and close with one sentence asking the reader to " + + "reconnect it from the workbench's Plugins settings. Never invent a " + + "credential the tool did not return, and never omit one it did.", +].join("\n\n"); + +/** + * Everything the definition needs that is per-deployment data. The + * schedule trigger is fixed on the definition; inference and the + * per-turn timeout are resolved at deploy time. + */ +export interface CredentialExpiryWorkflowInput { + /** Provider/model preferences, in order; resolved at deploy time. */ + readonly inferencePreferences: readonly InferencePreference[]; + /** Per-turn timeout in milliseconds, enforced on the single step. */ + readonly turnTimeoutMs: number; +} + +/** + * Builds the credential-expiry definition. Exactly one step, matching + * the shape every other definition in this repo commits to. Tools are + * never inlined on the serialized definition — `toolFactories` stays + * empty here, same as every other package in `workflows/*`, since a + * `ToolFactory` is a function and cannot survive the workflow asset's + * JSON round trip; the deploy resolves this package's own exported + * `CREDENTIAL_EXPIRY_CHECK_TOOL` the same way it resolves any other + * pinned tool package. + */ +export function buildCredentialExpiryWorkflow( + input: CredentialExpiryWorkflowInput, +): WorkflowDefinition { + if (!Number.isInteger(input.turnTimeoutMs) || input.turnTimeoutMs <= 0) { + throw new Error( + "buildCredentialExpiryWorkflow requires turnTimeoutMs to be a positive integer", + ); + } + return defineWorkflow({ + id: CREDENTIAL_EXPIRY_WORKFLOW_ID, + trigger: { type: "schedule", cron: CREDENTIAL_EXPIRY_SCHEDULE_CRON }, + steps: { + [CREDENTIAL_EXPIRY_STEP_ID]: step({ + agent: defineAgent({ + id: CREDENTIAL_EXPIRY_STEP_ID, + description: + "Checks this tenant's credentials for ones past their own " + + "expiry and mails a reconnect notice for each", + systemPrompt: CREDENTIAL_EXPIRY_SYSTEM_PROMPT, + tools: [], + capabilities: [], + inference: { sources: input.inferencePreferences }, + }) satisfies AgentDefinition, + timeout: input.turnTimeoutMs, + }), + }, + }); +} + +/** + * Serializes a definition to the JSON a workflow asset carries. The + * definition must survive the asset round-trip byte-faithfully, so + * anything JSON would silently drop or mangle — functions, undefined, + * symbols, bigints, non-finite numbers, class instances — is a loud + * error naming the offending path instead of a corrupted asset. + */ +export function serializeCredentialExpiryWorkflow( + definition: WorkflowDefinition, +): string { + assertJsonPortable(definition, "definition"); + return JSON.stringify(definition); +} + +function assertJsonPortable(value: unknown, path: string): void { + if (value === null) return; + switch (typeof value) { + case "string": + case "boolean": + return; + case "number": + if (!Number.isFinite(value)) { + throw new Error(`${path} is a non-finite number; JSON drops it`); + } + return; + case "object": + break; + default: + throw new Error( + `${path} is a ${typeof value}, which does not survive JSON ` + + "serialization", + ); + } + if (Array.isArray(value)) { + value.forEach((element, index) => { + assertJsonPortable(element, `${path}[${index}]`); + }); + return; + } + const proto: unknown = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) { + throw new Error( + `${path} is a non-plain object; JSON would flatten it lossily`, + ); + } + for (const [key, entry] of Object.entries(value)) { + assertJsonPortable(entry, `${path}.${key}`); + } +} + +export { + CREDENTIAL_EXPIRY_CHECK_TOOL, + CREDENTIAL_EXPIRY_CHECK_TOOL_NAME, + CREDENTIAL_EXPIRY_CHECK_DESCRIPTION, +} from "./tool"; +export type { WorkflowCredentialExpiryEnv } from "./tool"; +export { findDueCredentialExpiries } from "./decide"; +export type { DueCredentialExpiry, ExpiringCredential } from "./decide"; diff --git a/workflows/credential-expiry/src/tool.ts b/workflows/credential-expiry/src/tool.ts new file mode 100644 index 0000000000..6d134d5217 --- /dev/null +++ b/workflows/credential-expiry/src/tool.ts @@ -0,0 +1,84 @@ +// The one tool this workflow's step calls: read this tenant's +// credentials through the stock route and report which ones are +// `active` and past their own `expiresAt`. Kept inside the workflow +// package rather than a shared tool package — same "workflow-specific +// logic lives in the definition" convention `exa-topic-watch`'s +// `finalize-tool.ts` established — this read-only reconnect check is +// not a reusable integration on its own. +// +// Read-only: this tool sends no mail and mutates nothing, so it +// declares no `approval` key, matching `list_connections` +// (`@corbits/connections-tools`). The reconnect notice itself is this +// step's own reply text, delivered as mail by the host the same way +// `@corbits/heartbeat-workflow` and `@corbits/workbench-digest-workflow` +// deliver their replies — no separate mail-send tool exists here. +import { defineTool, type BaseEnv } from "@intx/agent"; + +import { fetchTenantCredentials } from "./client"; +import { findDueCredentialExpiries } from "./decide"; + +export const CREDENTIAL_EXPIRY_CHECK_TOOL_NAME = "credential_expiry_check"; + +export const CREDENTIAL_EXPIRY_CHECK_DESCRIPTION = + "Reads this tenant's credentials and reports which ones are active but past their own expiresAt, so a reconnect notice can be drafted for each."; + +/** The env this tool needs beyond `BaseEnv`: the run's own hub-reach + * credential, mirroring `@corbits/connections-tools`' + * `WorkflowConnectionEnv`. */ +export interface WorkflowCredentialExpiryEnv extends BaseEnv { + readonly hubConnectionsUrl: string; + readonly tenantId: string; + readonly sidecarToken: string; + readonly address: string; +} + +export const CREDENTIAL_EXPIRY_CHECK_TOOL = + defineTool({ + id: "@corbits/workflow-credential-expiry/check", + requires: ["hubConnectionsUrl", "tenantId", "sidecarToken", "address"], + definitions: [{ name: CREDENTIAL_EXPIRY_CHECK_TOOL_NAME }], + factory: (env) => ({ + definitions: [ + { + name: CREDENTIAL_EXPIRY_CHECK_TOOL_NAME, + description: CREDENTIAL_EXPIRY_CHECK_DESCRIPTION, + inputSchema: { type: "object", properties: {}, required: [] }, + }, + ], + run: async (call) => { + try { + const candidates = await fetchTenantCredentials({ + hubConnectionsUrl: env.hubConnectionsUrl, + tenantId: env.tenantId, + sidecarToken: env.sidecarToken, + address: env.address, + }); + const due = findDueCredentialExpiries(candidates, new Date()); + return { + callId: call.id, + isError: false, + content: JSON.stringify({ + due: due.map(({ credential }) => ({ + credentialId: credential.credentialId, + name: credential.name, + providerLabel: credential.providerLabel, + expiresAt: credential.expiresAt, + })), + }), + }; + } catch (err) { + // report-error-ignore: this failure is surfaced to the calling + // agent as an error tool result, which it reports plainly in + // its reply rather than silently retrying — nothing here is + // swallowed. + return { + callId: call.id, + isError: true, + content: `Failed to check credential expiry: ${ + err instanceof Error ? err.message : String(err) + }`, + }; + } + }, + }), + }); diff --git a/workflows/credential-expiry/tsconfig.json b/workflows/credential-expiry/tsconfig.json new file mode 100644 index 0000000000..e125e90614 --- /dev/null +++ b/workflows/credential-expiry/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.src.json", + "compilerOptions": { + "composite": false, + "noEmit": true, + "disableSourceOfProjectReferenceRedirect": true, + "declaration": false, + "declarationMap": false, + "emitDeclarationOnly": false, + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "rootDir": "../.." + }, + "include": ["src"], + "exclude": [] +} diff --git a/workflows/credential-expiry/tsconfig.src.json b/workflows/credential-expiry/tsconfig.src.json new file mode 100644 index 0000000000..fc8724305f --- /dev/null +++ b/workflows/credential-expiry/tsconfig.src.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "package.json", "src/**/*.json"], + "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], + "compilerOptions": { + "types": ["bun"], + "composite": true, + "emitDeclarationOnly": true, + "outDir": "dist", + "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" + } +}