@tangle-network/agent-integrations 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -30
- package/data/bundled-adapter-manifests.json +1 -1
- package/dist/{adapters-SSISY8Yg.js → adapters-x5V_2d6D.js} +74 -113
- package/dist/{adapters-SSISY8Yg.js.map → adapters-x5V_2d6D.js.map} +1 -1
- package/dist/{billing-access-policy-CtvuHvM8.d.ts → billing-access-policy-Ce3WWxG5.d.ts} +2 -3
- package/dist/billing-access-policy-Ce3WWxG5.d.ts.map +1 -0
- package/dist/billing-access-policy-DJ63AxZ5.js.map +1 -1
- package/dist/{bundled-manifest-data-y4NLBbZM.js → bundled-manifest-data-DLzwtr7z.js} +25 -1
- package/dist/{bundled-manifest-data-y4NLBbZM.js.map → bundled-manifest-data-DLzwtr7z.js.map} +1 -1
- package/dist/{bundled-manifest-runtime-EpjLQKA9.d.ts → bundled-manifest-runtime-nc86Eowo.d.ts} +2 -2
- package/dist/{bundled-manifest-runtime-EpjLQKA9.d.ts.map → bundled-manifest-runtime-nc86Eowo.d.ts.map} +1 -1
- package/dist/{catalog-CFvKzwVj.js → catalog-DEbD4Cn3.js} +6 -10
- package/dist/catalog-DEbD4Cn3.js.map +1 -0
- package/dist/{catalog-z4zNeXVL.d.ts → catalog-VQlC1Ew0.d.ts} +8 -12
- package/dist/{catalog-z4zNeXVL.d.ts.map → catalog-VQlC1Ew0.d.ts.map} +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/connect/index.d.ts +1 -1
- package/dist/connectors/adapters/index.d.ts +3 -2
- package/dist/connectors/adapters/index.js +1 -1
- package/dist/connectors/index.d.ts +7 -7
- package/dist/connectors/index.js +2 -2
- package/dist/connectors/oauth.d.ts +1 -1
- package/dist/{consumer-PHOoRorX.d.ts → consumer-BMWxApGG.d.ts} +10 -122
- package/dist/consumer-BMWxApGG.d.ts.map +1 -0
- package/dist/consumer.d.ts +1 -1
- package/dist/{types-Bq85dJDW.d.ts → core-types-ZuEjjJAr.d.ts} +546 -14
- package/dist/core-types-ZuEjjJAr.d.ts.map +1 -0
- package/dist/{coverage-catalog-5LheuThC.d.ts → coverage-catalog-CsJmShn5.d.ts} +3 -4
- package/dist/{coverage-catalog-5LheuThC.d.ts.map → coverage-catalog-CsJmShn5.d.ts.map} +1 -1
- package/dist/coverage-catalog.d.ts +2 -2
- package/dist/coverage-catalog.js +1 -22
- package/dist/coverage-catalog.js.map +1 -1
- package/dist/{errors-8ePwEZRM.d.ts → errors-CvjrGB5r.d.ts} +4 -1
- package/dist/errors-CvjrGB5r.d.ts.map +1 -0
- package/dist/{errors-CvO_y8JO.js → errors-DSdeYms8.js} +16 -3
- package/dist/errors-DSdeYms8.js.map +1 -0
- package/dist/{hub-DkiKVWJX.d.ts → hub-CRteFmOR.d.ts} +3 -3
- package/dist/{hub-DkiKVWJX.d.ts.map → hub-CRteFmOR.d.ts.map} +1 -1
- package/dist/{hub-Du6wsA1o.js → hub-DnPkr4xn.js} +2 -1
- package/dist/hub-DnPkr4xn.js.map +1 -0
- package/dist/hub.d.ts +1 -1
- package/dist/hub.js +1 -1
- package/dist/{index-BFK-G6g1.d.ts → index-BAI3O7bc.d.ts} +2 -2
- package/dist/{index-BFK-G6g1.d.ts.map → index-BAI3O7bc.d.ts.map} +1 -1
- package/dist/{index-poLalSQ6.d.ts → index-BbluAb0U.d.ts} +3 -12
- package/dist/index-BbluAb0U.d.ts.map +1 -0
- package/dist/{index-HBXVPkSs.d.ts → index-C5W0VfzQ.d.ts} +19 -194
- package/dist/index-C5W0VfzQ.d.ts.map +1 -0
- package/dist/{index-CkCYzn8f.d.ts → index-CezgaMuD.d.ts} +3 -3
- package/dist/{index-CkCYzn8f.d.ts.map → index-CezgaMuD.d.ts.map} +1 -1
- package/dist/{index-DoJFdW9K.d.ts → index-Dev4r3_u.d.ts} +3 -3
- package/dist/{index-DoJFdW9K.d.ts.map → index-Dev4r3_u.d.ts.map} +1 -1
- package/dist/index.d.ts +19 -20
- package/dist/index.js +11 -11
- package/dist/internal/bundled-manifest-runtime.d.ts +1 -1
- package/dist/internal/bundled-manifest-runtime.js +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +2 -2
- package/dist/middleware/index.d.ts +1 -1
- package/dist/{oauth-DoUCpYU_.d.ts → oauth-Br5r5Ms0.d.ts} +2 -2
- package/dist/{oauth-DoUCpYU_.d.ts.map → oauth-Br5r5Ms0.d.ts.map} +1 -1
- package/dist/{policy-C8jynxf9.d.ts → policy-BH4ZAZ4s.d.ts} +3 -14
- package/dist/policy-BH4ZAZ4s.d.ts.map +1 -0
- package/dist/{policy-UOPcZqdE.js → policy-C0XpcajG.js} +5 -30
- package/dist/policy-C0XpcajG.js.map +1 -0
- package/dist/{redaction-B6R-ZeWT.js → redaction-dXj4op-I.js} +16 -2
- package/dist/redaction-dXj4op-I.js.map +1 -0
- package/dist/{registry-0xWMSBUu.d.ts → registry-CJFl46d3.d.ts} +3 -3
- package/dist/{registry-0xWMSBUu.d.ts.map → registry-CJFl46d3.d.ts.map} +1 -1
- package/dist/{registry-core-B1ApiG47.d.ts → registry-core-_BnkpeSe.d.ts} +2 -2
- package/dist/{registry-core-B1ApiG47.d.ts.map → registry-core-_BnkpeSe.d.ts.map} +1 -1
- package/dist/registry.d.ts +2 -2
- package/dist/registry.js +1 -1
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.js +1 -1
- package/dist/sandbox.d.ts +2 -2
- package/dist/sandbox.js +5 -20
- package/dist/sandbox.js.map +1 -1
- package/dist/{specs-B7c5wARo.js → specs-BQHb_KgP.js} +4 -23
- package/dist/specs-BQHb_KgP.js.map +1 -0
- package/dist/specs.d.ts +2 -2
- package/dist/specs.js +2 -2
- package/dist/{src-ZNpLV5ka.js → src-BZmlzQzN.js} +8 -186
- package/dist/src-BZmlzQzN.js.map +1 -0
- package/dist/stripe/index.d.ts +3 -79
- package/dist/stripe/index.d.ts.map +1 -1
- package/dist/stripe/index.js +5 -52
- package/dist/stripe/index.js.map +1 -1
- package/dist/{tangle-id-BW5dTiGi.d.ts → tangle-id-BnzGOA_W.d.ts} +2 -2
- package/dist/{tangle-id-BW5dTiGi.d.ts.map → tangle-id-BnzGOA_W.d.ts.map} +1 -1
- package/dist/types-CjrugGcd.js.map +1 -1
- package/dist/worker.d.ts +3 -3
- package/dist/worker.js +2 -2
- package/docs/external-product-integration.md +14 -5
- package/docs/integration-coverage-checklist.md +1 -12
- package/docs/private-audio-transcription.md +1 -1
- package/package.json +2 -1
- package/dist/billing-access-policy-CtvuHvM8.d.ts.map +0 -1
- package/dist/catalog-CFvKzwVj.js.map +0 -1
- package/dist/consumer-PHOoRorX.d.ts.map +0 -1
- package/dist/core-types-0BenSoZJ.d.ts +0 -365
- package/dist/core-types-0BenSoZJ.d.ts.map +0 -1
- package/dist/errors-8ePwEZRM.d.ts.map +0 -1
- package/dist/errors-CvO_y8JO.js.map +0 -1
- package/dist/hub-Du6wsA1o.js.map +0 -1
- package/dist/index-HBXVPkSs.d.ts.map +0 -1
- package/dist/index-poLalSQ6.d.ts.map +0 -1
- package/dist/policy-C8jynxf9.d.ts.map +0 -1
- package/dist/policy-UOPcZqdE.js.map +0 -1
- package/dist/redaction-B6R-ZeWT.js.map +0 -1
- package/dist/specs-B7c5wARo.js.map +0 -1
- package/dist/src-ZNpLV5ka.js.map +0 -1
- package/dist/types-Bq85dJDW.d.ts.map +0 -1
- package/docs/generated-integration-coverage-checklist.md +0 -156
package/dist/stripe/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/stripe/errors.ts","../../src/stripe/subscription-state.ts","../../src/stripe/webhooks.ts","../../src/stripe/pricing.ts","../../src/stripe/tenant-config.ts","../../src/stripe/middleware.ts"],"sourcesContent":["/**\n * Stripe billing error taxonomy.\n *\n * Layered on top of `IntegrationRuntimeError` (the cross-package error\n * contract) so a billing failure surfaces through the same normalization\n * pipeline the rest of the integration runtime uses: `status` maps to\n * an HTTP status, `userAction` carries the recommended next step\n * (connect / reconnect / contact_support), and `code` is stable across\n * versions for product analytics.\n *\n * Why a billing-specific subclass and not bare `IntegrationRuntimeError`:\n * three error classes carry a payload product agents NEED to branch on\n * (subscription state, tenant id, plan id). Encoding them as discriminated\n * subclasses keeps the call site `instanceof BillingError` lookup O(1)\n * and avoids stuffing them into `metadata` where they decay to `unknown`.\n *\n * Code mapping (`BillingErrorCode` → `IntegrationErrorCode`):\n * subscription_required → action_denied (403)\n * subscription_inactive → action_denied (403)\n * subscription_past_due → action_denied (403, w/ warning)\n * trial_expired → action_denied (403)\n * free_tier_exhausted → action_denied (403)\n * tenant_not_configured → provider_error (500) — operator bug\n * webhook_secret_missing→ provider_auth_failed (401) — config bug\n * webhook_event_unknown → input_invalid (400)\n * webhook_replay → input_invalid (400)\n */\n\nimport { IntegrationRuntimeError, type IntegrationUserAction } from '../errors.js'\nimport type { SubscriptionState } from './subscription-state.js'\n\nexport type BillingErrorCode =\n | 'subscription_required'\n | 'subscription_inactive'\n | 'subscription_past_due'\n | 'trial_expired'\n | 'free_tier_exhausted'\n | 'platform_evidence_required'\n | 'platform_evidence_expired'\n | 'platform_evidence_replayed'\n | 'platform_evidence_subject_mismatch'\n | 'email_verification_required'\n | 'real_email_required'\n | 'paid_evidence_required'\n | 'product_free_credits_disabled'\n | 'tenant_not_configured'\n | 'webhook_secret_missing'\n | 'webhook_event_unknown'\n | 'webhook_replay'\n\nexport interface BillingErrorContext {\n workspaceId?: string\n productId?: string\n subscriptionId?: string\n subscriptionState?: SubscriptionState\n planId?: string\n eventId?: string\n}\n\nexport class BillingError extends IntegrationRuntimeError {\n readonly billingCode: BillingErrorCode\n readonly context: BillingErrorContext\n\n constructor(input: {\n code: BillingErrorCode\n message: string\n context?: BillingErrorContext\n userAction?: IntegrationUserAction\n }) {\n super({\n code: mapToIntegrationCode(input.code),\n message: input.message,\n status: statusForBillingCode(input.code),\n userAction: input.userAction ?? defaultUserAction(input.code),\n metadata: input.context as Record<string, unknown> | undefined,\n })\n this.name = 'BillingError'\n this.billingCode = input.code\n this.context = input.context ?? {}\n }\n}\n\n/** Distinct subclass: operator missed an environment variable. Surfaces\n * with a different `userAction` (`contact_support`) so the consumer\n * doesn't render a \"connect Stripe\" CTA to a customer for what is in\n * fact a backend deploy bug. */\nexport class ConfigError extends BillingError {\n constructor(input: { message: string; context?: BillingErrorContext }) {\n super({\n code: 'tenant_not_configured',\n message: input.message,\n context: input.context,\n userAction: { type: 'contact_support', label: 'Contact support' },\n })\n this.name = 'ConfigError'\n }\n}\n\nfunction mapToIntegrationCode(code: BillingErrorCode): IntegrationRuntimeError['code'] {\n switch (code) {\n case 'subscription_required':\n case 'subscription_inactive':\n case 'subscription_past_due':\n case 'trial_expired':\n case 'free_tier_exhausted':\n case 'platform_evidence_required':\n case 'platform_evidence_expired':\n case 'platform_evidence_replayed':\n case 'platform_evidence_subject_mismatch':\n case 'email_verification_required':\n case 'real_email_required':\n case 'paid_evidence_required':\n case 'product_free_credits_disabled':\n return 'action_denied'\n case 'tenant_not_configured':\n return 'provider_error'\n case 'webhook_secret_missing':\n return 'provider_auth_failed'\n case 'webhook_event_unknown':\n case 'webhook_replay':\n return 'input_invalid'\n }\n}\n\nfunction statusForBillingCode(code: BillingErrorCode): number {\n switch (code) {\n case 'subscription_required':\n case 'subscription_inactive':\n case 'subscription_past_due':\n case 'trial_expired':\n case 'free_tier_exhausted':\n case 'platform_evidence_required':\n case 'platform_evidence_expired':\n case 'platform_evidence_replayed':\n case 'platform_evidence_subject_mismatch':\n case 'email_verification_required':\n case 'real_email_required':\n case 'paid_evidence_required':\n case 'product_free_credits_disabled':\n return 403\n case 'tenant_not_configured':\n return 500\n case 'webhook_secret_missing':\n return 401\n case 'webhook_event_unknown':\n case 'webhook_replay':\n return 400\n }\n}\n\nfunction defaultUserAction(code: BillingErrorCode): IntegrationUserAction | undefined {\n switch (code) {\n case 'subscription_required':\n return { type: 'change_request', label: 'Subscribe to continue' }\n case 'subscription_inactive':\n case 'subscription_past_due':\n return { type: 'change_request', label: 'Update billing' }\n case 'trial_expired':\n return { type: 'change_request', label: 'Choose a plan' }\n case 'free_tier_exhausted':\n return { type: 'change_request', label: 'Upgrade for more usage' }\n case 'platform_evidence_required':\n case 'platform_evidence_expired':\n case 'platform_evidence_replayed':\n case 'platform_evidence_subject_mismatch':\n case 'email_verification_required':\n case 'real_email_required':\n case 'paid_evidence_required':\n case 'product_free_credits_disabled':\n return { type: 'change_request', label: 'Verify access to continue' }\n case 'tenant_not_configured':\n case 'webhook_secret_missing':\n return { type: 'contact_support', label: 'Contact support' }\n case 'webhook_event_unknown':\n case 'webhook_replay':\n return undefined\n }\n}\n","/**\n * Subscription state machine.\n *\n * Stripe ships eight terminal states on `Subscription.status`. We model\n * them verbatim — never normalize, never collapse — so the state\n * persisted in product DBs round-trips Stripe webhooks losslessly.\n *\n * incomplete — first invoice not paid within 23 hours\n * incomplete_expired — first invoice failed, no retry coming\n * trialing — inside a trial window (not product access)\n * active — paying, current\n * past_due — auto-renewal failed; grace period running\n * canceled — terminal; ended at period boundary or hard\n * unpaid — past_due → unpaid after retries exhausted\n * paused — operator-paused (collection_method=pause_collection)\n *\n * Transition rules below derive STRICTLY from the Stripe state diagram\n * (https://docs.stripe.com/billing/subscriptions/overview#subscription-statuses)\n * — the dispatcher in `webhooks.ts` calls `applyTransition()` which\n * rejects any state pair Stripe never emits. This catches manual-edit\n * bugs (someone POSTing a `force_state` admin endpoint) and tests for\n * the consumer's state store at the same time.\n *\n * Persistence: products pick an adapter (FS, D1, Postgres, in-memory).\n * The interface is intentionally minimal — load(), save(), and a\n * compare-and-set `saveIfVersion()` that defends against duplicate\n * webhook delivery racing the same store. Stripe re-delivers failed\n * webhooks for 3 days; the in-flight one and the retry will both write\n * the same key. `WebhookRouter`'s idempotency hook short-circuits at\n * the event level, but a misconfigured deploy with two routers in\n * different regions both processing the same event needs the second\n * line of defense here.\n *\n * `requireActiveSubscription()` (middleware) calls `gateAccess(state)`\n * to map state → access-decision. `past_due` is intentionally allowed\n * with a warning flag — the dunning period is when products MOST need\n * customers to keep using the product so they remember why they pay,\n * but the UI should render the \"card declined\" banner.\n */\n\nimport { BillingError } from './errors.js'\n\nexport type SubscriptionState =\n | 'incomplete'\n | 'incomplete_expired'\n | 'trialing'\n | 'active'\n | 'past_due'\n | 'canceled'\n | 'unpaid'\n | 'paused'\n\n/** All eight states, exported so tests + consumers can enumerate. */\nexport const SUBSCRIPTION_STATES: readonly SubscriptionState[] = Object.freeze([\n 'incomplete',\n 'incomplete_expired',\n 'trialing',\n 'active',\n 'past_due',\n 'canceled',\n 'unpaid',\n 'paused',\n])\n\n/** Tristate access decision. `warn` means the route runs, but the UI\n * should render a billing banner. */\nexport type AccessDecision =\n | { allowed: true; warn?: 'past_due' | 'trial_ending' }\n | { allowed: false; reason: 'no_subscription' | 'subscription_inactive' | 'subscription_past_due' | 'trial_expired' }\n\nexport interface SubscriptionRecord {\n /** Tenant key the product uses to look up \"is this workspace paying?\" —\n * typically a workspaceId, but products that bill per-user or\n * per-organization can swap in their own scope. */\n workspaceId: string\n /** Stripe customer id (`cus_...`). */\n customerId: string\n /** Stripe subscription id (`sub_...`). */\n subscriptionId: string\n /** Last-known subscription state — updated by webhook handlers. */\n state: SubscriptionState\n /** Stripe price id active on the subscription. Null for canceled. */\n priceId: string | null\n /** Current billing period end (unix seconds). Used by middleware to\n * emit `trial_ending` warning in the last 72h of a trial. */\n currentPeriodEnd: number | null\n /** Trial end (unix seconds), null for non-trial subs. */\n trialEnd: number | null\n /** `cancel_at_period_end` flag — once true, state stays `active` until\n * the period ends, then transitions to `canceled`. */\n cancelAtPeriodEnd: boolean\n /** Monotonic write counter for optimistic concurrency. Incremented on\n * every save; persistence adapters use it for CAS. */\n version: number\n /** Last event id we processed for this subscription — defends against\n * Stripe re-delivering the same event and us racing the dedupe store. */\n lastEventId: string | null\n /** Stripe `event.created` for the newest applied subscription event. */\n lastEventCreatedAt: number | null\n /** State before the newest applied event. This lets a failed durable\n * listener retry the exact typed update after the state write succeeded. */\n lastEventPreviousState?: SubscriptionState | null\n /** Event whose state is durable but whose listener has not completed.\n * A different subscription event cannot advance until this is cleared. */\n pendingEventId?: string | null\n /** Wall-clock ms of last successful write. */\n updatedAt: number\n}\n\n/** Persistence adapter contract. Three operations — pick the storage\n * layer that matches the product's existing infra. Adapters live below\n * (in-memory + filesystem). D1 / Postgres are one-liners on top. */\nexport interface SubscriptionStore {\n load(workspaceId: string): Promise<SubscriptionRecord | null>\n save(record: SubscriptionRecord): Promise<void>\n /** Compare-and-set on `version`. Returns false if the stored record's\n * version doesn't match `expectedVersion` (someone else wrote first).\n * Implementations MUST return false rather than throw on contention —\n * the caller branches on the bool. */\n saveIfVersion(record: SubscriptionRecord, expectedVersion: number): Promise<boolean>\n}\n\n/** Transitions table — adjacency map of legal {from → to} edges derived\n * from Stripe's subscription status diagram. Used by `applyTransition`. */\nconst TRANSITIONS: Readonly<Record<SubscriptionState, ReadonlySet<SubscriptionState>>> = Object.freeze({\n incomplete: new Set<SubscriptionState>(['active', 'trialing', 'incomplete_expired', 'canceled']),\n incomplete_expired: new Set<SubscriptionState>([]),\n trialing: new Set<SubscriptionState>(['active', 'past_due', 'canceled', 'paused', 'unpaid']),\n active: new Set<SubscriptionState>(['past_due', 'canceled', 'paused', 'unpaid', 'trialing']),\n past_due: new Set<SubscriptionState>(['active', 'canceled', 'unpaid', 'paused']),\n canceled: new Set<SubscriptionState>([]),\n unpaid: new Set<SubscriptionState>(['active', 'canceled', 'past_due']),\n paused: new Set<SubscriptionState>(['active', 'canceled', 'past_due']),\n})\n\n/** Returns true if `to` is reachable from `from` in one Stripe transition.\n * Self-edges are accepted (a webhook can re-emit the current state on\n * any field change). */\nexport function isValidTransition(from: SubscriptionState, to: SubscriptionState): boolean {\n if (from === to) return true\n return TRANSITIONS[from].has(to)\n}\n\n/** Apply a state transition to a record. Throws `BillingError` if Stripe\n * would never emit this edge (defensive — a bad admin tool POSTing a\n * raw state update gets refused). Returns the new record without writing. */\nexport function applyTransition(\n current: SubscriptionRecord,\n next: Partial<SubscriptionRecord> & { state: SubscriptionState },\n options: {\n eventId?: string\n eventCreatedAt?: number\n pendingEventId?: string | null\n now?: () => number\n } = {},\n): SubscriptionRecord {\n if (!isValidTransition(current.state, next.state)) {\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Illegal subscription transition ${current.state} → ${next.state}`,\n context: {\n workspaceId: current.workspaceId,\n subscriptionId: current.subscriptionId,\n subscriptionState: current.state,\n eventId: options.eventId,\n },\n })\n }\n const now = (options.now ?? Date.now)()\n return {\n ...current,\n ...next,\n version: current.version + 1,\n lastEventId: options.eventId ?? current.lastEventId,\n lastEventCreatedAt: options.eventCreatedAt ?? current.lastEventCreatedAt,\n lastEventPreviousState: options.eventId ? current.state : (current.lastEventPreviousState ?? null),\n pendingEventId: options.pendingEventId !== undefined\n ? options.pendingEventId\n : (current.pendingEventId ?? null),\n updatedAt: now,\n }\n}\n\n/**\n * Map a state to an access decision.\n *\n * Rule rationale:\n * active → allow\n * trialing → deny (product-funded trials are disabled)\n * past_due → allow + warn (dunning grace)\n * paused → deny (operator action; resume restores)\n * canceled, unpaid → deny (terminal financial states)\n * incomplete, incomplete_expired → deny (never paid; first invoice failed)\n *\n * Note `requireActiveSubscription` in `middleware.ts` is the consumer of\n * this — gating is centralized here so the rule lives in one place. The\n * mapping is one assertion in the test suite. Changing the rule for one\n * product (e.g., legal-agent wants past_due to deny) is a per-call\n * `overrides` option on the middleware, NOT a fork of this function.\n */\nexport function gateAccess(state: SubscriptionState): AccessDecision {\n switch (state) {\n case 'active':\n return { allowed: true }\n case 'trialing':\n return { allowed: false, reason: 'trial_expired' }\n case 'past_due':\n return { allowed: true, warn: 'past_due' }\n case 'paused':\n return { allowed: false, reason: 'subscription_past_due' }\n case 'canceled':\n case 'unpaid':\n return { allowed: false, reason: 'subscription_inactive' }\n case 'incomplete':\n case 'incomplete_expired':\n return { allowed: false, reason: 'subscription_inactive' }\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* persistence adapter: in-memory */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Process-local store. Useful for tests; product instances should pick\n * `FileSystemSubscriptionStore` or wire D1 / Postgres. Implements proper\n * CAS — concurrent saves with stale versions are rejected.\n */\nexport class InMemorySubscriptionStore implements SubscriptionStore {\n private readonly records = new Map<string, SubscriptionRecord>()\n\n async load(workspaceId: string): Promise<SubscriptionRecord | null> {\n const r = this.records.get(workspaceId)\n return r ? { ...r } : null\n }\n\n async save(record: SubscriptionRecord): Promise<void> {\n this.records.set(record.workspaceId, { ...record })\n }\n\n async saveIfVersion(record: SubscriptionRecord, expectedVersion: number): Promise<boolean> {\n const current = this.records.get(record.workspaceId)\n if (current && current.version !== expectedVersion) return false\n if (!current && expectedVersion !== 0) return false\n this.records.set(record.workspaceId, { ...record })\n return true\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* persistence adapter: filesystem */\n/* ---------------------------------------------------------------------- */\n\n/**\n * File-per-workspace JSON store. One file per workspace under\n * `<rootDir>/<workspaceId>.versions/<version>.json`. Each version is written\n * completely and then hard-linked to its final path. Two processes racing the\n * same expected version therefore contend on one atomic filesystem operation.\n *\n * Why per-workspace versions and not one JSONL: subscriptions are accessed by\n * workspace id. Reads inspect only that workspace's immutable versions.\n *\n * The store does NOT use `fs.watch` — webhooks are the only writer in\n * production, and webhooks always go through `applyTransition()` →\n * `saveIfVersion()`, so the CAS catches the race.\n */\nexport class FileSystemSubscriptionStore implements SubscriptionStore {\n constructor(private readonly rootDir: string) {\n if (!rootDir.trim()) throw new Error('FileSystemSubscriptionStore requires a root directory')\n }\n\n async load(workspaceId: string): Promise<SubscriptionRecord | null> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n const versionDir = await this.versionDir(workspaceId)\n let versionFiles: string[] = []\n try {\n versionFiles = (await fs.readdir(versionDir))\n .filter((file) => /^\\d+\\.json$/.test(file))\n .sort((left, right) => Number.parseInt(right, 10) - Number.parseInt(left, 10))\n } catch (err) {\n if (!isNodeENOENT(err)) throw err\n }\n\n const candidates: SubscriptionRecord[] = []\n if (versionFiles[0]) {\n candidates.push(await this.readRecord(path.join(versionDir, versionFiles[0]), workspaceId))\n }\n const legacyFile = path.join(this.rootDir, this.fileName(workspaceId))\n try {\n candidates.push(await this.readRecord(legacyFile, workspaceId))\n } catch (err) {\n if (!isNodeENOENT(err)) throw err\n }\n if (candidates.length === 0) return null\n candidates.sort((left, right) => right.version - left.version)\n if (\n candidates[1]\n && candidates[0]!.version === candidates[1].version\n && !sameSubscriptionRecord(candidates[0]!, candidates[1])\n ) {\n throw new Error(`Conflicting subscription version ${candidates[0]!.version} for ${workspaceId}`)\n }\n return { ...candidates[0]! }\n }\n\n async save(record: SubscriptionRecord): Promise<void> {\n assertSubscriptionRecord(record)\n const existing = await this.load(record.workspaceId)\n if (existing) {\n if (existing.version > record.version) {\n throw new Error(`Stale subscription save for ${record.workspaceId}`)\n }\n if (existing.version === record.version) {\n if (sameSubscriptionRecord(existing, record)) return\n throw new Error(`Conflicting subscription version ${record.version} for ${record.workspaceId}`)\n }\n if (record.version !== existing.version + 1) {\n throw new Error(`Subscription save must advance exactly one version for ${record.workspaceId}`)\n }\n } else if (record.version !== 0) {\n throw new Error(`Initial subscription version must be 0 for ${record.workspaceId}`)\n }\n if (!(await this.writeVersion(record))) {\n const winner = await this.load(record.workspaceId)\n if (winner && sameSubscriptionRecord(winner, record)) return\n throw new Error(`Subscription write contention for ${record.workspaceId}`)\n }\n }\n\n async saveIfVersion(record: SubscriptionRecord, expectedVersion: number): Promise<boolean> {\n assertSubscriptionRecord(record)\n if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) return false\n const existing = await this.load(record.workspaceId)\n if (existing && existing.version !== expectedVersion) return false\n if (!existing && expectedVersion !== 0) return false\n if (existing && record.version !== expectedVersion + 1) return false\n if (!existing && record.version !== 0) return false\n return this.writeVersion(record)\n }\n\n private async readRecord(file: string, expectedWorkspaceId: string): Promise<SubscriptionRecord> {\n const fs = await import('node:fs/promises')\n const raw = await fs.readFile(file, 'utf8')\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new Error(`Invalid subscription JSON at ${file}`)\n }\n const record = normalizeSubscriptionRecord(parsed)\n if (record.workspaceId !== expectedWorkspaceId) {\n throw new Error(`Subscription workspace mismatch at ${file}`)\n }\n return record\n }\n\n private async writeVersion(record: SubscriptionRecord): Promise<boolean> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n const versionDir = await this.versionDir(record.workspaceId)\n await fs.mkdir(versionDir, { recursive: true, mode: 0o700 })\n const finalFile = path.join(versionDir, `${record.version}.json`)\n const tmp = path.join(versionDir, `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`)\n const handle = await fs.open(tmp, 'wx', 0o600)\n try {\n await handle.writeFile(JSON.stringify(record), 'utf8')\n await handle.sync()\n await handle.close()\n try {\n await fs.link(tmp, finalFile)\n await syncDirectory(versionDir)\n return true\n } catch (err) {\n if (isNodeEEXIST(err)) return false\n throw err\n }\n } catch (err) {\n throw err\n } finally {\n await handle.close().catch(() => undefined)\n await fs.unlink(tmp).catch(() => undefined)\n }\n }\n\n private async versionDir(workspaceId: string): Promise<string> {\n const path = await import('node:path')\n return path.join(this.rootDir, `${this.fileName(workspaceId)}.versions`)\n }\n\n /** Safe filename: workspaceId is restricted to a charset that maps 1:1\n * to a posix filename. Anything outside is hex-encoded so we can never\n * escape the rootDir via `../`. */\n private fileName(workspaceId: string): string {\n if (!/^[A-Za-z0-9_.-]+$/.test(workspaceId)) {\n return `${Buffer.from(workspaceId, 'utf-8').toString('hex')}.json`\n }\n return `${workspaceId}.json`\n }\n}\n\nfunction isNodeENOENT(err: unknown): boolean {\n return !!err && typeof err === 'object' && (err as { code?: string }).code === 'ENOENT'\n}\n\n/* ---------------------------------------------------------------------- */\n/* construction helper */\n/* ---------------------------------------------------------------------- */\n\n/** Convenience constructor for the initial record after a checkout\n * succeeds. The webhook handler for `customer.subscription.created` calls\n * this — exposed for tests + manual-fix scripts that need to backfill. */\nexport function makeSubscriptionRecord(input: {\n workspaceId: string\n customerId: string\n subscriptionId: string\n state: SubscriptionState\n priceId: string | null\n currentPeriodEnd: number | null\n trialEnd?: number | null\n cancelAtPeriodEnd?: boolean\n eventId?: string\n eventCreatedAt?: number\n pendingEventId?: string | null\n now?: () => number\n}): SubscriptionRecord {\n const now = (input.now ?? Date.now)()\n return {\n workspaceId: input.workspaceId,\n customerId: input.customerId,\n subscriptionId: input.subscriptionId,\n state: input.state,\n priceId: input.priceId,\n currentPeriodEnd: input.currentPeriodEnd,\n trialEnd: input.trialEnd ?? null,\n cancelAtPeriodEnd: input.cancelAtPeriodEnd ?? false,\n version: 0,\n lastEventId: input.eventId ?? null,\n lastEventCreatedAt: input.eventCreatedAt ?? null,\n lastEventPreviousState: null,\n pendingEventId: input.pendingEventId ?? null,\n updatedAt: now,\n }\n}\n\nfunction normalizeSubscriptionRecord(value: unknown): SubscriptionRecord {\n if (!value || typeof value !== 'object') throw new Error('Invalid subscription record')\n const candidate = value as Partial<SubscriptionRecord>\n const record = {\n ...candidate,\n lastEventCreatedAt: candidate.lastEventCreatedAt ?? null,\n lastEventPreviousState: candidate.lastEventPreviousState ?? null,\n pendingEventId: candidate.pendingEventId ?? null,\n } as SubscriptionRecord\n assertSubscriptionRecord(record)\n return record\n}\n\nfunction assertSubscriptionRecord(record: SubscriptionRecord): void {\n if (!record || typeof record !== 'object') throw new Error('Invalid subscription record')\n if (!record.workspaceId?.trim()) throw new Error('Subscription workspaceId is required')\n if (!record.customerId?.trim()) throw new Error('Subscription customerId is required')\n if (!record.subscriptionId?.trim()) throw new Error('Subscription subscriptionId is required')\n if (!SUBSCRIPTION_STATES.includes(record.state)) throw new Error('Invalid subscription state')\n if (!Number.isSafeInteger(record.version) || record.version < 0) throw new Error('Invalid subscription version')\n if (record.lastEventId !== null && typeof record.lastEventId !== 'string') throw new Error('Invalid lastEventId')\n if (\n record.lastEventCreatedAt !== null\n && (!Number.isSafeInteger(record.lastEventCreatedAt) || record.lastEventCreatedAt < 0)\n ) throw new Error('Invalid lastEventCreatedAt')\n if (\n record.lastEventPreviousState !== undefined\n && record.lastEventPreviousState !== null\n && !SUBSCRIPTION_STATES.includes(record.lastEventPreviousState)\n ) throw new Error('Invalid lastEventPreviousState')\n if (\n record.pendingEventId !== undefined\n && record.pendingEventId !== null\n && (typeof record.pendingEventId !== 'string' || !record.pendingEventId.trim())\n ) throw new Error('Invalid pendingEventId')\n if (!Number.isFinite(record.updatedAt)) throw new Error('Invalid subscription updatedAt')\n}\n\nfunction sameSubscriptionRecord(left: SubscriptionRecord, right: SubscriptionRecord): boolean {\n return left.workspaceId === right.workspaceId\n && left.customerId === right.customerId\n && left.subscriptionId === right.subscriptionId\n && left.state === right.state\n && left.priceId === right.priceId\n && left.currentPeriodEnd === right.currentPeriodEnd\n && left.trialEnd === right.trialEnd\n && left.cancelAtPeriodEnd === right.cancelAtPeriodEnd\n && left.version === right.version\n && left.lastEventId === right.lastEventId\n && left.lastEventCreatedAt === right.lastEventCreatedAt\n && (left.lastEventPreviousState ?? null) === (right.lastEventPreviousState ?? null)\n && (left.pendingEventId ?? null) === (right.pendingEventId ?? null)\n && left.updatedAt === right.updatedAt\n}\n\nfunction isNodeEEXIST(err: unknown): boolean {\n return !!err && typeof err === 'object' && (err as { code?: string }).code === 'EEXIST'\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const fs = await import('node:fs/promises')\n const handle = await fs.open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n","/**\n * Stripe subscription webhook dispatcher.\n *\n * Receives `WebhookEnvelope` rows from `WebhookRouter`'s `deliver()`\n * callback, decodes them into typed `StripeBillingEvent` values, and\n * applies the corresponding state transition to the consumer's\n * `SubscriptionStore`. Emits a typed event the consumer subscribes to.\n *\n * Layering:\n *\n * Stripe → HTTP → WebhookRouter (verify + idempotency dedup)\n * ↓ deliver(envelope)\n * StripeBillingDispatcher (this file)\n * ↓\n * ├─ SubscriptionStore.saveIfVersion(...)\n * └─ emit(typed event) → consumer's subscriber\n *\n * Critical guarantees:\n *\n * 1. Idempotency at two layers — the router de-dupes at the event id;\n * the dispatcher's `saveIfVersion` defends against the second\n * router instance (multi-region) racing the same event. The\n * a finished claim is distinguishable from concurrent work. Listener\n * failure releases the claim and reaches the HTTP layer as a failure.\n *\n * 2. Order-independence — Stripe doesn't guarantee delivery order.\n * We persist the newest applied `event.created` timestamp and reject\n * older subscription events. Stripe timestamps have one-second resolution,\n * so equal timestamps require an authenticated current-state read.\n *\n * 3. Explicit unknown handling — events we don't have a handler for\n * are not dropped silently; we emit them as\n * `stripe.event_unhandled` so the consumer can log + alert if\n * they expected coverage that we don't ship.\n *\n * 4. Idempotency of the dispatcher itself — calling `dispatch()` with\n * an event whose id equals `lastEventId` on the loaded record is a\n * no-op that emits `stripe.event_replay` instead of advancing state.\n *\n * Events supported (8 critical + 2 lifecycle):\n *\n * customer.subscription.created\n * customer.subscription.updated\n * customer.subscription.deleted\n * customer.subscription.trial_will_end\n * customer.subscription.paused\n * customer.subscription.resumed\n * invoice.paid\n * invoice.payment_failed\n */\n\nimport type { WebhookEnvelope } from '../webhooks/router.js'\nimport {\n FileSystemAtomicIdempotencyStore,\n InMemoryAtomicIdempotencyStore,\n resolveAtomicIdempotencyStore,\n type AtomicIdempotencyStore,\n type IdempotencyRuntime,\n} from '../idempotency.js'\nimport { BillingError } from './errors.js'\nimport {\n applyTransition,\n isValidTransition,\n makeSubscriptionRecord,\n type SubscriptionRecord,\n type SubscriptionState,\n type SubscriptionStore,\n} from './subscription-state.js'\n\n/* ---------------------------------------------------------------------- */\n/* Stripe payload type subset */\n/* ---------------------------------------------------------------------- */\n\n/** Subset of Stripe's `Subscription` object we read. Keep narrow — the\n * full object has 70+ fields; we only need the ones that map to our\n * `SubscriptionRecord`. New fields land here on demand. */\nexport interface StripeSubscriptionSnapshot {\n id: string\n status: string\n customer: string | { id?: string }\n current_period_end?: number | null\n cancel_at_period_end?: boolean | null\n trial_end?: number | null\n items?: {\n data?: Array<{ price?: { id?: string } }>\n }\n /** Stripe `Subscription.metadata` — agents put their `workspaceId`\n * here at checkout time so we can route subsequent webhooks back to\n * the right tenant without an extra DB lookup. */\n metadata?: Record<string, string>\n}\n\ninterface StripeInvoicePayload {\n id: string\n /** Legacy Stripe versions expose the subscription at the top level. */\n subscription?: string | null\n /** Stripe 2025-03-31.basil and newer move subscription identity here. */\n parent?: {\n type?: string\n subscription_details?: {\n subscription?: string | { id?: string } | null\n metadata?: Record<string, string>\n } | null\n } | null\n customer?: string\n status?: string\n /** Cents. */\n amount_paid?: number\n amount_due?: number\n /** Lined up to subscription metadata at invoice generation. */\n metadata?: Record<string, string>\n}\n\ninterface StripeSubscriptionIdentity {\n customerId: string\n subscriptionId: string\n}\n\ninterface StripeEvent {\n id: string\n type: string\n created?: number\n data: { object: unknown }\n}\n\n/* ---------------------------------------------------------------------- */\n/* dispatcher contract */\n/* ---------------------------------------------------------------------- */\n\n/** Strongly-typed events the consumer can subscribe to. Each carries\n * enough context to drive downstream side effects without a second\n * DB round-trip (audit log row, Slack ping, in-app notification). */\nexport type StripeBillingEvent =\n | {\n kind: 'subscription.created'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.trial_ignored'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.updated'\n eventId: string\n previousState: SubscriptionState\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.deleted'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.trial_will_end'\n eventId: string\n record: SubscriptionRecord\n trialEndsAt: number\n }\n | {\n kind: 'subscription.paused'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.resumed'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'invoice.paid'\n eventId: string\n record: SubscriptionRecord | null\n invoiceId: string\n amountPaid: number\n }\n | {\n kind: 'invoice.zero_dollar_ignored'\n eventId: string\n invoiceId: string\n amountPaid: number\n }\n | {\n kind: 'invoice.payment_failed'\n eventId: string\n record: SubscriptionRecord | null\n invoiceId: string\n amountDue: number\n }\n | {\n kind: 'event_unhandled'\n eventId: string\n type: string\n }\n | {\n kind: 'event_replay'\n eventId: string\n type: string\n }\n | {\n kind: 'event_dropped_out_of_order'\n eventId: string\n type: string\n reason: string\n }\n\n/** Listener — production consumers must durably enqueue by `eventId` before\n * resolving. A throw releases the claim and reaches the HTTP boundary. */\nexport type StripeBillingListener = (event: StripeBillingEvent) => void | Promise<void>\n\nexport interface StripeEventIdempotencyStore extends AtomicIdempotencyStore {}\n\n/** Process-local store for direct dispatcher use and tests. */\nexport class InMemoryStripeEventIdempotencyStore extends InMemoryAtomicIdempotencyStore implements StripeEventIdempotencyStore {}\n\n/** Durable store for workers that share the same filesystem directory. */\nexport class FileSystemStripeEventIdempotencyStore extends FileSystemAtomicIdempotencyStore implements StripeEventIdempotencyStore {}\n\nexport interface StripeBillingDispatcherOptions {\n store: SubscriptionStore\n /** Maps a Stripe `customer.id` → the workspaceId the product uses to\n * key its `SubscriptionStore`. We default to reading\n * `subscription.metadata.workspaceId` (agents inject it at checkout\n * time); supply this override for products that key by customer id\n * directly or look up a join table. */\n resolveWorkspaceId?(input: {\n customerId: string\n subscriptionMetadata?: Record<string, string>\n invoiceMetadata?: Record<string, string>\n }): Promise<string | null> | string | null\n /** Retrieve the current subscription through an authenticated Stripe API\n * client. Equal `event.created` timestamps fail until this callback returns\n * an authoritative snapshot. */\n retrieveSubscription?(subscriptionId: string): Promise<StripeSubscriptionSnapshot>\n /** Single typed listener (most consumers want one — they route inside\n * it themselves). Compose multiple via `combineListeners(a, b)`. */\n listener?: StripeBillingListener\n /** Observe unexpected dispatcher errors before they are rethrown. */\n onError?(err: unknown, context: { eventId: string; type: string }): void\n /** Override `Date.now()` for tests. */\n now?(): number\n /** Max retries on `saveIfVersion` contention. Default 3. */\n maxCasRetries?: number\n /** Separate atomic event store for direct dispatcher calls. */\n idempotency?: StripeEventIdempotencyStore\n /** Runtime controls the safe default. Production fails closed without a\n * shared store; test/development use an in-memory store when omitted. */\n runtime?: IdempotencyRuntime\n idempotencyTtlMs?: number\n}\n\n/* ---------------------------------------------------------------------- */\n/* dispatcher */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Process a webhook envelope. Safe to call concurrently with itself —\n * the in-store CAS serializes per-workspace updates.\n */\nexport class StripeBillingDispatcher {\n private readonly store: SubscriptionStore\n private readonly resolveWorkspaceId: NonNullable<StripeBillingDispatcherOptions['resolveWorkspaceId']>\n private readonly retrieveSubscription?: StripeBillingDispatcherOptions['retrieveSubscription']\n private readonly listener?: StripeBillingListener\n private readonly onError: NonNullable<StripeBillingDispatcherOptions['onError']>\n private readonly now: () => number\n private readonly maxCasRetries: number\n private readonly idempotency: StripeEventIdempotencyStore\n private readonly idempotencyTtlMs: number\n\n constructor(opts: StripeBillingDispatcherOptions) {\n this.store = opts.store\n this.resolveWorkspaceId = opts.resolveWorkspaceId ?? defaultResolveWorkspaceId\n this.retrieveSubscription = opts.retrieveSubscription\n this.listener = opts.listener\n this.onError = opts.onError ?? defaultOnError\n this.now = opts.now ?? Date.now\n this.maxCasRetries = opts.maxCasRetries ?? 3\n this.idempotency = resolveAtomicIdempotencyStore({\n component: 'StripeBillingDispatcher',\n store: opts.idempotency,\n runtime: opts.runtime,\n })\n if (isProductionRuntime(opts.runtime) && !opts.listener) {\n throw new Error('StripeBillingDispatcher: production requires a durable billing listener')\n }\n this.idempotencyTtlMs = opts.idempotencyTtlMs ?? 7 * 24 * 60 * 60 * 1000\n }\n\n /** Drive one envelope through the pipeline. Idempotent w.r.t. the\n * event id (replays are a no-op + emit `event_replay`). */\n async dispatch(envelope: WebhookEnvelope): Promise<void> {\n const evt = envelope.payload as StripeEvent | undefined\n if (!evt || typeof evt !== 'object' || typeof evt.id !== 'string' || typeof evt.type !== 'string') {\n const error = new Error('Stripe envelope missing id or type')\n this.onError(error, {\n eventId: 'unknown',\n type: 'unknown',\n })\n throw error\n }\n const claimStatus = await this.idempotency.claimStatus(evt.id, this.idempotencyTtlMs)\n if (claimStatus === 'completed') {\n await this.emit({ kind: 'event_replay', eventId: evt.id, type: evt.type })\n return\n }\n if (claimStatus === 'in_progress') {\n const error = new BillingError({\n code: 'webhook_event_unknown',\n message: `Stripe event ${evt.id} is already in progress`,\n context: { eventId: evt.id },\n })\n throw error\n }\n try {\n await this.handle(evt)\n await this.idempotency.complete(evt.id)\n } catch (err) {\n try {\n await this.idempotency.release(evt.id)\n } catch (releaseError) {\n this.onError(releaseError, { eventId: evt.id, type: evt.type })\n }\n this.onError(err, { eventId: evt.id, type: evt.type })\n throw err\n }\n }\n\n private async handle(evt: StripeEvent): Promise<void> {\n switch (evt.type) {\n case 'customer.subscription.created':\n return this.handleSubCreated(evt)\n case 'customer.subscription.updated':\n return this.handleSubUpdated(evt)\n case 'customer.subscription.deleted':\n return this.handleSubDeleted(evt)\n case 'customer.subscription.trial_will_end':\n return this.handleTrialWillEnd(evt)\n case 'customer.subscription.paused':\n return this.handleSubLifecycle(evt, 'paused')\n case 'customer.subscription.resumed':\n return this.handleSubLifecycle(evt, 'active')\n case 'invoice.paid':\n return this.handleInvoicePaid(evt)\n case 'invoice.payment_failed':\n return this.handleInvoicePaymentFailed(evt)\n default:\n await this.emit({ kind: 'event_unhandled', eventId: evt.id, type: evt.type })\n return\n }\n }\n\n /* --------------------- subscription event handlers ------------------- */\n\n private async handleSubCreated(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n\n const existing = await this.store.load(workspaceId)\n // A `created` event names a subscription the record does not hold. That is\n // a foreign event unless the same customer is starting a new subscription\n // after the recorded one reached a terminal state — the resubscribe path.\n // Rebinding only from a terminal state keeps a live subscription bound.\n const rebinds =\n existing !== null &&\n !matchesSubscription(existing, identity) &&\n existing.customerId === identity.customerId &&\n isTerminalSubscriptionState(existing.state)\n if (existing && !matchesSubscription(existing, identity) && !rebinds) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(existing, evt)\n if (existing && existing.lastEventId === evt.id) {\n return this.emitPersisted(\n existing.state === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record: existing }\n : { kind: 'subscription.created', eventId: evt.id, record: existing },\n workspaceId,\n )\n }\n if (existing && isOlderEvent(existing, eventCreatedAt)) {\n return this.emitOlderEvent(evt, existing)\n }\n if (existing && isEqualTimestampEvent(existing, eventCreatedAt)) {\n return this.reconcileEqualTimestamp(evt, workspaceId, identity)\n }\n\n // Create-only: if a record already exists with a non-incomplete state\n // and this is a stale created event, treat as out-of-order.\n if (existing && !canApplyFreshCreate(existing.state)) {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: `existing state ${existing.state} cannot accept a fresh 'created'`,\n })\n }\n\n const nextState = parseState(sub.status, evt.id)\n const freshRecord = makeSubscriptionRecord({\n workspaceId,\n customerId: identity.customerId,\n subscriptionId: identity.subscriptionId,\n state: nextState,\n priceId: extractPriceId(sub),\n currentPeriodEnd: sub.current_period_end ?? null,\n trialEnd: sub.trial_end ?? null,\n cancelAtPeriodEnd: sub.cancel_at_period_end ?? false,\n eventId: evt.id,\n eventCreatedAt,\n pendingEventId: evt.id,\n now: this.now,\n })\n // A rebind writes a fresh record rather than a transition: `applyTransition`\n // spreads the base, which would carry the terminal subscription's id into\n // the new one. The version still advances, so a concurrent writer's\n // compare-and-set fails as it does on every other path.\n const record = !existing\n ? freshRecord\n : rebinds\n ? { ...freshRecord, version: existing.version + 1 }\n : applyTransition(\n existing,\n {\n state: nextState,\n priceId: extractPriceId(sub),\n currentPeriodEnd: sub.current_period_end ?? null,\n trialEnd: sub.trial_end ?? null,\n cancelAtPeriodEnd: sub.cancel_at_period_end ?? false,\n },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n const expectedVersion = existing?.version ?? 0\n const written = await this.cas(record, expectedVersion)\n if (!written) return this.emitUnbound(evt, 'subscription create lost a concurrent compare-and-set')\n await this.emitPersisted(\n record.state === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record }\n : { kind: 'subscription.created', eventId: evt.id, record },\n workspaceId,\n )\n }\n\n private async handleSubUpdated(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const nextState = parseState(sub.status, evt.id)\n\n await this.advance(evt, workspaceId, (current) => {\n if (current.lastEventId === evt.id) {\n return {\n emitOnly: nextState === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record: current }\n : {\n kind: 'subscription.updated',\n eventId: evt.id,\n previousState: current.lastEventPreviousState ?? current.state,\n record: current,\n },\n }\n }\n if (!isValidTransition(current.state, nextState)) return 'out_of_order'\n const next = applyTransition(\n current,\n {\n state: nextState,\n priceId: extractPriceId(sub) ?? current.priceId,\n currentPeriodEnd: sub.current_period_end ?? current.currentPeriodEnd,\n trialEnd: sub.trial_end ?? current.trialEnd,\n cancelAtPeriodEnd: sub.cancel_at_period_end ?? current.cancelAtPeriodEnd,\n },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n return {\n next,\n emit:\n nextState === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record: next }\n : { kind: 'subscription.updated', eventId: evt.id, previousState: current.state, record: next },\n }\n }, identity)\n }\n\n private async handleSubDeleted(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n\n await this.advance(evt, workspaceId, (current) => {\n if (current.lastEventId === evt.id) {\n return { emitOnly: { kind: 'subscription.deleted', eventId: evt.id, record: current } }\n }\n if (current.state === 'canceled') return 'replay' // terminal — fine to no-op\n const next = applyTransition(\n current,\n { state: 'canceled', priceId: null, currentPeriodEnd: sub.current_period_end ?? current.currentPeriodEnd },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n return {\n next,\n emit: { kind: 'subscription.deleted', eventId: evt.id, record: next },\n }\n }, identity)\n }\n\n private async handleTrialWillEnd(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const current = await this.store.load(workspaceId)\n if (!current) throw retryableStripeEvent(evt, 'subscription state is not available yet')\n if (!matchesSubscription(current, identity)) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(current, evt)\n if (current.lastEventId === evt.id) {\n return this.emitPersisted({\n kind: 'subscription.trial_will_end',\n eventId: evt.id,\n record: current,\n trialEndsAt: current.trialEnd ?? 0,\n }, workspaceId)\n }\n if (isOlderEvent(current, eventCreatedAt)) return this.emitOlderEvent(evt, current)\n if (isEqualTimestampEvent(current, eventCreatedAt)) {\n return this.reconcileEqualTimestamp(evt, workspaceId, identity)\n }\n // No state transition — trial_will_end is informational. Update\n // lastEventId so a replay is detected.\n const next: SubscriptionRecord = {\n ...current,\n lastEventId: evt.id,\n lastEventCreatedAt: eventCreatedAt,\n lastEventPreviousState: current.state,\n pendingEventId: evt.id,\n trialEnd: sub.trial_end ?? current.trialEnd,\n version: current.version + 1,\n updatedAt: this.now(),\n }\n const written = await this.cas(next, current.version)\n if (!written) return this.emitUnbound(evt, 'trial update lost a concurrent compare-and-set')\n await this.emitPersisted({\n kind: 'subscription.trial_will_end',\n eventId: evt.id,\n record: next,\n trialEndsAt: sub.trial_end ?? next.trialEnd ?? 0,\n }, workspaceId)\n }\n\n private async handleSubLifecycle(evt: StripeEvent, target: SubscriptionState): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n\n await this.advance(evt, workspaceId, (current) => {\n if (current.lastEventId === evt.id) {\n const kind = target === 'paused' ? 'subscription.paused' : 'subscription.resumed'\n return { emitOnly: { kind, eventId: evt.id, record: current } }\n }\n if (!isValidTransition(current.state, target)) return 'out_of_order'\n const next = applyTransition(\n current,\n { state: target },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n const kind = target === 'paused' ? 'subscription.paused' : 'subscription.resumed'\n return { next, emit: { kind, eventId: evt.id, record: next } }\n }, identity)\n }\n\n /* ----------------------- invoice event handlers ---------------------- */\n\n private async handleInvoicePaid(evt: StripeEvent): Promise<void> {\n const inv = evt.data.object as StripeInvoicePayload\n if (!invoiceIdentity(inv)) return this.emitUnbound(evt, 'paid invoice is missing customer or invoice id')\n const subscription = invoiceSubscription(inv)\n if (!subscription) return this.emitUnbound(evt, 'paid invoice is missing a subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: inv.customer ?? '',\n invoiceMetadata: subscription.metadata ?? inv.metadata,\n })\n const amountPaid = typeof inv.amount_paid === 'number' && Number.isFinite(inv.amount_paid) ? inv.amount_paid : 0\n if (amountPaid <= 0) {\n await this.emit({\n kind: 'invoice.zero_dollar_ignored',\n eventId: evt.id,\n invoiceId: inv.id,\n amountPaid,\n })\n return\n }\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const record = await this.store.load(workspaceId)\n if (!record) throw retryableStripeEvent(evt, 'paid invoice subscription state is not available yet')\n if (record.customerId !== inv.customer || record.subscriptionId !== subscription.subscriptionId) {\n return this.emitUnbound(evt, 'paid invoice identity does not match the workspace record')\n }\n await this.emit({\n kind: 'invoice.paid',\n eventId: evt.id,\n record,\n invoiceId: inv.id,\n amountPaid,\n })\n }\n\n private async handleInvoicePaymentFailed(evt: StripeEvent): Promise<void> {\n const inv = evt.data.object as StripeInvoicePayload\n if (!invoiceIdentity(inv)) return this.emitUnbound(evt, 'failed invoice is missing customer or invoice id')\n const subscription = invoiceSubscription(inv)\n if (!subscription) return this.emitUnbound(evt, 'failed invoice is missing a subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: inv.customer ?? '',\n invoiceMetadata: subscription.metadata ?? inv.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const record = await this.store.load(workspaceId)\n if (!record) throw retryableStripeEvent(evt, 'failed invoice subscription state is not available yet')\n if (record.customerId !== inv.customer || record.subscriptionId !== subscription.subscriptionId) {\n return this.emitUnbound(evt, 'failed invoice identity does not match the workspace record')\n }\n await this.emit({\n kind: 'invoice.payment_failed',\n eventId: evt.id,\n record,\n invoiceId: inv.id,\n amountDue: inv.amount_due ?? 0,\n })\n }\n\n /* ------------------------------- core -------------------------------- */\n\n /** Load, apply a transformation, CAS-write. The transformation may\n * return 'replay' / 'out_of_order' for the dispatcher to emit\n * diagnostic events instead. Retries on contention up to\n * `maxCasRetries`; if exhausted, throws so the event claim is released\n * and the provider can retry. */\n private async advance(\n evt: StripeEvent,\n workspaceId: string,\n transform: (current: SubscriptionRecord) =>\n | { next: SubscriptionRecord; emit: StripeBillingEvent }\n | { emitOnly: StripeBillingEvent }\n | 'replay'\n | 'out_of_order',\n identity: StripeSubscriptionIdentity,\n ): Promise<void> {\n for (let attempt = 0; attempt < this.maxCasRetries; attempt++) {\n const current = await this.store.load(workspaceId)\n if (!current) throw retryableStripeEvent(evt, 'subscription state is not available yet')\n if (identity && !matchesSubscription(current, identity)) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(current, evt)\n const eventCreatedAt = requireEventCreatedAt(evt)\n if (current.lastEventId !== evt.id && isOlderEvent(current, eventCreatedAt)) {\n return this.emitOlderEvent(evt, current)\n }\n if (current.lastEventId !== evt.id && isEqualTimestampEvent(current, eventCreatedAt)) {\n return this.reconcileEqualTimestamp(evt, workspaceId, identity)\n }\n const result = transform(current)\n if (result === 'replay') {\n return this.emit({ kind: 'event_replay', eventId: evt.id, type: evt.type })\n }\n if (result === 'out_of_order') {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: `current=${current.state}`,\n })\n }\n if ('emitOnly' in result) return this.emitPersisted(result.emitOnly, workspaceId)\n const written = await this.store.saveIfVersion(result.next, current.version)\n if (written) return this.emitPersisted(result.emit, workspaceId)\n }\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `CAS contention exhausted after ${this.maxCasRetries} attempts`,\n context: { workspaceId, eventId: evt.id },\n })\n }\n\n private async cas(record: SubscriptionRecord, expectedVersion: number): Promise<boolean> {\n // The record was built from one loaded version. Retrying it against a\n // newer expected version would overwrite another event with stale state.\n return this.store.saveIfVersion(record, expectedVersion)\n }\n\n private async emit(event: StripeBillingEvent): Promise<void> {\n if (!this.listener) return\n await this.listener(event)\n }\n\n private async emitPersisted(event: StripeBillingEvent, workspaceId: string): Promise<void> {\n await this.emit(event)\n await this.clearPendingSubscriptionEvent(workspaceId, event.eventId)\n }\n\n private assertNoPendingSubscriptionEvent(\n record: SubscriptionRecord | null,\n evt: StripeEvent,\n ): void {\n if (!record?.pendingEventId || record.pendingEventId === evt.id) return\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Subscription event ${record.pendingEventId} still needs durable delivery`,\n context: { workspaceId: record.workspaceId, eventId: evt.id },\n })\n }\n\n private async clearPendingSubscriptionEvent(workspaceId: string, eventId: string): Promise<void> {\n for (let attempt = 0; attempt < this.maxCasRetries; attempt++) {\n const current = await this.store.load(workspaceId)\n if (!current) throw new Error(`Subscription record ${workspaceId} disappeared after delivery`)\n if (current.pendingEventId === null || current.pendingEventId === undefined) return\n if (current.pendingEventId !== eventId) {\n throw new Error(`Subscription pending event changed from ${eventId} to ${current.pendingEventId}`)\n }\n const cleared: SubscriptionRecord = {\n ...current,\n pendingEventId: null,\n version: current.version + 1,\n updatedAt: this.now(),\n }\n if (await this.store.saveIfVersion(cleared, current.version)) return\n }\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Pending event clear exhausted after ${this.maxCasRetries} attempts`,\n context: { workspaceId, eventId },\n })\n }\n\n private async reconcileEqualTimestamp(\n evt: StripeEvent,\n workspaceId: string,\n expectedIdentity: StripeSubscriptionIdentity,\n ): Promise<void> {\n if (!this.retrieveSubscription) {\n throw retryableStripeEvent(evt, 'equal event.created timestamps require Stripe reconciliation')\n }\n const snapshot = await this.retrieveSubscription(expectedIdentity.subscriptionId)\n const canonicalIdentity = subscriptionIdentity(snapshot)\n if (\n !canonicalIdentity\n || canonicalIdentity.customerId !== expectedIdentity.customerId\n || canonicalIdentity.subscriptionId !== expectedIdentity.subscriptionId\n ) {\n throw retryableStripeEvent(evt, 'Stripe reconciliation returned a mismatched subscription')\n }\n const canonicalState = parseState(snapshot.status, evt.id)\n const eventCreatedAt = requireEventCreatedAt(evt)\n\n for (let attempt = 0; attempt < this.maxCasRetries; attempt++) {\n const current = await this.store.load(workspaceId)\n if (!current) throw retryableStripeEvent(evt, 'subscription state is not available yet')\n if (!matchesSubscription(current, expectedIdentity)) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(current, evt)\n if (current.lastEventId === evt.id) {\n return this.emitPersisted(canonicalBillingEvent(evt, current, current), workspaceId)\n }\n if (isOlderEvent(current, eventCreatedAt)) return this.emitOlderEvent(evt, current)\n if (!isEqualTimestampEvent(current, eventCreatedAt)) {\n throw retryableStripeEvent(evt, 'subscription state changed during Stripe reconciliation')\n }\n const next: SubscriptionRecord = {\n ...current,\n state: canonicalState,\n priceId: canonicalState === 'canceled' ? null : extractPriceId(snapshot),\n currentPeriodEnd: snapshot.current_period_end ?? null,\n trialEnd: snapshot.trial_end ?? null,\n cancelAtPeriodEnd: snapshot.cancel_at_period_end ?? false,\n version: current.version + 1,\n lastEventId: evt.id,\n lastEventCreatedAt: eventCreatedAt,\n lastEventPreviousState: current.state,\n pendingEventId: evt.id,\n updatedAt: this.now(),\n }\n if (await this.store.saveIfVersion(next, current.version)) {\n return this.emitPersisted(canonicalBillingEvent(evt, current, next), workspaceId)\n }\n }\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Stripe reconciliation contention exhausted after ${this.maxCasRetries} attempts`,\n context: { workspaceId, eventId: evt.id },\n })\n }\n\n private emitNoWorkspace(evt: StripeEvent): Promise<void> {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: 'workspaceId could not be resolved from event payload',\n })\n }\n\n private emitUnbound(evt: StripeEvent, reason: string): Promise<void> {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason,\n })\n }\n\n private emitOlderEvent(evt: StripeEvent, current: SubscriptionRecord): Promise<void> {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: `event.created=${evt.created} is older than stored=${current.lastEventCreatedAt}`,\n })\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* helpers */\n/* ---------------------------------------------------------------------- */\n\n/** Compose multiple listeners — fan out + collect errors. */\nexport function combineListeners(...listeners: StripeBillingListener[]): StripeBillingListener {\n return async (event) => {\n for (const l of listeners) await l(event)\n }\n}\n\nfunction defaultResolveWorkspaceId(input: { subscriptionMetadata?: Record<string, string>; invoiceMetadata?: Record<string, string> }): string | null {\n const sub = input.subscriptionMetadata?.workspaceId\n if (sub) return sub\n const inv = input.invoiceMetadata?.workspaceId\n return inv ?? null\n}\n\nfunction subscriptionIdentity(value: unknown): StripeSubscriptionIdentity | null {\n if (!value || typeof value !== 'object') return null\n const candidate = value as { customer?: unknown; id?: unknown }\n const customerId = readExpandableId(candidate.customer)\n if (!customerId) return null\n if (typeof candidate.id !== 'string' || !candidate.id.trim()) return null\n return { customerId, subscriptionId: candidate.id }\n}\n\nfunction invoiceIdentity(value: unknown): { customer: string; id: string } | null {\n if (!value || typeof value !== 'object') return null\n const candidate = value as { customer?: unknown; id?: unknown }\n if (typeof candidate.customer !== 'string' || !candidate.customer.trim()) return null\n if (typeof candidate.id !== 'string' || !candidate.id.trim()) return null\n return { customer: candidate.customer, id: candidate.id }\n}\n\nfunction invoiceSubscription(\n invoice: StripeInvoicePayload,\n): { subscriptionId: string; metadata?: Record<string, string> } | null {\n if (invoice.parent !== undefined && invoice.parent !== null) {\n if (invoice.parent.type !== 'subscription_details') return null\n const details = invoice.parent.subscription_details\n const subscriptionId = readExpandableId(details?.subscription)\n if (!subscriptionId) return null\n return {\n subscriptionId,\n ...(details?.metadata ? { metadata: details.metadata } : {}),\n }\n }\n const subscriptionId = readExpandableId(invoice.subscription)\n return subscriptionId ? { subscriptionId } : null\n}\n\nfunction readExpandableId(value: unknown): string | null {\n if (typeof value === 'string' && value.trim()) return value\n if (!value || typeof value !== 'object') return null\n const id = (value as { id?: unknown }).id\n return typeof id === 'string' && id.trim() ? id : null\n}\n\nfunction matchesSubscription(record: SubscriptionRecord, identity: StripeSubscriptionIdentity): boolean {\n return record.customerId === identity.customerId && record.subscriptionId === identity.subscriptionId\n}\n\nfunction requireEventCreatedAt(evt: StripeEvent): number {\n if (!Number.isSafeInteger(evt.created) || (evt.created as number) < 0) {\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: 'Stripe subscription event is missing a valid event.created timestamp',\n context: { eventId: evt.id },\n })\n }\n return evt.created as number\n}\n\nfunction isOlderEvent(record: SubscriptionRecord, eventCreatedAt: number): boolean {\n return record.lastEventCreatedAt !== null && eventCreatedAt < record.lastEventCreatedAt\n}\n\nfunction isEqualTimestampEvent(record: SubscriptionRecord, eventCreatedAt: number): boolean {\n return record.lastEventCreatedAt !== null && eventCreatedAt === record.lastEventCreatedAt\n}\n\nfunction retryableStripeEvent(evt: StripeEvent, message: string): BillingError {\n return new BillingError({\n code: 'webhook_event_unknown',\n message,\n context: { eventId: evt.id },\n })\n}\n\nfunction canonicalBillingEvent(\n evt: StripeEvent,\n previous: SubscriptionRecord,\n current: SubscriptionRecord,\n): StripeBillingEvent {\n if (current.state === 'canceled') {\n return { kind: 'subscription.deleted', eventId: evt.id, record: current }\n }\n if (current.state === 'trialing') {\n return { kind: 'subscription.trial_ignored', eventId: evt.id, record: current }\n }\n return {\n kind: 'subscription.updated',\n eventId: evt.id,\n previousState: previous.state,\n record: current,\n }\n}\n\nfunction isProductionRuntime(runtime: IdempotencyRuntime | undefined): boolean {\n if (runtime) return runtime === 'production'\n if (typeof process !== 'undefined' && process.env.VITEST) return false\n const nodeEnv = typeof process !== 'undefined' ? process.env.NODE_ENV : undefined\n return nodeEnv !== 'test' && nodeEnv !== 'development'\n}\n\nfunction defaultOnError(err: unknown, context: { eventId: string; type: string }): void {\n // eslint-disable-next-line no-console\n console.error('[StripeBillingDispatcher]', context, err)\n}\n\nfunction parseState(status: string, eventId: string): SubscriptionState {\n switch (status) {\n case 'incomplete':\n case 'incomplete_expired':\n case 'trialing':\n case 'active':\n case 'past_due':\n case 'canceled':\n case 'unpaid':\n case 'paused':\n return status\n default:\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Unknown Stripe subscription status '${status}'`,\n context: { eventId },\n })\n }\n}\n\n/**\n * States a subscription cannot leave, so the customer can only return through\n * a new subscription. A `created` event for a different subscription id is a\n * resubscribe from one of these, and a foreign event from any other state.\n */\nfunction isTerminalSubscriptionState(state: SubscriptionState): boolean {\n return state === 'canceled' || state === 'incomplete_expired'\n}\n\nfunction canApplyFreshCreate(state: SubscriptionState): boolean {\n // A 'created' event on a record that already advanced past incomplete means\n // the lifecycle was processed and a retried-late 'created' should be dropped.\n // A terminal state is the exception: it accepts the customer's next\n // subscription, which is the only way back from it.\n return state === 'incomplete' || isTerminalSubscriptionState(state)\n}\n\nfunction extractPriceId(sub: StripeSubscriptionSnapshot): string | null {\n return sub.items?.data?.[0]?.price?.id ?? null\n}\n","/**\n * Pricing plan scaffold + checkout URL generator.\n *\n * Per task constraint, this module does NOT bake in pricing. The\n * consumer (product agent) supplies the `PricingPlan[]` table at boot.\n * We standardize the SHAPE (id, name, monthly/yearly USD, feature\n * bullets, stripe price ids), the LOOKUP (`findPlan`, `requirePlan`),\n * and the CHECKOUT URL flow (`createCheckoutUrl`).\n *\n * The shape is intentionally USD-only with month/year recurrence.\n * Stripe supports more — multi-currency, week/quarter, usage-based,\n * tiered — but adding columns we don't use creates pressure to fill\n * them with defaults that mislead. When a product needs more, extend\n * the shape; do not work around it in the consumer.\n *\n * `createCheckoutUrl` writes the workspaceId into\n * `subscription_data.metadata.workspaceId` so the dispatcher's default\n * `resolveWorkspaceId` finds it on the first `customer.subscription.created`\n * webhook. THIS IS LOAD-BEARING: drop it and you have to write a\n * customer → workspace join table by hand.\n */\n\nimport type { StripeClient } from './tenant-config.js'\nimport { assertNoProductFreeTrial } from '../billing-access-policy.js'\n\nexport interface PricingPlanFeature {\n /** Short label rendered in pricing table rows. */\n label: string\n /** Optional richer description for the marketing page. */\n description?: string\n /** Whether the feature is included in this plan. Many products show\n * the same feature row across plans with a check/cross. */\n included: boolean\n}\n\nexport interface PricingPlan {\n /** Stable internal id — used by middleware to gate features, NOT the\n * Stripe price id. */\n id: string\n /** Display name in the pricing table. */\n name: string\n /** Monthly price in whole USD. `null` for plans that are yearly-only\n * or contact-sales tiers. */\n monthlyUsd: number | null\n /** Yearly price in whole USD. `null` for plans that don't offer\n * annual billing. */\n yearlyUsd: number | null\n /** Marketing feature bullets. */\n features: PricingPlanFeature[]\n /** Stripe `price_…` ids per cadence. At least one must be set if the\n * matching `*Usd` field is non-null. */\n stripePriceIds: {\n monthly?: string\n yearly?: string\n }\n /**\n * Legacy compatibility field. Positive values are rejected because\n * product-funded free trials are disabled.\n */\n trialDays?: number\n /** Optional metadata threaded into Stripe Subscription metadata — the\n * product can use these for analytics or grant-feature lookup. */\n metadata?: Record<string, string>\n}\n\nexport type BillingCadence = 'monthly' | 'yearly'\n\n/** Find a plan by id. Returns null when not found. */\nexport function findPlan(plans: readonly PricingPlan[], id: string): PricingPlan | null {\n return plans.find((p) => p.id === id) ?? null\n}\n\n/** Look up a plan or throw — for code paths where missing is a bug\n * (e.g., resolving a stored subscription's plan id back to a name). */\nexport function requirePlan(plans: readonly PricingPlan[], id: string): PricingPlan {\n const plan = findPlan(plans, id)\n if (!plan) throw new Error(`pricing: unknown plan id '${id}'`)\n return plan\n}\n\nexport interface CreateCheckoutUrlInput {\n /** Tenant key — written to subscription metadata for webhook routing. */\n workspaceId: string\n /** Plan from the consumer's pricing table. */\n plan: PricingPlan\n /** Which Stripe price id to charge against. */\n billing: BillingCadence\n /** Optional existing Stripe customer id — pre-fills the checkout. */\n customerId?: string\n /** Customer email — used by Stripe to pre-fill or to create a new\n * customer if `customerId` is absent. */\n customerEmail?: string\n /** Success/cancel URLs. Overrides the per-tenant defaults from\n * `TenantStripeConfig.successUrl`/`cancelUrl`. */\n successUrl?: string\n cancelUrl?: string\n /** Idempotency key — pass a deterministic key (e.g.,\n * `${workspaceId}:${plan.id}:${billing}`) so the same user clicking\n * twice gets the same checkout session. */\n idempotencyKey: string\n /** Legacy compatibility field. Positive values are rejected. */\n trialDays?: number\n /** Optional extra metadata mixed into Stripe metadata. */\n metadata?: Record<string, string>\n}\n\nexport interface CheckoutUrl {\n sessionId: string\n url: string\n}\n\n/**\n * Create a Stripe checkout session and return its hosted URL. Uses the\n * per-tenant `StripeClient` from `getStripeClient(productId)`.\n *\n * The workspaceId is written into TWO metadata maps:\n * - `metadata` (on the session itself, surfaces on `checkout.session.*`)\n * - `subscription_data[metadata]` (carries through to the Subscription\n * row Stripe creates, which is what `customer.subscription.*`\n * webhooks carry)\n *\n * Without the second, the dispatcher can't route the first\n * `subscription.created` event to a workspace. We've shipped that bug\n * before — written here once to make it impossible to forget.\n */\nexport async function createCheckoutUrl(\n client: StripeClient,\n input: CreateCheckoutUrlInput,\n): Promise<CheckoutUrl> {\n if (!input.workspaceId.trim()) throw new Error('pricing: workspaceId is required')\n if (!input.plan.id.trim() || !input.plan.name.trim()) throw new Error('pricing: plan id and name are required')\n if (!input.idempotencyKey.trim()) throw new Error('pricing: idempotencyKey is required')\n const priceId = input.plan.stripePriceIds[input.billing]\n if (!priceId) {\n throw new Error(`pricing: plan '${input.plan.id}' has no Stripe price for cadence '${input.billing}'`)\n }\n if (!/^price_[A-Za-z0-9_]+$/.test(priceId)) {\n throw new Error(`pricing: invalid Stripe price id '${priceId}'`)\n }\n if (!client.config.approvedPriceIds?.includes(priceId)) {\n throw new Error(`pricing: Stripe price '${priceId}' is not approved for product '${client.productId}'`)\n }\n const planUsd = input.billing === 'monthly' ? input.plan.monthlyUsd : input.plan.yearlyUsd\n if (typeof planUsd !== 'number' || !Number.isFinite(planUsd) || planUsd <= 0) {\n throw new Error(`pricing: ${input.billing} price must be greater than zero`)\n }\n const successUrl = input.successUrl ?? client.config.successUrl\n const cancelUrl = input.cancelUrl ?? client.config.cancelUrl\n if (!successUrl || !cancelUrl) {\n throw new Error('pricing: successUrl and cancelUrl required (per-call or in TenantStripeConfig)')\n }\n\n const trialDays = input.trialDays ?? input.plan.trialDays\n assertNoProductFreeTrial(trialDays)\n const body: Record<string, string | number | boolean | undefined> = {\n mode: 'subscription',\n success_url: successUrl,\n cancel_url: cancelUrl,\n 'line_items[0][price]': priceId,\n 'line_items[0][quantity]': 1,\n 'metadata[workspaceId]': input.workspaceId,\n 'metadata[planId]': input.plan.id,\n 'subscription_data[metadata][workspaceId]': input.workspaceId,\n 'subscription_data[metadata][planId]': input.plan.id,\n }\n if (input.customerId) body.customer = input.customerId\n if (input.customerEmail && !input.customerId) body.customer_email = input.customerEmail\n // Mix in plan-defined metadata + caller-supplied metadata.\n const extra = { ...(input.plan.metadata ?? {}), ...(input.metadata ?? {}) }\n for (const [k, v] of Object.entries(extra)) {\n if (k === 'workspaceId' || k === 'planId') {\n throw new Error(`pricing: metadata key '${k}' is reserved`)\n }\n body[`metadata[${k}]`] = v\n body[`subscription_data[metadata][${k}]`] = v\n }\n\n const created = await client.mutate<{ id: string; url: string }>(\n 'POST',\n '/checkout/sessions',\n body,\n input.idempotencyKey,\n )\n if (!created.url) {\n throw new Error('pricing: Stripe checkout response missing url')\n }\n return { sessionId: created.id, url: created.url }\n}\n\n/**\n * Create a Stripe customer-billing-portal session and return its URL.\n * The product calls this when a user clicks \"manage billing\" — the\n * portal handles cancel / change plan / update card without us\n * implementing those flows.\n */\nexport async function createBillingPortalUrl(\n client: StripeClient,\n input: { customerId: string; returnUrl: string; idempotencyKey: string },\n): Promise<{ sessionId: string; url: string }> {\n const created = await client.mutate<{ id: string; url: string }>(\n 'POST',\n '/billing_portal/sessions',\n {\n customer: input.customerId,\n return_url: input.returnUrl,\n },\n input.idempotencyKey,\n )\n return { sessionId: created.id, url: created.url }\n}\n","/**\n * Per-tenant Stripe configuration routing.\n *\n * Five product agents (legal, tax, gtm, creative, agent-builder) each\n * own a SEPARATE Stripe account. Reasons we pay the multi-account tax\n * rather than billing everyone through a single Tangle Stripe account:\n *\n * 1. Each product is a different LLC/legal entity for tax + dispute\n * handling. Customer chargebacks land on the product's account.\n * 2. Stripe Tax + Atlas are per-account; we can't share a single\n * Tax-collection setup across five SaaS products.\n * 3. Each product has its own pricing experiments; sharing one account\n * would force a shared products/prices namespace and surface\n * leak risk in the Stripe dashboard.\n *\n * The routing table maps `productId` (a Tangle-internal stable\n * identifier) to:\n * - Stripe Secret Key (`sk_live_…` or `rk_live_…`)\n * - Webhook signing secret (`whsec_…`) — used by the WebhookRouter's\n * `resolveSecret` callback.\n * - Optional success/cancel URL defaults the product wants used\n * unless the caller overrides per-checkout.\n *\n * Env-var convention is `STRIPE_SK_<PRODUCT_UPPER>` and\n * `STRIPE_WHSEC_<PRODUCT_UPPER>` — the resolver below honors that by\n * default. Consumers that store keys in a vault (Doppler, AWS Secrets\n * Manager) inject their own `TenantConfigResolver` instead.\n *\n * Critical invariant: this module NEVER caches resolved keys across\n * `getStripeClient()` calls without the consumer opting in. Stripe\n * encourages key rotation (Atlas docs); a cached `sk_…` outlives the\n * rotation. The default `EnvTenantConfigResolver` re-reads env every\n * call. Consumers that want a memoized cache wrap with\n * `memoizeResolver(resolver, ttlMs)`.\n */\n\nimport { ConfigError } from './errors.js'\n\n/** Stable product identifiers — kept in sync with the product registry.\n * Adding a product is a one-line addition; we centralize so a typo at\n * a call site (`'legal-agent'` vs `'legal'`) is a type error. */\nexport type ProductId =\n | 'legal'\n | 'tax'\n | 'gtm'\n | 'creative'\n | 'agent-builder'\n\nexport const PRODUCT_IDS: readonly ProductId[] = Object.freeze([\n 'legal',\n 'tax',\n 'gtm',\n 'creative',\n 'agent-builder',\n])\n\nexport interface TenantStripeConfig {\n productId: ProductId\n /** Stripe API secret key. Treat as opaque — do NOT log. */\n secretKey: string\n /** Webhook signing secret (`whsec_...`). */\n webhookSecret: string\n /** Price ids the product explicitly approved for checkout. */\n approvedPriceIds?: readonly string[]\n /** Optional default URLs the checkout/portal generators fall back to. */\n successUrl?: string\n cancelUrl?: string\n /** Free-form metadata threaded through to the product (e.g., the\n * Connect account id if you later migrate to Connect). */\n metadata?: Record<string, string>\n}\n\n/** Stateless resolver — called per `getStripeClient()` / `resolveSecret()`.\n * Implementations: read from env (default), read from a vault, read\n * from a workspace-scoped DB row (per-tenant Connect). */\nexport interface TenantConfigResolver {\n resolve(productId: ProductId): Promise<TenantStripeConfig | null> | TenantStripeConfig | null\n}\n\n/* ---------------------------------------------------------------------- */\n/* env resolver */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Reads `STRIPE_SK_<PRODUCT>` + `STRIPE_WHSEC_<PRODUCT>` from\n * `process.env`. Product id is upper-snake-cased (`agent-builder` →\n * `AGENT_BUILDER`).\n *\n * Optional defaults:\n * STRIPE_SUCCESS_URL_<PRODUCT>\n * STRIPE_CANCEL_URL_<PRODUCT>\n */\nexport class EnvTenantConfigResolver implements TenantConfigResolver {\n constructor(private readonly env: NodeJS.ProcessEnv = process.env) {}\n\n resolve(productId: ProductId): TenantStripeConfig | null {\n const key = envKey(productId)\n const sk = this.env[`STRIPE_SK_${key}`]\n const wh = this.env[`STRIPE_WHSEC_${key}`]\n if (!sk || !wh) return null\n const approvedPriceIds = (this.env[`STRIPE_APPROVED_PRICE_IDS_${key}`] ?? '')\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return {\n productId,\n secretKey: sk,\n webhookSecret: wh,\n ...(approvedPriceIds.length > 0 ? { approvedPriceIds } : {}),\n successUrl: this.env[`STRIPE_SUCCESS_URL_${key}`],\n cancelUrl: this.env[`STRIPE_CANCEL_URL_${key}`],\n }\n }\n}\n\n/**\n * Static resolver — pass a hardcoded map, useful for tests and for\n * deployments that pull from a vault at boot.\n */\nexport class StaticTenantConfigResolver implements TenantConfigResolver {\n constructor(private readonly table: Partial<Record<ProductId, TenantStripeConfig>>) {}\n resolve(productId: ProductId): TenantStripeConfig | null {\n return this.table[productId] ?? null\n }\n}\n\n/**\n * Memoize a resolver with a TTL. Used in production to avoid pounding\n * a remote vault on every webhook. Default 60s — short enough that a\n * key rotation lands within the next minute.\n */\nexport function memoizeResolver(inner: TenantConfigResolver, ttlMs = 60_000): TenantConfigResolver {\n const cache = new Map<ProductId, { config: TenantStripeConfig | null; expiresAt: number }>()\n return {\n async resolve(productId: ProductId) {\n const now = Date.now()\n const hit = cache.get(productId)\n if (hit && hit.expiresAt > now) return hit.config\n const config = await inner.resolve(productId)\n cache.set(productId, { config, expiresAt: now + ttlMs })\n return config\n },\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* the Stripe client handle */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Thin Stripe HTTP client handle. We do NOT depend on the `stripe`\n * npm package — same rationale as `stripe-pack`: keep the install\n * footprint zero, use `fetch` directly. The handle carries the\n * resolved secret + a Stripe-spec base URL so call sites can issue\n * scoped requests without re-resolving for every operation in a\n * batch.\n *\n * Idempotency-Key forwarding: every mutation MUST include an\n * `idempotency-key` header. Stripe enforces a 24h replay window\n * keyed off it. The `mutate()` helper accepts the key explicitly to\n * make it impossible to forget.\n */\nexport interface StripeClient {\n productId: ProductId\n config: TenantStripeConfig\n /** GET request — returns parsed JSON or throws on non-2xx. */\n get<T = unknown>(path: string, query?: Record<string, string>): Promise<T>\n /** Form-urlencoded POST/DELETE with idempotency. */\n mutate<T = unknown>(\n method: 'POST' | 'DELETE',\n path: string,\n body: Record<string, string | number | boolean | undefined>,\n idempotencyKey: string,\n ): Promise<T>\n}\n\nconst STRIPE_API = 'https://api.stripe.com/v1'\n\n/**\n * Look up the Stripe client for a product. Throws `ConfigError` if the\n * resolver returns null — the product agent fails its startup health\n * check and the deploy is held back. NEVER silently falls back to a\n * shared key.\n */\nexport async function getStripeClient(\n productId: ProductId,\n resolver: TenantConfigResolver,\n): Promise<StripeClient> {\n const config = await resolver.resolve(productId)\n if (!config) {\n throw new ConfigError({\n message: `Stripe not configured for product '${productId}'. Set STRIPE_SK_${envKey(productId)} and STRIPE_WHSEC_${envKey(productId)}.`,\n context: { productId },\n })\n }\n return buildClient(config)\n}\n\n/** Build a client from an already-resolved config — for callers that\n * manage resolution themselves (e.g., long-lived workers that\n * resolved at startup). */\nexport function buildStripeClient(config: TenantStripeConfig): StripeClient {\n return buildClient(config)\n}\n\nfunction buildClient(config: TenantStripeConfig): StripeClient {\n const auth = `Bearer ${config.secretKey}`\n return {\n productId: config.productId,\n config,\n async get<T>(path: string, query?: Record<string, string>): Promise<T> {\n const qs = query ? `?${new URLSearchParams(query).toString()}` : ''\n const res = await fetch(`${STRIPE_API}${path}${qs}`, {\n headers: { authorization: auth },\n signal: AbortSignal.timeout(10_000),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe ${path} ${res.status}: ${text.slice(0, 200)}`)\n }\n return (await res.json()) as T\n },\n async mutate<T>(\n method: 'POST' | 'DELETE',\n path: string,\n body: Record<string, string | number | boolean | undefined>,\n idempotencyKey: string,\n ): Promise<T> {\n const form = new URLSearchParams()\n for (const [k, v] of Object.entries(body)) {\n if (v === undefined) continue\n form.set(k, String(v))\n }\n const init: RequestInit = {\n method,\n headers: {\n authorization: auth,\n 'idempotency-key': idempotencyKey,\n ...(method === 'POST' ? { 'content-type': 'application/x-www-form-urlencoded' } : {}),\n },\n signal: AbortSignal.timeout(15_000),\n }\n if (method === 'POST') init.body = form\n const res = await fetch(`${STRIPE_API}${path}`, init)\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe ${path} ${res.status}: ${text.slice(0, 200)}`)\n }\n return (await res.json()) as T\n },\n }\n}\n\n/**\n * `WebhookRouter.resolveSecret` adapter. The router calls this with\n * the provider id and headers; we extract the product id from a\n * header the gateway routes by (`x-tangle-product`) and look it up.\n *\n * Why a header and not the URL path: the router is provider-keyed,\n * not product-keyed, by design. Products inject the header in their\n * gateway layer (Hono middleware in our case). The header is\n * authenticated as part of the gateway's edge auth — Stripe's own\n * signature still has to verify against the secret we return here,\n * so a forged header alone can't bypass anything.\n */\nexport function makeStripeSecretResolver(resolver: TenantConfigResolver) {\n return async function resolveSecret(\n providerId: string,\n headers: { [name: string]: string | string[] | undefined },\n ): Promise<string | null> {\n if (providerId !== 'stripe') return null\n const productHeader = headers['x-tangle-product']\n const productId = Array.isArray(productHeader) ? productHeader[0] : productHeader\n if (!productId || !isProductId(productId)) return null\n const config = await resolver.resolve(productId)\n return config?.webhookSecret ?? null\n }\n}\n\nfunction isProductId(s: string): s is ProductId {\n return (PRODUCT_IDS as readonly string[]).includes(s)\n}\n\nfunction envKey(productId: ProductId): string {\n return productId.toUpperCase().replace(/-/g, '_')\n}\n","/**\n * Drop-in middleware for product agents.\n *\n * Three primitives consumers wire into their HTTP layer (Hono, Express,\n * raw Workers `fetch` handler — middleware here is framework-neutral,\n * returns a `BillingGate` value the consumer chooses how to respond to).\n *\n * requireActiveSubscription({ workspaceId, store })\n * → 'allow' | { allowed: false, error: BillingError }\n *\n * withTrialAccess({ workspaceId, days, trialStore })\n * → always deny product-funded trial access\n *\n * getRemainingFreeTier({ workspaceId, freeTierStore })\n * → always { remaining: 0, total: 0, exhausted: true }\n *\n * Frameworks: we don't import Hono / Express. The middleware shape is a\n * pure async function returning a decision. The product wires it into\n * its framework with a 3-line adapter (see `examples/hono.ts`).\n *\n * Past-due policy: by default `requireActiveSubscription` allows\n * `past_due` (the dunning grace window — see `gateAccess` in\n * `subscription-state.ts`). Pass `denyPastDue: true` to override\n * per-route (e.g., legal-agent's \"file new petition\" gate where\n * irreversible actions justify a stricter rule).\n */\n\nimport { BillingError } from './errors.js'\nimport { decideBillingAccess } from '../billing-access-policy.js'\nimport {\n gateAccess,\n type SubscriptionRecord,\n type SubscriptionStore,\n} from './subscription-state.js'\n\n/* ---------------------------------------------------------------------- */\n/* requireActiveSubscription */\n/* ---------------------------------------------------------------------- */\n\nexport interface RequireActiveSubscriptionInput {\n workspaceId: string\n store: SubscriptionStore\n /** Parsed Platform proof for the owner or an explicitly named service/admin. */\n accessEvidence?: import('../billing-access-policy.js').TrustedPlatformEvidence\n /** Optional owner id to compare with Platform proof. */\n expectedUserId?: string\n /** Strict mode: reject `past_due`. Default false (allow with warn). */\n denyPastDue?: boolean\n}\n\nexport type SubscriptionGateResult =\n | { allowed: true; record: SubscriptionRecord; warn?: 'past_due' | 'trial_ending' }\n | { allowed: false; error: BillingError }\n\n/**\n * Gate decision for a route that requires an active subscription.\n *\n * Returns `{ allowed: true }` on `active` and on `past_due` (unless\n * `denyPastDue`). A `trialing` record is denied because product-funded\n * trials are disabled. Returns `{ allowed: false, error }` with a typed\n * `BillingError` for any other state.\n */\nexport async function requireActiveSubscription(\n input: RequireActiveSubscriptionInput,\n): Promise<SubscriptionGateResult> {\n const record = await input.store.load(input.workspaceId)\n if (!record) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'subscription_required',\n message: 'This workspace has no Stripe subscription.',\n context: { workspaceId: input.workspaceId },\n }),\n }\n }\n const accessDecision = decideBillingAccess({\n evidence: input.accessEvidence,\n expectedUserId: input.expectedUserId,\n })\n if (!accessDecision.allowed) {\n return {\n allowed: false,\n error: new BillingError({\n code: accessDecision.code,\n message: accessDecision.reason,\n context: { workspaceId: input.workspaceId },\n }),\n }\n }\n if (\n accessDecision.basis !== 'paid_subscription' &&\n accessDecision.principal.kind === 'human'\n ) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'paid_evidence_required',\n message: 'Active subscription access requires matching paid subscription evidence.',\n context: { workspaceId: input.workspaceId },\n }),\n }\n }\n if (\n input.accessEvidence?.funding.kind === 'paid_subscription' &&\n input.accessEvidence.funding.subscriptionId !== record.subscriptionId\n ) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'platform_evidence_subject_mismatch',\n message: 'Subscription evidence does not match the stored subscription.',\n context: { workspaceId: input.workspaceId, subscriptionId: record.subscriptionId },\n }),\n }\n }\n const decision = gateAccess(record.state)\n if (!decision.allowed) {\n return {\n allowed: false,\n error: new BillingError({\n code: decision.reason === 'trial_expired'\n ? 'trial_expired'\n : decision.reason === 'subscription_inactive'\n ? 'subscription_inactive'\n : decision.reason === 'subscription_past_due'\n ? 'subscription_past_due'\n : 'subscription_required',\n message: `Subscription is ${record.state}.`,\n context: {\n workspaceId: input.workspaceId,\n subscriptionId: record.subscriptionId,\n subscriptionState: record.state,\n },\n }),\n }\n }\n if (decision.warn === 'past_due' && input.denyPastDue) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'subscription_past_due',\n message: 'Subscription is past due — this action requires a current payment method.',\n context: {\n workspaceId: input.workspaceId,\n subscriptionId: record.subscriptionId,\n subscriptionState: record.state,\n },\n }),\n }\n }\n return { allowed: true, record, warn: decision.warn }\n}\n\n/* ---------------------------------------------------------------------- */\n/* withTrialAccess */\n/* ---------------------------------------------------------------------- */\n\n/** Legacy workspace timestamp store retained for source compatibility. */\nexport interface TrialStore {\n /** Returns a workspace creation timestamp (ms epoch), or null. */\n getCreatedAt(workspaceId: string): Promise<number | null> | number | null\n}\n\nexport interface WithTrialAccessInput {\n workspaceId: string\n /** Trial length in days from workspace creation. */\n days: number\n trialStore: TrialStore\n /** Optional `now` override for tests. */\n now?: () => number\n}\n\nexport interface TrialAccessResult {\n /** Always false while product-funded trials are disabled. */\n inTrial: boolean\n /** Always zero while product-funded trials are disabled. */\n daysRemaining: number\n /** Always null while product-funded trials are disabled. */\n trialEndsAt: number | null\n}\n\n/**\n * Legacy compatibility helper. Product-funded trials are disabled, so this\n * function always returns a denied trial result without reading the store.\n *\n * Callers must use `requireActiveSubscription` for product access.\n */\nexport async function withTrialAccess(input: WithTrialAccessInput): Promise<TrialAccessResult> {\n const decision = decideBillingAccess({})\n if (decision.allowed) throw new Error('billing: unexpected trial access allowance')\n return { inTrial: false, daysRemaining: 0, trialEndsAt: null }\n}\n\n/* ---------------------------------------------------------------------- */\n/* getRemainingFreeTier */\n/* ---------------------------------------------------------------------- */\n\n/** Legacy read-only counter store retained for source compatibility. */\nexport interface FreeTierStore {\n /** Returns `{ used, total }` for a workspace. */\n getUsage(workspaceId: string): Promise<{ used: number; total: number }> | { used: number; total: number }\n}\n\nexport interface GetRemainingFreeTierInput {\n workspaceId: string\n freeTierStore: FreeTierStore\n}\n\nexport interface FreeTierResult {\n /** Units (whatever the product counts: API calls, tokens, generations) still allowed. */\n remaining: number\n /** Total quota. */\n total: number\n /** Whether the quota is exhausted. */\n exhausted: boolean\n}\n\n/**\n * Legacy compatibility helper. Product-funded free-tier quota is disabled,\n * so this function always returns zero without reading the consumer store.\n */\nexport async function getRemainingFreeTier(\n input: GetRemainingFreeTierInput,\n): Promise<FreeTierResult> {\n const decision = decideBillingAccess({})\n if (decision.allowed) throw new Error('billing: unexpected free-tier allowance')\n return { remaining: 0, total: 0, exhausted: true }\n}\n\n/* ---------------------------------------------------------------------- */\n/* composed gate (trial + sub) */\n/* ---------------------------------------------------------------------- */\n\nexport interface ComposedGateInput {\n workspaceId: string\n store: SubscriptionStore\n accessEvidence?: import('../billing-access-policy.js').TrustedPlatformEvidence\n expectedUserId?: string\n trialStore?: TrialStore\n trialDays?: number\n denyPastDue?: boolean\n now?: () => number\n}\n\n/**\n * Legacy compatibility helper. Trial inputs are ignored and access depends\n * only on the paid subscription state.\n */\nexport async function gateSubscriptionOrTrial(\n input: ComposedGateInput,\n): Promise<SubscriptionGateResult & { viaTrial?: boolean; daysRemaining?: number }> {\n return requireActiveSubscription({\n workspaceId: input.workspaceId,\n store: input.store,\n accessEvidence: input.accessEvidence,\n expectedUserId: input.expectedUserId,\n denyPastDue: input.denyPastDue,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAa,eAAb,cAAkC,wBAAwB;CACxD;CACA;CAEA,YAAY,OAKT;EACD,MAAM;GACJ,MAAM,qBAAqB,MAAM,IAAI;GACrC,SAAS,MAAM;GACf,QAAQ,qBAAqB,MAAM,IAAI;GACvC,YAAY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B,OACkF;CAClF,OAAO,0BAA0B;EAC/B,aAAa,MAAM;EACnB,OAAO,MAAM;EACb,gBAAgB,MAAM;EACtB,gBAAgB,MAAM;EACtB,aAAa,MAAM;CACrB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/stripe/errors.ts","../../src/stripe/subscription-state.ts","../../src/stripe/webhooks.ts","../../src/stripe/pricing.ts","../../src/stripe/tenant-config.ts","../../src/stripe/middleware.ts"],"sourcesContent":["/**\n * Stripe billing error taxonomy.\n *\n * Layered on top of `IntegrationRuntimeError` (the cross-package error\n * contract) so a billing failure surfaces through the same normalization\n * pipeline the rest of the integration runtime uses: `status` maps to\n * an HTTP status, `userAction` carries the recommended next step\n * (connect / reconnect / contact_support), and `code` is stable across\n * versions for product analytics.\n *\n * Why a billing-specific subclass and not bare `IntegrationRuntimeError`:\n * three error classes carry a payload product agents NEED to branch on\n * (subscription state, tenant id, plan id). Encoding them as discriminated\n * subclasses keeps the call site `instanceof BillingError` lookup O(1)\n * and avoids stuffing them into `metadata` where they decay to `unknown`.\n *\n * Code mapping (`BillingErrorCode` → `IntegrationErrorCode`):\n * subscription_required → action_denied (403)\n * subscription_inactive → action_denied (403)\n * subscription_past_due → action_denied (403, w/ warning)\n * trial_expired → action_denied (403)\n * free_tier_exhausted → action_denied (403)\n * tenant_not_configured → provider_error (500) — operator bug\n * webhook_secret_missing→ provider_auth_failed (401) — config bug\n * webhook_event_unknown → input_invalid (400)\n * webhook_replay → input_invalid (400)\n */\n\nimport { IntegrationRuntimeError, type IntegrationUserAction } from '../errors.js'\nimport type { SubscriptionState } from './subscription-state.js'\n\nexport type BillingErrorCode =\n | 'subscription_required'\n | 'subscription_inactive'\n | 'subscription_past_due'\n | 'trial_expired'\n | 'free_tier_exhausted'\n | 'platform_evidence_required'\n | 'platform_evidence_expired'\n | 'platform_evidence_replayed'\n | 'platform_evidence_subject_mismatch'\n | 'email_verification_required'\n | 'real_email_required'\n | 'paid_evidence_required'\n | 'product_free_credits_disabled'\n | 'tenant_not_configured'\n | 'webhook_secret_missing'\n | 'webhook_event_unknown'\n | 'webhook_replay'\n\nexport interface BillingErrorContext {\n workspaceId?: string\n productId?: string\n subscriptionId?: string\n subscriptionState?: SubscriptionState\n planId?: string\n eventId?: string\n}\n\nexport class BillingError extends IntegrationRuntimeError {\n readonly billingCode: BillingErrorCode\n readonly context: BillingErrorContext\n\n constructor(input: {\n code: BillingErrorCode\n message: string\n context?: BillingErrorContext\n userAction?: IntegrationUserAction\n }) {\n super({\n code: mapToIntegrationCode(input.code),\n message: input.message,\n status: statusForBillingCode(input.code),\n userAction: input.userAction ?? defaultUserAction(input.code),\n metadata: input.context as Record<string, unknown> | undefined,\n })\n this.name = 'BillingError'\n this.billingCode = input.code\n this.context = input.context ?? {}\n }\n}\n\n/** Distinct subclass: operator missed an environment variable. Surfaces\n * with a different `userAction` (`contact_support`) so the consumer\n * doesn't render a \"connect Stripe\" CTA to a customer for what is in\n * fact a backend deploy bug. */\nexport class ConfigError extends BillingError {\n constructor(input: { message: string; context?: BillingErrorContext }) {\n super({\n code: 'tenant_not_configured',\n message: input.message,\n context: input.context,\n userAction: { type: 'contact_support', label: 'Contact support' },\n })\n this.name = 'ConfigError'\n }\n}\n\nfunction mapToIntegrationCode(code: BillingErrorCode): IntegrationRuntimeError['code'] {\n switch (code) {\n case 'subscription_required':\n case 'subscription_inactive':\n case 'subscription_past_due':\n case 'trial_expired':\n case 'free_tier_exhausted':\n case 'platform_evidence_required':\n case 'platform_evidence_expired':\n case 'platform_evidence_replayed':\n case 'platform_evidence_subject_mismatch':\n case 'email_verification_required':\n case 'real_email_required':\n case 'paid_evidence_required':\n case 'product_free_credits_disabled':\n return 'action_denied'\n case 'tenant_not_configured':\n return 'provider_error'\n case 'webhook_secret_missing':\n return 'provider_auth_failed'\n case 'webhook_event_unknown':\n case 'webhook_replay':\n return 'input_invalid'\n }\n}\n\nfunction statusForBillingCode(code: BillingErrorCode): number {\n switch (code) {\n case 'subscription_required':\n case 'subscription_inactive':\n case 'subscription_past_due':\n case 'trial_expired':\n case 'free_tier_exhausted':\n case 'platform_evidence_required':\n case 'platform_evidence_expired':\n case 'platform_evidence_replayed':\n case 'platform_evidence_subject_mismatch':\n case 'email_verification_required':\n case 'real_email_required':\n case 'paid_evidence_required':\n case 'product_free_credits_disabled':\n return 403\n case 'tenant_not_configured':\n return 500\n case 'webhook_secret_missing':\n return 401\n case 'webhook_event_unknown':\n case 'webhook_replay':\n return 400\n }\n}\n\nfunction defaultUserAction(code: BillingErrorCode): IntegrationUserAction | undefined {\n switch (code) {\n case 'subscription_required':\n return { type: 'change_request', label: 'Subscribe to continue' }\n case 'subscription_inactive':\n case 'subscription_past_due':\n return { type: 'change_request', label: 'Update billing' }\n case 'trial_expired':\n return { type: 'change_request', label: 'Choose a plan' }\n case 'free_tier_exhausted':\n return { type: 'change_request', label: 'Upgrade for more usage' }\n case 'platform_evidence_required':\n case 'platform_evidence_expired':\n case 'platform_evidence_replayed':\n case 'platform_evidence_subject_mismatch':\n case 'email_verification_required':\n case 'real_email_required':\n case 'paid_evidence_required':\n case 'product_free_credits_disabled':\n return { type: 'change_request', label: 'Verify access to continue' }\n case 'tenant_not_configured':\n case 'webhook_secret_missing':\n return { type: 'contact_support', label: 'Contact support' }\n case 'webhook_event_unknown':\n case 'webhook_replay':\n return undefined\n }\n}\n","/**\n * Subscription state machine.\n *\n * Stripe ships eight terminal states on `Subscription.status`. We model\n * them verbatim — never normalize, never collapse — so the state\n * persisted in product DBs round-trips Stripe webhooks losslessly.\n *\n * incomplete — first invoice not paid within 23 hours\n * incomplete_expired — first invoice failed, no retry coming\n * trialing — inside a trial window (not product access)\n * active — paying, current\n * past_due — auto-renewal failed; grace period running\n * canceled — terminal; ended at period boundary or hard\n * unpaid — past_due → unpaid after retries exhausted\n * paused — operator-paused (collection_method=pause_collection)\n *\n * Transition rules below derive STRICTLY from the Stripe state diagram\n * (https://docs.stripe.com/billing/subscriptions/overview#subscription-statuses)\n * — the dispatcher in `webhooks.ts` calls `applyTransition()` which\n * rejects any state pair Stripe never emits. This catches manual-edit\n * bugs (someone POSTing a `force_state` admin endpoint) and tests for\n * the consumer's state store at the same time.\n *\n * Persistence: products pick an adapter (FS, D1, Postgres, in-memory).\n * The interface is intentionally minimal — load(), save(), and a\n * compare-and-set `saveIfVersion()` that defends against duplicate\n * webhook delivery racing the same store. Stripe re-delivers failed\n * webhooks for 3 days; the in-flight one and the retry will both write\n * the same key. `WebhookRouter`'s idempotency hook short-circuits at\n * the event level, but a misconfigured deploy with two routers in\n * different regions both processing the same event needs the second\n * line of defense here.\n *\n * `requireActiveSubscription()` (middleware) calls `gateAccess(state)`\n * to map state → access-decision. `past_due` is intentionally allowed\n * with a warning flag — the dunning period is when products MOST need\n * customers to keep using the product so they remember why they pay,\n * but the UI should render the \"card declined\" banner.\n */\n\nimport { BillingError } from './errors.js'\n\nexport type SubscriptionState =\n | 'incomplete'\n | 'incomplete_expired'\n | 'trialing'\n | 'active'\n | 'past_due'\n | 'canceled'\n | 'unpaid'\n | 'paused'\n\n/** All eight states, exported so tests + consumers can enumerate. */\nexport const SUBSCRIPTION_STATES: readonly SubscriptionState[] = Object.freeze([\n 'incomplete',\n 'incomplete_expired',\n 'trialing',\n 'active',\n 'past_due',\n 'canceled',\n 'unpaid',\n 'paused',\n])\n\n/** Tristate access decision. `warn` means the route runs, but the UI\n * should render a billing banner. */\nexport type AccessDecision =\n | { allowed: true; warn?: 'past_due' | 'trial_ending' }\n | { allowed: false; reason: 'no_subscription' | 'subscription_inactive' | 'subscription_past_due' | 'trial_expired' }\n\nexport interface SubscriptionRecord {\n /** Tenant key the product uses to look up \"is this workspace paying?\" —\n * typically a workspaceId, but products that bill per-user or\n * per-organization can swap in their own scope. */\n workspaceId: string\n /** Stripe customer id (`cus_...`). */\n customerId: string\n /** Stripe subscription id (`sub_...`). */\n subscriptionId: string\n /** Last-known subscription state — updated by webhook handlers. */\n state: SubscriptionState\n /** Stripe price id active on the subscription. Null for canceled. */\n priceId: string | null\n /** Current billing period end (unix seconds). Used by middleware to\n * emit `trial_ending` warning in the last 72h of a trial. */\n currentPeriodEnd: number | null\n /** Trial end (unix seconds), null for non-trial subs. */\n trialEnd: number | null\n /** `cancel_at_period_end` flag — once true, state stays `active` until\n * the period ends, then transitions to `canceled`. */\n cancelAtPeriodEnd: boolean\n /** Monotonic write counter for optimistic concurrency. Incremented on\n * every save; persistence adapters use it for CAS. */\n version: number\n /** Last event id we processed for this subscription — defends against\n * Stripe re-delivering the same event and us racing the dedupe store. */\n lastEventId: string | null\n /** Stripe `event.created` for the newest applied subscription event. */\n lastEventCreatedAt: number | null\n /** State before the newest applied event. This lets a failed durable\n * listener retry the exact typed update after the state write succeeded. */\n lastEventPreviousState?: SubscriptionState | null\n /** Event whose state is durable but whose listener has not completed.\n * A different subscription event cannot advance until this is cleared. */\n pendingEventId?: string | null\n /** Wall-clock ms of last successful write. */\n updatedAt: number\n}\n\n/** Persistence adapter contract. Three operations — pick the storage\n * layer that matches the product's existing infra. Adapters live below\n * (in-memory + filesystem). D1 / Postgres are one-liners on top. */\nexport interface SubscriptionStore {\n load(workspaceId: string): Promise<SubscriptionRecord | null>\n save(record: SubscriptionRecord): Promise<void>\n /** Compare-and-set on `version`. Returns false if the stored record's\n * version doesn't match `expectedVersion` (someone else wrote first).\n * Implementations MUST return false rather than throw on contention —\n * the caller branches on the bool. */\n saveIfVersion(record: SubscriptionRecord, expectedVersion: number): Promise<boolean>\n}\n\n/** Transitions table — adjacency map of legal {from → to} edges derived\n * from Stripe's subscription status diagram. Used by `applyTransition`. */\nconst TRANSITIONS: Readonly<Record<SubscriptionState, ReadonlySet<SubscriptionState>>> = Object.freeze({\n incomplete: new Set<SubscriptionState>(['active', 'trialing', 'incomplete_expired', 'canceled']),\n incomplete_expired: new Set<SubscriptionState>([]),\n trialing: new Set<SubscriptionState>(['active', 'past_due', 'canceled', 'paused', 'unpaid']),\n active: new Set<SubscriptionState>(['past_due', 'canceled', 'paused', 'unpaid', 'trialing']),\n past_due: new Set<SubscriptionState>(['active', 'canceled', 'unpaid', 'paused']),\n canceled: new Set<SubscriptionState>([]),\n unpaid: new Set<SubscriptionState>(['active', 'canceled', 'past_due']),\n paused: new Set<SubscriptionState>(['active', 'canceled', 'past_due']),\n})\n\n/** Returns true if `to` is reachable from `from` in one Stripe transition.\n * Self-edges are accepted (a webhook can re-emit the current state on\n * any field change). */\nexport function isValidTransition(from: SubscriptionState, to: SubscriptionState): boolean {\n if (from === to) return true\n return TRANSITIONS[from].has(to)\n}\n\n/** Apply a state transition to a record. Throws `BillingError` if Stripe\n * would never emit this edge (defensive — a bad admin tool POSTing a\n * raw state update gets refused). Returns the new record without writing. */\nexport function applyTransition(\n current: SubscriptionRecord,\n next: Partial<SubscriptionRecord> & { state: SubscriptionState },\n options: {\n eventId?: string\n eventCreatedAt?: number\n pendingEventId?: string | null\n now?: () => number\n } = {},\n): SubscriptionRecord {\n if (!isValidTransition(current.state, next.state)) {\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Illegal subscription transition ${current.state} → ${next.state}`,\n context: {\n workspaceId: current.workspaceId,\n subscriptionId: current.subscriptionId,\n subscriptionState: current.state,\n eventId: options.eventId,\n },\n })\n }\n const now = (options.now ?? Date.now)()\n return {\n ...current,\n ...next,\n version: current.version + 1,\n lastEventId: options.eventId ?? current.lastEventId,\n lastEventCreatedAt: options.eventCreatedAt ?? current.lastEventCreatedAt,\n lastEventPreviousState: options.eventId ? current.state : (current.lastEventPreviousState ?? null),\n pendingEventId: options.pendingEventId !== undefined\n ? options.pendingEventId\n : (current.pendingEventId ?? null),\n updatedAt: now,\n }\n}\n\n/**\n * Map a state to an access decision.\n *\n * Rule rationale:\n * active → allow\n * trialing → deny (product-funded trials are disabled)\n * past_due → allow + warn (dunning grace)\n * paused → deny (operator action; resume restores)\n * canceled, unpaid → deny (terminal financial states)\n * incomplete, incomplete_expired → deny (never paid; first invoice failed)\n *\n * Note `requireActiveSubscription` in `middleware.ts` is the consumer of\n * this — gating is centralized here so the rule lives in one place. The\n * mapping is one assertion in the test suite. Changing the rule for one\n * product (e.g., legal-agent wants past_due to deny) is a per-call\n * `overrides` option on the middleware, NOT a fork of this function.\n */\nexport function gateAccess(state: SubscriptionState): AccessDecision {\n switch (state) {\n case 'active':\n return { allowed: true }\n case 'trialing':\n return { allowed: false, reason: 'trial_expired' }\n case 'past_due':\n return { allowed: true, warn: 'past_due' }\n case 'paused':\n return { allowed: false, reason: 'subscription_past_due' }\n case 'canceled':\n case 'unpaid':\n return { allowed: false, reason: 'subscription_inactive' }\n case 'incomplete':\n case 'incomplete_expired':\n return { allowed: false, reason: 'subscription_inactive' }\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* persistence adapter: in-memory */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Process-local store. Useful for tests; product instances should pick\n * `FileSystemSubscriptionStore` or wire D1 / Postgres. Implements proper\n * CAS — concurrent saves with stale versions are rejected.\n */\nexport class InMemorySubscriptionStore implements SubscriptionStore {\n private readonly records = new Map<string, SubscriptionRecord>()\n\n async load(workspaceId: string): Promise<SubscriptionRecord | null> {\n const r = this.records.get(workspaceId)\n return r ? { ...r } : null\n }\n\n async save(record: SubscriptionRecord): Promise<void> {\n this.records.set(record.workspaceId, { ...record })\n }\n\n async saveIfVersion(record: SubscriptionRecord, expectedVersion: number): Promise<boolean> {\n const current = this.records.get(record.workspaceId)\n if (current && current.version !== expectedVersion) return false\n if (!current && expectedVersion !== 0) return false\n this.records.set(record.workspaceId, { ...record })\n return true\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* persistence adapter: filesystem */\n/* ---------------------------------------------------------------------- */\n\n/**\n * File-per-workspace JSON store. One file per workspace under\n * `<rootDir>/<workspaceId>.versions/<version>.json`. Each version is written\n * completely and then hard-linked to its final path. Two processes racing the\n * same expected version therefore contend on one atomic filesystem operation.\n *\n * Why per-workspace versions and not one JSONL: subscriptions are accessed by\n * workspace id. Reads inspect only that workspace's immutable versions.\n *\n * The store does NOT use `fs.watch` — webhooks are the only writer in\n * production, and webhooks always go through `applyTransition()` →\n * `saveIfVersion()`, so the CAS catches the race.\n */\nexport class FileSystemSubscriptionStore implements SubscriptionStore {\n constructor(private readonly rootDir: string) {\n if (!rootDir.trim()) throw new Error('FileSystemSubscriptionStore requires a root directory')\n }\n\n async load(workspaceId: string): Promise<SubscriptionRecord | null> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n const versionDir = await this.versionDir(workspaceId)\n let versionFiles: string[] = []\n try {\n versionFiles = (await fs.readdir(versionDir))\n .filter((file) => /^\\d+\\.json$/.test(file))\n .sort((left, right) => Number.parseInt(right, 10) - Number.parseInt(left, 10))\n } catch (err) {\n if (!isNodeENOENT(err)) throw err\n }\n\n const candidates: SubscriptionRecord[] = []\n if (versionFiles[0]) {\n candidates.push(await this.readRecord(path.join(versionDir, versionFiles[0]), workspaceId))\n }\n const legacyFile = path.join(this.rootDir, this.fileName(workspaceId))\n try {\n candidates.push(await this.readRecord(legacyFile, workspaceId))\n } catch (err) {\n if (!isNodeENOENT(err)) throw err\n }\n if (candidates.length === 0) return null\n candidates.sort((left, right) => right.version - left.version)\n if (\n candidates[1]\n && candidates[0]!.version === candidates[1].version\n && !sameSubscriptionRecord(candidates[0]!, candidates[1])\n ) {\n throw new Error(`Conflicting subscription version ${candidates[0]!.version} for ${workspaceId}`)\n }\n return { ...candidates[0]! }\n }\n\n async save(record: SubscriptionRecord): Promise<void> {\n assertSubscriptionRecord(record)\n const existing = await this.load(record.workspaceId)\n if (existing) {\n if (existing.version > record.version) {\n throw new Error(`Stale subscription save for ${record.workspaceId}`)\n }\n if (existing.version === record.version) {\n if (sameSubscriptionRecord(existing, record)) return\n throw new Error(`Conflicting subscription version ${record.version} for ${record.workspaceId}`)\n }\n if (record.version !== existing.version + 1) {\n throw new Error(`Subscription save must advance exactly one version for ${record.workspaceId}`)\n }\n } else if (record.version !== 0) {\n throw new Error(`Initial subscription version must be 0 for ${record.workspaceId}`)\n }\n if (!(await this.writeVersion(record))) {\n const winner = await this.load(record.workspaceId)\n if (winner && sameSubscriptionRecord(winner, record)) return\n throw new Error(`Subscription write contention for ${record.workspaceId}`)\n }\n }\n\n async saveIfVersion(record: SubscriptionRecord, expectedVersion: number): Promise<boolean> {\n assertSubscriptionRecord(record)\n if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) return false\n const existing = await this.load(record.workspaceId)\n if (existing && existing.version !== expectedVersion) return false\n if (!existing && expectedVersion !== 0) return false\n if (existing && record.version !== expectedVersion + 1) return false\n if (!existing && record.version !== 0) return false\n return this.writeVersion(record)\n }\n\n private async readRecord(file: string, expectedWorkspaceId: string): Promise<SubscriptionRecord> {\n const fs = await import('node:fs/promises')\n const raw = await fs.readFile(file, 'utf8')\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new Error(`Invalid subscription JSON at ${file}`)\n }\n const record = normalizeSubscriptionRecord(parsed)\n if (record.workspaceId !== expectedWorkspaceId) {\n throw new Error(`Subscription workspace mismatch at ${file}`)\n }\n return record\n }\n\n private async writeVersion(record: SubscriptionRecord): Promise<boolean> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n const versionDir = await this.versionDir(record.workspaceId)\n await fs.mkdir(versionDir, { recursive: true, mode: 0o700 })\n const finalFile = path.join(versionDir, `${record.version}.json`)\n const tmp = path.join(versionDir, `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`)\n const handle = await fs.open(tmp, 'wx', 0o600)\n try {\n await handle.writeFile(JSON.stringify(record), 'utf8')\n await handle.sync()\n await handle.close()\n try {\n await fs.link(tmp, finalFile)\n await syncDirectory(versionDir)\n return true\n } catch (err) {\n if (isNodeEEXIST(err)) return false\n throw err\n }\n } catch (err) {\n throw err\n } finally {\n await handle.close().catch(() => undefined)\n await fs.unlink(tmp).catch(() => undefined)\n }\n }\n\n private async versionDir(workspaceId: string): Promise<string> {\n const path = await import('node:path')\n return path.join(this.rootDir, `${this.fileName(workspaceId)}.versions`)\n }\n\n /** Safe filename: workspaceId is restricted to a charset that maps 1:1\n * to a posix filename. Anything outside is hex-encoded so we can never\n * escape the rootDir via `../`. */\n private fileName(workspaceId: string): string {\n if (!/^[A-Za-z0-9_.-]+$/.test(workspaceId)) {\n return `${Buffer.from(workspaceId, 'utf-8').toString('hex')}.json`\n }\n return `${workspaceId}.json`\n }\n}\n\nfunction isNodeENOENT(err: unknown): boolean {\n return !!err && typeof err === 'object' && (err as { code?: string }).code === 'ENOENT'\n}\n\n/* ---------------------------------------------------------------------- */\n/* construction helper */\n/* ---------------------------------------------------------------------- */\n\n/** Convenience constructor for the initial record after a checkout\n * succeeds. The webhook handler for `customer.subscription.created` calls\n * this — exposed for tests + manual-fix scripts that need to backfill. */\nexport function makeSubscriptionRecord(input: {\n workspaceId: string\n customerId: string\n subscriptionId: string\n state: SubscriptionState\n priceId: string | null\n currentPeriodEnd: number | null\n trialEnd?: number | null\n cancelAtPeriodEnd?: boolean\n eventId?: string\n eventCreatedAt?: number\n pendingEventId?: string | null\n now?: () => number\n}): SubscriptionRecord {\n const now = (input.now ?? Date.now)()\n return {\n workspaceId: input.workspaceId,\n customerId: input.customerId,\n subscriptionId: input.subscriptionId,\n state: input.state,\n priceId: input.priceId,\n currentPeriodEnd: input.currentPeriodEnd,\n trialEnd: input.trialEnd ?? null,\n cancelAtPeriodEnd: input.cancelAtPeriodEnd ?? false,\n version: 0,\n lastEventId: input.eventId ?? null,\n lastEventCreatedAt: input.eventCreatedAt ?? null,\n lastEventPreviousState: null,\n pendingEventId: input.pendingEventId ?? null,\n updatedAt: now,\n }\n}\n\nfunction normalizeSubscriptionRecord(value: unknown): SubscriptionRecord {\n if (!value || typeof value !== 'object') throw new Error('Invalid subscription record')\n const candidate = value as Partial<SubscriptionRecord>\n const record = {\n ...candidate,\n lastEventCreatedAt: candidate.lastEventCreatedAt ?? null,\n lastEventPreviousState: candidate.lastEventPreviousState ?? null,\n pendingEventId: candidate.pendingEventId ?? null,\n } as SubscriptionRecord\n assertSubscriptionRecord(record)\n return record\n}\n\nfunction assertSubscriptionRecord(record: SubscriptionRecord): void {\n if (!record || typeof record !== 'object') throw new Error('Invalid subscription record')\n if (!record.workspaceId?.trim()) throw new Error('Subscription workspaceId is required')\n if (!record.customerId?.trim()) throw new Error('Subscription customerId is required')\n if (!record.subscriptionId?.trim()) throw new Error('Subscription subscriptionId is required')\n if (!SUBSCRIPTION_STATES.includes(record.state)) throw new Error('Invalid subscription state')\n if (!Number.isSafeInteger(record.version) || record.version < 0) throw new Error('Invalid subscription version')\n if (record.lastEventId !== null && typeof record.lastEventId !== 'string') throw new Error('Invalid lastEventId')\n if (\n record.lastEventCreatedAt !== null\n && (!Number.isSafeInteger(record.lastEventCreatedAt) || record.lastEventCreatedAt < 0)\n ) throw new Error('Invalid lastEventCreatedAt')\n if (\n record.lastEventPreviousState !== undefined\n && record.lastEventPreviousState !== null\n && !SUBSCRIPTION_STATES.includes(record.lastEventPreviousState)\n ) throw new Error('Invalid lastEventPreviousState')\n if (\n record.pendingEventId !== undefined\n && record.pendingEventId !== null\n && (typeof record.pendingEventId !== 'string' || !record.pendingEventId.trim())\n ) throw new Error('Invalid pendingEventId')\n if (!Number.isFinite(record.updatedAt)) throw new Error('Invalid subscription updatedAt')\n}\n\nfunction sameSubscriptionRecord(left: SubscriptionRecord, right: SubscriptionRecord): boolean {\n return left.workspaceId === right.workspaceId\n && left.customerId === right.customerId\n && left.subscriptionId === right.subscriptionId\n && left.state === right.state\n && left.priceId === right.priceId\n && left.currentPeriodEnd === right.currentPeriodEnd\n && left.trialEnd === right.trialEnd\n && left.cancelAtPeriodEnd === right.cancelAtPeriodEnd\n && left.version === right.version\n && left.lastEventId === right.lastEventId\n && left.lastEventCreatedAt === right.lastEventCreatedAt\n && (left.lastEventPreviousState ?? null) === (right.lastEventPreviousState ?? null)\n && (left.pendingEventId ?? null) === (right.pendingEventId ?? null)\n && left.updatedAt === right.updatedAt\n}\n\nfunction isNodeEEXIST(err: unknown): boolean {\n return !!err && typeof err === 'object' && (err as { code?: string }).code === 'EEXIST'\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const fs = await import('node:fs/promises')\n const handle = await fs.open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n","/**\n * Stripe subscription webhook dispatcher.\n *\n * Receives `WebhookEnvelope` rows from `WebhookRouter`'s `deliver()`\n * callback, decodes them into typed `StripeBillingEvent` values, and\n * applies the corresponding state transition to the consumer's\n * `SubscriptionStore`. Emits a typed event the consumer subscribes to.\n *\n * Layering:\n *\n * Stripe → HTTP → WebhookRouter (verify + idempotency dedup)\n * ↓ deliver(envelope)\n * StripeBillingDispatcher (this file)\n * ↓\n * ├─ SubscriptionStore.saveIfVersion(...)\n * └─ emit(typed event) → consumer's subscriber\n *\n * Critical guarantees:\n *\n * 1. Idempotency at two layers — the router de-dupes at the event id;\n * the dispatcher's `saveIfVersion` defends against the second\n * router instance (multi-region) racing the same event. The\n * a finished claim is distinguishable from concurrent work. Listener\n * failure releases the claim and reaches the HTTP layer as a failure.\n *\n * 2. Order-independence — Stripe doesn't guarantee delivery order.\n * We persist the newest applied `event.created` timestamp and reject\n * older subscription events. Stripe timestamps have one-second resolution,\n * so equal timestamps require an authenticated current-state read.\n *\n * 3. Explicit unknown handling — events we don't have a handler for\n * are not dropped silently; we emit them as\n * `stripe.event_unhandled` so the consumer can log + alert if\n * they expected coverage that we don't ship.\n *\n * 4. Idempotency of the dispatcher itself — calling `dispatch()` with\n * an event whose id equals `lastEventId` on the loaded record is a\n * no-op that emits `stripe.event_replay` instead of advancing state.\n *\n * Events supported (8 critical + 2 lifecycle):\n *\n * customer.subscription.created\n * customer.subscription.updated\n * customer.subscription.deleted\n * customer.subscription.trial_will_end\n * customer.subscription.paused\n * customer.subscription.resumed\n * invoice.paid\n * invoice.payment_failed\n */\n\nimport type { WebhookEnvelope } from '../webhooks/router.js'\nimport {\n FileSystemAtomicIdempotencyStore,\n InMemoryAtomicIdempotencyStore,\n resolveAtomicIdempotencyStore,\n type AtomicIdempotencyStore,\n type IdempotencyRuntime,\n} from '../idempotency.js'\nimport { BillingError } from './errors.js'\nimport {\n applyTransition,\n isValidTransition,\n makeSubscriptionRecord,\n type SubscriptionRecord,\n type SubscriptionState,\n type SubscriptionStore,\n} from './subscription-state.js'\n\n/* ---------------------------------------------------------------------- */\n/* Stripe payload type subset */\n/* ---------------------------------------------------------------------- */\n\n/** Subset of Stripe's `Subscription` object we read. Keep narrow — the\n * full object has 70+ fields; we only need the ones that map to our\n * `SubscriptionRecord`. New fields land here on demand. */\nexport interface StripeSubscriptionSnapshot {\n id: string\n status: string\n customer: string | { id?: string }\n current_period_end?: number | null\n cancel_at_period_end?: boolean | null\n trial_end?: number | null\n items?: {\n data?: Array<{ price?: { id?: string } }>\n }\n /** Stripe `Subscription.metadata` — agents put their `workspaceId`\n * here at checkout time so we can route subsequent webhooks back to\n * the right tenant without an extra DB lookup. */\n metadata?: Record<string, string>\n}\n\ninterface StripeInvoicePayload {\n id: string\n /** Legacy Stripe versions expose the subscription at the top level. */\n subscription?: string | null\n /** Stripe 2025-03-31.basil and newer move subscription identity here. */\n parent?: {\n type?: string\n subscription_details?: {\n subscription?: string | { id?: string } | null\n metadata?: Record<string, string>\n } | null\n } | null\n customer?: string\n status?: string\n /** Cents. */\n amount_paid?: number\n amount_due?: number\n /** Lined up to subscription metadata at invoice generation. */\n metadata?: Record<string, string>\n}\n\ninterface StripeSubscriptionIdentity {\n customerId: string\n subscriptionId: string\n}\n\ninterface StripeEvent {\n id: string\n type: string\n created?: number\n data: { object: unknown }\n}\n\n/* ---------------------------------------------------------------------- */\n/* dispatcher contract */\n/* ---------------------------------------------------------------------- */\n\n/** Strongly-typed events the consumer can subscribe to. Each carries\n * enough context to drive downstream side effects without a second\n * DB round-trip (audit log row, Slack ping, in-app notification). */\nexport type StripeBillingEvent =\n | {\n kind: 'subscription.created'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.trial_ignored'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.updated'\n eventId: string\n previousState: SubscriptionState\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.deleted'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.trial_will_end'\n eventId: string\n record: SubscriptionRecord\n trialEndsAt: number\n }\n | {\n kind: 'subscription.paused'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'subscription.resumed'\n eventId: string\n record: SubscriptionRecord\n }\n | {\n kind: 'invoice.paid'\n eventId: string\n record: SubscriptionRecord | null\n invoiceId: string\n amountPaid: number\n }\n | {\n kind: 'invoice.zero_dollar_ignored'\n eventId: string\n invoiceId: string\n amountPaid: number\n }\n | {\n kind: 'invoice.payment_failed'\n eventId: string\n record: SubscriptionRecord | null\n invoiceId: string\n amountDue: number\n }\n | {\n kind: 'event_unhandled'\n eventId: string\n type: string\n }\n | {\n kind: 'event_replay'\n eventId: string\n type: string\n }\n | {\n kind: 'event_dropped_out_of_order'\n eventId: string\n type: string\n reason: string\n }\n\n/** Listener — production consumers must durably enqueue by `eventId` before\n * resolving. A throw releases the claim and reaches the HTTP boundary. */\nexport type StripeBillingListener = (event: StripeBillingEvent) => void | Promise<void>\n\nexport interface StripeEventIdempotencyStore extends AtomicIdempotencyStore {}\n\n/** Durable store for workers that share the same filesystem directory. */\nexport class FileSystemStripeEventIdempotencyStore extends FileSystemAtomicIdempotencyStore implements StripeEventIdempotencyStore {}\n\nexport interface StripeBillingDispatcherOptions {\n store: SubscriptionStore\n /** Maps a Stripe `customer.id` → the workspaceId the product uses to\n * key its `SubscriptionStore`. We default to reading\n * `subscription.metadata.workspaceId` (agents inject it at checkout\n * time); supply this override for products that key by customer id\n * directly or look up a join table. */\n resolveWorkspaceId?(input: {\n customerId: string\n subscriptionMetadata?: Record<string, string>\n invoiceMetadata?: Record<string, string>\n }): Promise<string | null> | string | null\n /** Retrieve the current subscription through an authenticated Stripe API\n * client. Equal `event.created` timestamps fail until this callback returns\n * an authoritative snapshot. */\n retrieveSubscription?(subscriptionId: string): Promise<StripeSubscriptionSnapshot>\n /** Single typed listener (most consumers want one — they route inside\n * it themselves). Compose multiple via `combineListeners(a, b)`. */\n listener?: StripeBillingListener\n /** Observe unexpected dispatcher errors before they are rethrown. */\n onError?(err: unknown, context: { eventId: string; type: string }): void\n /** Override `Date.now()` for tests. */\n now?(): number\n /** Max retries on `saveIfVersion` contention. Default 3. */\n maxCasRetries?: number\n /** Separate atomic event store for direct dispatcher calls. */\n idempotency?: StripeEventIdempotencyStore\n /** Runtime controls the safe default. Production fails closed without a\n * shared store; test/development use an in-memory store when omitted. */\n runtime?: IdempotencyRuntime\n idempotencyTtlMs?: number\n}\n\n/* ---------------------------------------------------------------------- */\n/* dispatcher */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Process a webhook envelope. Safe to call concurrently with itself —\n * the in-store CAS serializes per-workspace updates.\n */\nexport class StripeBillingDispatcher {\n private readonly store: SubscriptionStore\n private readonly resolveWorkspaceId: NonNullable<StripeBillingDispatcherOptions['resolveWorkspaceId']>\n private readonly retrieveSubscription?: StripeBillingDispatcherOptions['retrieveSubscription']\n private readonly listener?: StripeBillingListener\n private readonly onError: NonNullable<StripeBillingDispatcherOptions['onError']>\n private readonly now: () => number\n private readonly maxCasRetries: number\n private readonly idempotency: StripeEventIdempotencyStore\n private readonly idempotencyTtlMs: number\n\n constructor(opts: StripeBillingDispatcherOptions) {\n this.store = opts.store\n this.resolveWorkspaceId = opts.resolveWorkspaceId ?? defaultResolveWorkspaceId\n this.retrieveSubscription = opts.retrieveSubscription\n this.listener = opts.listener\n this.onError = opts.onError ?? defaultOnError\n this.now = opts.now ?? Date.now\n this.maxCasRetries = opts.maxCasRetries ?? 3\n this.idempotency = resolveAtomicIdempotencyStore({\n component: 'StripeBillingDispatcher',\n store: opts.idempotency,\n runtime: opts.runtime,\n })\n if (isProductionRuntime(opts.runtime) && !opts.listener) {\n throw new Error('StripeBillingDispatcher: production requires a durable billing listener')\n }\n this.idempotencyTtlMs = opts.idempotencyTtlMs ?? 7 * 24 * 60 * 60 * 1000\n }\n\n /** Drive one envelope through the pipeline. Idempotent w.r.t. the\n * event id (replays are a no-op + emit `event_replay`). */\n async dispatch(envelope: WebhookEnvelope): Promise<void> {\n const evt = envelope.payload as StripeEvent | undefined\n if (!evt || typeof evt !== 'object' || typeof evt.id !== 'string' || typeof evt.type !== 'string') {\n const error = new Error('Stripe envelope missing id or type')\n this.onError(error, {\n eventId: 'unknown',\n type: 'unknown',\n })\n throw error\n }\n const claimStatus = await this.idempotency.claimStatus(evt.id, this.idempotencyTtlMs)\n if (claimStatus === 'completed') {\n await this.emit({ kind: 'event_replay', eventId: evt.id, type: evt.type })\n return\n }\n if (claimStatus === 'in_progress') {\n const error = new BillingError({\n code: 'webhook_event_unknown',\n message: `Stripe event ${evt.id} is already in progress`,\n context: { eventId: evt.id },\n })\n throw error\n }\n try {\n await this.handle(evt)\n await this.idempotency.complete(evt.id)\n } catch (err) {\n try {\n await this.idempotency.release(evt.id)\n } catch (releaseError) {\n this.onError(releaseError, { eventId: evt.id, type: evt.type })\n }\n this.onError(err, { eventId: evt.id, type: evt.type })\n throw err\n }\n }\n\n private async handle(evt: StripeEvent): Promise<void> {\n switch (evt.type) {\n case 'customer.subscription.created':\n return this.handleSubCreated(evt)\n case 'customer.subscription.updated':\n return this.handleSubUpdated(evt)\n case 'customer.subscription.deleted':\n return this.handleSubDeleted(evt)\n case 'customer.subscription.trial_will_end':\n return this.handleTrialWillEnd(evt)\n case 'customer.subscription.paused':\n return this.handleSubLifecycle(evt, 'paused')\n case 'customer.subscription.resumed':\n return this.handleSubLifecycle(evt, 'active')\n case 'invoice.paid':\n return this.handleInvoicePaid(evt)\n case 'invoice.payment_failed':\n return this.handleInvoicePaymentFailed(evt)\n default:\n await this.emit({ kind: 'event_unhandled', eventId: evt.id, type: evt.type })\n return\n }\n }\n\n /* --------------------- subscription event handlers ------------------- */\n\n private async handleSubCreated(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n\n const existing = await this.store.load(workspaceId)\n // A `created` event names a subscription the record does not hold. That is\n // a foreign event unless the same customer is starting a new subscription\n // after the recorded one reached a terminal state — the resubscribe path.\n // Rebinding only from a terminal state keeps a live subscription bound.\n const rebinds =\n existing !== null &&\n !matchesSubscription(existing, identity) &&\n existing.customerId === identity.customerId &&\n isTerminalSubscriptionState(existing.state)\n if (existing && !matchesSubscription(existing, identity) && !rebinds) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(existing, evt)\n if (existing && existing.lastEventId === evt.id) {\n return this.emitPersisted(\n existing.state === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record: existing }\n : { kind: 'subscription.created', eventId: evt.id, record: existing },\n workspaceId,\n )\n }\n if (existing && isOlderEvent(existing, eventCreatedAt)) {\n return this.emitOlderEvent(evt, existing)\n }\n if (existing && isEqualTimestampEvent(existing, eventCreatedAt)) {\n return this.reconcileEqualTimestamp(evt, workspaceId, identity)\n }\n\n // Create-only: if a record already exists with a non-incomplete state\n // and this is a stale created event, treat as out-of-order.\n if (existing && !canApplyFreshCreate(existing.state)) {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: `existing state ${existing.state} cannot accept a fresh 'created'`,\n })\n }\n\n const nextState = parseState(sub.status, evt.id)\n const freshRecord = makeSubscriptionRecord({\n workspaceId,\n customerId: identity.customerId,\n subscriptionId: identity.subscriptionId,\n state: nextState,\n priceId: extractPriceId(sub),\n currentPeriodEnd: sub.current_period_end ?? null,\n trialEnd: sub.trial_end ?? null,\n cancelAtPeriodEnd: sub.cancel_at_period_end ?? false,\n eventId: evt.id,\n eventCreatedAt,\n pendingEventId: evt.id,\n now: this.now,\n })\n // A rebind writes a fresh record rather than a transition: `applyTransition`\n // spreads the base, which would carry the terminal subscription's id into\n // the new one. The version still advances, so a concurrent writer's\n // compare-and-set fails as it does on every other path.\n const record = !existing\n ? freshRecord\n : rebinds\n ? { ...freshRecord, version: existing.version + 1 }\n : applyTransition(\n existing,\n {\n state: nextState,\n priceId: extractPriceId(sub),\n currentPeriodEnd: sub.current_period_end ?? null,\n trialEnd: sub.trial_end ?? null,\n cancelAtPeriodEnd: sub.cancel_at_period_end ?? false,\n },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n const expectedVersion = existing?.version ?? 0\n const written = await this.cas(record, expectedVersion)\n if (!written) return this.emitUnbound(evt, 'subscription create lost a concurrent compare-and-set')\n await this.emitPersisted(\n record.state === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record }\n : { kind: 'subscription.created', eventId: evt.id, record },\n workspaceId,\n )\n }\n\n private async handleSubUpdated(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const nextState = parseState(sub.status, evt.id)\n\n await this.advance(evt, workspaceId, (current) => {\n if (current.lastEventId === evt.id) {\n return {\n emitOnly: nextState === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record: current }\n : {\n kind: 'subscription.updated',\n eventId: evt.id,\n previousState: current.lastEventPreviousState ?? current.state,\n record: current,\n },\n }\n }\n if (!isValidTransition(current.state, nextState)) return 'out_of_order'\n const next = applyTransition(\n current,\n {\n state: nextState,\n priceId: extractPriceId(sub) ?? current.priceId,\n currentPeriodEnd: sub.current_period_end ?? current.currentPeriodEnd,\n trialEnd: sub.trial_end ?? current.trialEnd,\n cancelAtPeriodEnd: sub.cancel_at_period_end ?? current.cancelAtPeriodEnd,\n },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n return {\n next,\n emit:\n nextState === 'trialing'\n ? { kind: 'subscription.trial_ignored', eventId: evt.id, record: next }\n : { kind: 'subscription.updated', eventId: evt.id, previousState: current.state, record: next },\n }\n }, identity)\n }\n\n private async handleSubDeleted(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n\n await this.advance(evt, workspaceId, (current) => {\n if (current.lastEventId === evt.id) {\n return { emitOnly: { kind: 'subscription.deleted', eventId: evt.id, record: current } }\n }\n if (current.state === 'canceled') return 'replay' // terminal — fine to no-op\n const next = applyTransition(\n current,\n { state: 'canceled', priceId: null, currentPeriodEnd: sub.current_period_end ?? current.currentPeriodEnd },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n return {\n next,\n emit: { kind: 'subscription.deleted', eventId: evt.id, record: next },\n }\n }, identity)\n }\n\n private async handleTrialWillEnd(evt: StripeEvent): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const current = await this.store.load(workspaceId)\n if (!current) throw retryableStripeEvent(evt, 'subscription state is not available yet')\n if (!matchesSubscription(current, identity)) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(current, evt)\n if (current.lastEventId === evt.id) {\n return this.emitPersisted({\n kind: 'subscription.trial_will_end',\n eventId: evt.id,\n record: current,\n trialEndsAt: current.trialEnd ?? 0,\n }, workspaceId)\n }\n if (isOlderEvent(current, eventCreatedAt)) return this.emitOlderEvent(evt, current)\n if (isEqualTimestampEvent(current, eventCreatedAt)) {\n return this.reconcileEqualTimestamp(evt, workspaceId, identity)\n }\n // No state transition — trial_will_end is informational. Update\n // lastEventId so a replay is detected.\n const next: SubscriptionRecord = {\n ...current,\n lastEventId: evt.id,\n lastEventCreatedAt: eventCreatedAt,\n lastEventPreviousState: current.state,\n pendingEventId: evt.id,\n trialEnd: sub.trial_end ?? current.trialEnd,\n version: current.version + 1,\n updatedAt: this.now(),\n }\n const written = await this.cas(next, current.version)\n if (!written) return this.emitUnbound(evt, 'trial update lost a concurrent compare-and-set')\n await this.emitPersisted({\n kind: 'subscription.trial_will_end',\n eventId: evt.id,\n record: next,\n trialEndsAt: sub.trial_end ?? next.trialEnd ?? 0,\n }, workspaceId)\n }\n\n private async handleSubLifecycle(evt: StripeEvent, target: SubscriptionState): Promise<void> {\n const eventCreatedAt = requireEventCreatedAt(evt)\n const sub = evt.data.object as StripeSubscriptionSnapshot\n const identity = subscriptionIdentity(sub)\n if (!identity) return this.emitUnbound(evt, 'subscription event is missing customer or subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: identity.customerId,\n subscriptionMetadata: sub.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n\n await this.advance(evt, workspaceId, (current) => {\n if (current.lastEventId === evt.id) {\n const kind = target === 'paused' ? 'subscription.paused' : 'subscription.resumed'\n return { emitOnly: { kind, eventId: evt.id, record: current } }\n }\n if (!isValidTransition(current.state, target)) return 'out_of_order'\n const next = applyTransition(\n current,\n { state: target },\n { eventId: evt.id, eventCreatedAt, pendingEventId: evt.id, now: this.now },\n )\n const kind = target === 'paused' ? 'subscription.paused' : 'subscription.resumed'\n return { next, emit: { kind, eventId: evt.id, record: next } }\n }, identity)\n }\n\n /* ----------------------- invoice event handlers ---------------------- */\n\n private async handleInvoicePaid(evt: StripeEvent): Promise<void> {\n const inv = evt.data.object as StripeInvoicePayload\n if (!invoiceIdentity(inv)) return this.emitUnbound(evt, 'paid invoice is missing customer or invoice id')\n const subscription = invoiceSubscription(inv)\n if (!subscription) return this.emitUnbound(evt, 'paid invoice is missing a subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: inv.customer ?? '',\n invoiceMetadata: subscription.metadata ?? inv.metadata,\n })\n const amountPaid = typeof inv.amount_paid === 'number' && Number.isFinite(inv.amount_paid) ? inv.amount_paid : 0\n if (amountPaid <= 0) {\n await this.emit({\n kind: 'invoice.zero_dollar_ignored',\n eventId: evt.id,\n invoiceId: inv.id,\n amountPaid,\n })\n return\n }\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const record = await this.store.load(workspaceId)\n if (!record) throw retryableStripeEvent(evt, 'paid invoice subscription state is not available yet')\n if (record.customerId !== inv.customer || record.subscriptionId !== subscription.subscriptionId) {\n return this.emitUnbound(evt, 'paid invoice identity does not match the workspace record')\n }\n await this.emit({\n kind: 'invoice.paid',\n eventId: evt.id,\n record,\n invoiceId: inv.id,\n amountPaid,\n })\n }\n\n private async handleInvoicePaymentFailed(evt: StripeEvent): Promise<void> {\n const inv = evt.data.object as StripeInvoicePayload\n if (!invoiceIdentity(inv)) return this.emitUnbound(evt, 'failed invoice is missing customer or invoice id')\n const subscription = invoiceSubscription(inv)\n if (!subscription) return this.emitUnbound(evt, 'failed invoice is missing a subscription id')\n const workspaceId = await this.resolveWorkspaceId({\n customerId: inv.customer ?? '',\n invoiceMetadata: subscription.metadata ?? inv.metadata,\n })\n if (!workspaceId) return this.emitNoWorkspace(evt)\n const record = await this.store.load(workspaceId)\n if (!record) throw retryableStripeEvent(evt, 'failed invoice subscription state is not available yet')\n if (record.customerId !== inv.customer || record.subscriptionId !== subscription.subscriptionId) {\n return this.emitUnbound(evt, 'failed invoice identity does not match the workspace record')\n }\n await this.emit({\n kind: 'invoice.payment_failed',\n eventId: evt.id,\n record,\n invoiceId: inv.id,\n amountDue: inv.amount_due ?? 0,\n })\n }\n\n /* ------------------------------- core -------------------------------- */\n\n /** Load, apply a transformation, CAS-write. The transformation may\n * return 'replay' / 'out_of_order' for the dispatcher to emit\n * diagnostic events instead. Retries on contention up to\n * `maxCasRetries`; if exhausted, throws so the event claim is released\n * and the provider can retry. */\n private async advance(\n evt: StripeEvent,\n workspaceId: string,\n transform: (current: SubscriptionRecord) =>\n | { next: SubscriptionRecord; emit: StripeBillingEvent }\n | { emitOnly: StripeBillingEvent }\n | 'replay'\n | 'out_of_order',\n identity: StripeSubscriptionIdentity,\n ): Promise<void> {\n for (let attempt = 0; attempt < this.maxCasRetries; attempt++) {\n const current = await this.store.load(workspaceId)\n if (!current) throw retryableStripeEvent(evt, 'subscription state is not available yet')\n if (identity && !matchesSubscription(current, identity)) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(current, evt)\n const eventCreatedAt = requireEventCreatedAt(evt)\n if (current.lastEventId !== evt.id && isOlderEvent(current, eventCreatedAt)) {\n return this.emitOlderEvent(evt, current)\n }\n if (current.lastEventId !== evt.id && isEqualTimestampEvent(current, eventCreatedAt)) {\n return this.reconcileEqualTimestamp(evt, workspaceId, identity)\n }\n const result = transform(current)\n if (result === 'replay') {\n return this.emit({ kind: 'event_replay', eventId: evt.id, type: evt.type })\n }\n if (result === 'out_of_order') {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: `current=${current.state}`,\n })\n }\n if ('emitOnly' in result) return this.emitPersisted(result.emitOnly, workspaceId)\n const written = await this.store.saveIfVersion(result.next, current.version)\n if (written) return this.emitPersisted(result.emit, workspaceId)\n }\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `CAS contention exhausted after ${this.maxCasRetries} attempts`,\n context: { workspaceId, eventId: evt.id },\n })\n }\n\n private async cas(record: SubscriptionRecord, expectedVersion: number): Promise<boolean> {\n // The record was built from one loaded version. Retrying it against a\n // newer expected version would overwrite another event with stale state.\n return this.store.saveIfVersion(record, expectedVersion)\n }\n\n private async emit(event: StripeBillingEvent): Promise<void> {\n if (!this.listener) return\n await this.listener(event)\n }\n\n private async emitPersisted(event: StripeBillingEvent, workspaceId: string): Promise<void> {\n await this.emit(event)\n await this.clearPendingSubscriptionEvent(workspaceId, event.eventId)\n }\n\n private assertNoPendingSubscriptionEvent(\n record: SubscriptionRecord | null,\n evt: StripeEvent,\n ): void {\n if (!record?.pendingEventId || record.pendingEventId === evt.id) return\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Subscription event ${record.pendingEventId} still needs durable delivery`,\n context: { workspaceId: record.workspaceId, eventId: evt.id },\n })\n }\n\n private async clearPendingSubscriptionEvent(workspaceId: string, eventId: string): Promise<void> {\n for (let attempt = 0; attempt < this.maxCasRetries; attempt++) {\n const current = await this.store.load(workspaceId)\n if (!current) throw new Error(`Subscription record ${workspaceId} disappeared after delivery`)\n if (current.pendingEventId === null || current.pendingEventId === undefined) return\n if (current.pendingEventId !== eventId) {\n throw new Error(`Subscription pending event changed from ${eventId} to ${current.pendingEventId}`)\n }\n const cleared: SubscriptionRecord = {\n ...current,\n pendingEventId: null,\n version: current.version + 1,\n updatedAt: this.now(),\n }\n if (await this.store.saveIfVersion(cleared, current.version)) return\n }\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Pending event clear exhausted after ${this.maxCasRetries} attempts`,\n context: { workspaceId, eventId },\n })\n }\n\n private async reconcileEqualTimestamp(\n evt: StripeEvent,\n workspaceId: string,\n expectedIdentity: StripeSubscriptionIdentity,\n ): Promise<void> {\n if (!this.retrieveSubscription) {\n throw retryableStripeEvent(evt, 'equal event.created timestamps require Stripe reconciliation')\n }\n const snapshot = await this.retrieveSubscription(expectedIdentity.subscriptionId)\n const canonicalIdentity = subscriptionIdentity(snapshot)\n if (\n !canonicalIdentity\n || canonicalIdentity.customerId !== expectedIdentity.customerId\n || canonicalIdentity.subscriptionId !== expectedIdentity.subscriptionId\n ) {\n throw retryableStripeEvent(evt, 'Stripe reconciliation returned a mismatched subscription')\n }\n const canonicalState = parseState(snapshot.status, evt.id)\n const eventCreatedAt = requireEventCreatedAt(evt)\n\n for (let attempt = 0; attempt < this.maxCasRetries; attempt++) {\n const current = await this.store.load(workspaceId)\n if (!current) throw retryableStripeEvent(evt, 'subscription state is not available yet')\n if (!matchesSubscription(current, expectedIdentity)) {\n return this.emitUnbound(evt, 'subscription identity does not match the workspace record')\n }\n this.assertNoPendingSubscriptionEvent(current, evt)\n if (current.lastEventId === evt.id) {\n return this.emitPersisted(canonicalBillingEvent(evt, current, current), workspaceId)\n }\n if (isOlderEvent(current, eventCreatedAt)) return this.emitOlderEvent(evt, current)\n if (!isEqualTimestampEvent(current, eventCreatedAt)) {\n throw retryableStripeEvent(evt, 'subscription state changed during Stripe reconciliation')\n }\n const next: SubscriptionRecord = {\n ...current,\n state: canonicalState,\n priceId: canonicalState === 'canceled' ? null : extractPriceId(snapshot),\n currentPeriodEnd: snapshot.current_period_end ?? null,\n trialEnd: snapshot.trial_end ?? null,\n cancelAtPeriodEnd: snapshot.cancel_at_period_end ?? false,\n version: current.version + 1,\n lastEventId: evt.id,\n lastEventCreatedAt: eventCreatedAt,\n lastEventPreviousState: current.state,\n pendingEventId: evt.id,\n updatedAt: this.now(),\n }\n if (await this.store.saveIfVersion(next, current.version)) {\n return this.emitPersisted(canonicalBillingEvent(evt, current, next), workspaceId)\n }\n }\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Stripe reconciliation contention exhausted after ${this.maxCasRetries} attempts`,\n context: { workspaceId, eventId: evt.id },\n })\n }\n\n private emitNoWorkspace(evt: StripeEvent): Promise<void> {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: 'workspaceId could not be resolved from event payload',\n })\n }\n\n private emitUnbound(evt: StripeEvent, reason: string): Promise<void> {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason,\n })\n }\n\n private emitOlderEvent(evt: StripeEvent, current: SubscriptionRecord): Promise<void> {\n return this.emit({\n kind: 'event_dropped_out_of_order',\n eventId: evt.id,\n type: evt.type,\n reason: `event.created=${evt.created} is older than stored=${current.lastEventCreatedAt}`,\n })\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* helpers */\n/* ---------------------------------------------------------------------- */\n\n/** Compose multiple listeners — fan out + collect errors. */\nexport function combineListeners(...listeners: StripeBillingListener[]): StripeBillingListener {\n return async (event) => {\n for (const l of listeners) await l(event)\n }\n}\n\nfunction defaultResolveWorkspaceId(input: { subscriptionMetadata?: Record<string, string>; invoiceMetadata?: Record<string, string> }): string | null {\n const sub = input.subscriptionMetadata?.workspaceId\n if (sub) return sub\n const inv = input.invoiceMetadata?.workspaceId\n return inv ?? null\n}\n\nfunction subscriptionIdentity(value: unknown): StripeSubscriptionIdentity | null {\n if (!value || typeof value !== 'object') return null\n const candidate = value as { customer?: unknown; id?: unknown }\n const customerId = readExpandableId(candidate.customer)\n if (!customerId) return null\n if (typeof candidate.id !== 'string' || !candidate.id.trim()) return null\n return { customerId, subscriptionId: candidate.id }\n}\n\nfunction invoiceIdentity(value: unknown): { customer: string; id: string } | null {\n if (!value || typeof value !== 'object') return null\n const candidate = value as { customer?: unknown; id?: unknown }\n if (typeof candidate.customer !== 'string' || !candidate.customer.trim()) return null\n if (typeof candidate.id !== 'string' || !candidate.id.trim()) return null\n return { customer: candidate.customer, id: candidate.id }\n}\n\nfunction invoiceSubscription(\n invoice: StripeInvoicePayload,\n): { subscriptionId: string; metadata?: Record<string, string> } | null {\n if (invoice.parent !== undefined && invoice.parent !== null) {\n if (invoice.parent.type !== 'subscription_details') return null\n const details = invoice.parent.subscription_details\n const subscriptionId = readExpandableId(details?.subscription)\n if (!subscriptionId) return null\n return {\n subscriptionId,\n ...(details?.metadata ? { metadata: details.metadata } : {}),\n }\n }\n const subscriptionId = readExpandableId(invoice.subscription)\n return subscriptionId ? { subscriptionId } : null\n}\n\nfunction readExpandableId(value: unknown): string | null {\n if (typeof value === 'string' && value.trim()) return value\n if (!value || typeof value !== 'object') return null\n const id = (value as { id?: unknown }).id\n return typeof id === 'string' && id.trim() ? id : null\n}\n\nfunction matchesSubscription(record: SubscriptionRecord, identity: StripeSubscriptionIdentity): boolean {\n return record.customerId === identity.customerId && record.subscriptionId === identity.subscriptionId\n}\n\nfunction requireEventCreatedAt(evt: StripeEvent): number {\n if (!Number.isSafeInteger(evt.created) || (evt.created as number) < 0) {\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: 'Stripe subscription event is missing a valid event.created timestamp',\n context: { eventId: evt.id },\n })\n }\n return evt.created as number\n}\n\nfunction isOlderEvent(record: SubscriptionRecord, eventCreatedAt: number): boolean {\n return record.lastEventCreatedAt !== null && eventCreatedAt < record.lastEventCreatedAt\n}\n\nfunction isEqualTimestampEvent(record: SubscriptionRecord, eventCreatedAt: number): boolean {\n return record.lastEventCreatedAt !== null && eventCreatedAt === record.lastEventCreatedAt\n}\n\nfunction retryableStripeEvent(evt: StripeEvent, message: string): BillingError {\n return new BillingError({\n code: 'webhook_event_unknown',\n message,\n context: { eventId: evt.id },\n })\n}\n\nfunction canonicalBillingEvent(\n evt: StripeEvent,\n previous: SubscriptionRecord,\n current: SubscriptionRecord,\n): StripeBillingEvent {\n if (current.state === 'canceled') {\n return { kind: 'subscription.deleted', eventId: evt.id, record: current }\n }\n if (current.state === 'trialing') {\n return { kind: 'subscription.trial_ignored', eventId: evt.id, record: current }\n }\n return {\n kind: 'subscription.updated',\n eventId: evt.id,\n previousState: previous.state,\n record: current,\n }\n}\n\nfunction isProductionRuntime(runtime: IdempotencyRuntime | undefined): boolean {\n if (runtime) return runtime === 'production'\n if (typeof process !== 'undefined' && process.env.VITEST) return false\n const nodeEnv = typeof process !== 'undefined' ? process.env.NODE_ENV : undefined\n return nodeEnv !== 'test' && nodeEnv !== 'development'\n}\n\nfunction defaultOnError(err: unknown, context: { eventId: string; type: string }): void {\n // eslint-disable-next-line no-console\n console.error('[StripeBillingDispatcher]', context, err)\n}\n\nfunction parseState(status: string, eventId: string): SubscriptionState {\n switch (status) {\n case 'incomplete':\n case 'incomplete_expired':\n case 'trialing':\n case 'active':\n case 'past_due':\n case 'canceled':\n case 'unpaid':\n case 'paused':\n return status\n default:\n throw new BillingError({\n code: 'webhook_event_unknown',\n message: `Unknown Stripe subscription status '${status}'`,\n context: { eventId },\n })\n }\n}\n\n/**\n * States a subscription cannot leave, so the customer can only return through\n * a new subscription. A `created` event for a different subscription id is a\n * resubscribe from one of these, and a foreign event from any other state.\n */\nfunction isTerminalSubscriptionState(state: SubscriptionState): boolean {\n return state === 'canceled' || state === 'incomplete_expired'\n}\n\nfunction canApplyFreshCreate(state: SubscriptionState): boolean {\n // A 'created' event on a record that already advanced past incomplete means\n // the lifecycle was processed and a retried-late 'created' should be dropped.\n // A terminal state is the exception: it accepts the customer's next\n // subscription, which is the only way back from it.\n return state === 'incomplete' || isTerminalSubscriptionState(state)\n}\n\nfunction extractPriceId(sub: StripeSubscriptionSnapshot): string | null {\n return sub.items?.data?.[0]?.price?.id ?? null\n}\n","/**\n * Pricing plan scaffold + checkout URL generator.\n *\n * Per task constraint, this module does NOT bake in pricing. The\n * consumer (product agent) supplies the `PricingPlan[]` table at boot.\n * We standardize the SHAPE (id, name, monthly/yearly USD, feature\n * bullets, stripe price ids), the LOOKUP (`findPlan`, `requirePlan`),\n * and the CHECKOUT URL flow (`createCheckoutUrl`).\n *\n * The shape is intentionally USD-only with month/year recurrence.\n * Stripe supports more — multi-currency, week/quarter, usage-based,\n * tiered — but adding columns we don't use creates pressure to fill\n * them with defaults that mislead. When a product needs more, extend\n * the shape; do not work around it in the consumer.\n *\n * `createCheckoutUrl` writes the workspaceId into\n * `subscription_data.metadata.workspaceId` so the dispatcher's default\n * `resolveWorkspaceId` finds it on the first `customer.subscription.created`\n * webhook. THIS IS LOAD-BEARING: drop it and you have to write a\n * customer → workspace join table by hand.\n */\n\nimport type { StripeClient } from './tenant-config.js'\nimport { assertNoProductFreeTrial } from '../billing-access-policy.js'\n\nexport interface PricingPlanFeature {\n /** Short label rendered in pricing table rows. */\n label: string\n /** Optional richer description for the marketing page. */\n description?: string\n /** Whether the feature is included in this plan. Many products show\n * the same feature row across plans with a check/cross. */\n included: boolean\n}\n\nexport interface PricingPlan {\n /** Stable internal id — used by middleware to gate features, NOT the\n * Stripe price id. */\n id: string\n /** Display name in the pricing table. */\n name: string\n /** Monthly price in whole USD. `null` for plans that are yearly-only\n * or contact-sales tiers. */\n monthlyUsd: number | null\n /** Yearly price in whole USD. `null` for plans that don't offer\n * annual billing. */\n yearlyUsd: number | null\n /** Marketing feature bullets. */\n features: PricingPlanFeature[]\n /** Stripe `price_…` ids per cadence. At least one must be set if the\n * matching `*Usd` field is non-null. */\n stripePriceIds: {\n monthly?: string\n yearly?: string\n }\n /**\n * Legacy compatibility field. Positive values are rejected because\n * product-funded free trials are disabled.\n */\n trialDays?: number\n /** Optional metadata threaded into Stripe Subscription metadata — the\n * product can use these for analytics or grant-feature lookup. */\n metadata?: Record<string, string>\n}\n\nexport type BillingCadence = 'monthly' | 'yearly'\n\n/** Find a plan by id. Returns null when not found. */\nexport function findPlan(plans: readonly PricingPlan[], id: string): PricingPlan | null {\n return plans.find((p) => p.id === id) ?? null\n}\n\n/** Look up a plan or throw — for code paths where missing is a bug\n * (e.g., resolving a stored subscription's plan id back to a name). */\nexport function requirePlan(plans: readonly PricingPlan[], id: string): PricingPlan {\n const plan = findPlan(plans, id)\n if (!plan) throw new Error(`pricing: unknown plan id '${id}'`)\n return plan\n}\n\nexport interface CreateCheckoutUrlInput {\n /** Tenant key — written to subscription metadata for webhook routing. */\n workspaceId: string\n /** Plan from the consumer's pricing table. */\n plan: PricingPlan\n /** Which Stripe price id to charge against. */\n billing: BillingCadence\n /** Optional existing Stripe customer id — pre-fills the checkout. */\n customerId?: string\n /** Customer email — used by Stripe to pre-fill or to create a new\n * customer if `customerId` is absent. */\n customerEmail?: string\n /** Success/cancel URLs. Overrides the per-tenant defaults from\n * `TenantStripeConfig.successUrl`/`cancelUrl`. */\n successUrl?: string\n cancelUrl?: string\n /** Idempotency key — pass a deterministic key (e.g.,\n * `${workspaceId}:${plan.id}:${billing}`) so the same user clicking\n * twice gets the same checkout session. */\n idempotencyKey: string\n /** Legacy compatibility field. Positive values are rejected. */\n trialDays?: number\n /** Optional extra metadata mixed into Stripe metadata. */\n metadata?: Record<string, string>\n}\n\nexport interface CheckoutUrl {\n sessionId: string\n url: string\n}\n\n/**\n * Create a Stripe checkout session and return its hosted URL. Uses the\n * per-tenant `StripeClient` from `getStripeClient(productId)`.\n *\n * The workspaceId is written into TWO metadata maps:\n * - `metadata` (on the session itself, surfaces on `checkout.session.*`)\n * - `subscription_data[metadata]` (carries through to the Subscription\n * row Stripe creates, which is what `customer.subscription.*`\n * webhooks carry)\n *\n * Without the second, the dispatcher can't route the first\n * `subscription.created` event to a workspace. We've shipped that bug\n * before — written here once to make it impossible to forget.\n */\nexport async function createCheckoutUrl(\n client: StripeClient,\n input: CreateCheckoutUrlInput,\n): Promise<CheckoutUrl> {\n if (!input.workspaceId.trim()) throw new Error('pricing: workspaceId is required')\n if (!input.plan.id.trim() || !input.plan.name.trim()) throw new Error('pricing: plan id and name are required')\n if (!input.idempotencyKey.trim()) throw new Error('pricing: idempotencyKey is required')\n const priceId = input.plan.stripePriceIds[input.billing]\n if (!priceId) {\n throw new Error(`pricing: plan '${input.plan.id}' has no Stripe price for cadence '${input.billing}'`)\n }\n if (!/^price_[A-Za-z0-9_]+$/.test(priceId)) {\n throw new Error(`pricing: invalid Stripe price id '${priceId}'`)\n }\n if (!client.config.approvedPriceIds?.includes(priceId)) {\n throw new Error(`pricing: Stripe price '${priceId}' is not approved for product '${client.productId}'`)\n }\n const planUsd = input.billing === 'monthly' ? input.plan.monthlyUsd : input.plan.yearlyUsd\n if (typeof planUsd !== 'number' || !Number.isFinite(planUsd) || planUsd <= 0) {\n throw new Error(`pricing: ${input.billing} price must be greater than zero`)\n }\n const successUrl = input.successUrl ?? client.config.successUrl\n const cancelUrl = input.cancelUrl ?? client.config.cancelUrl\n if (!successUrl || !cancelUrl) {\n throw new Error('pricing: successUrl and cancelUrl required (per-call or in TenantStripeConfig)')\n }\n\n const trialDays = input.trialDays ?? input.plan.trialDays\n assertNoProductFreeTrial(trialDays)\n const body: Record<string, string | number | boolean | undefined> = {\n mode: 'subscription',\n success_url: successUrl,\n cancel_url: cancelUrl,\n 'line_items[0][price]': priceId,\n 'line_items[0][quantity]': 1,\n 'metadata[workspaceId]': input.workspaceId,\n 'metadata[planId]': input.plan.id,\n 'subscription_data[metadata][workspaceId]': input.workspaceId,\n 'subscription_data[metadata][planId]': input.plan.id,\n }\n if (input.customerId) body.customer = input.customerId\n if (input.customerEmail && !input.customerId) body.customer_email = input.customerEmail\n // Mix in plan-defined metadata + caller-supplied metadata.\n const extra = { ...(input.plan.metadata ?? {}), ...(input.metadata ?? {}) }\n for (const [k, v] of Object.entries(extra)) {\n if (k === 'workspaceId' || k === 'planId') {\n throw new Error(`pricing: metadata key '${k}' is reserved`)\n }\n body[`metadata[${k}]`] = v\n body[`subscription_data[metadata][${k}]`] = v\n }\n\n const created = await client.mutate<{ id: string; url: string }>(\n 'POST',\n '/checkout/sessions',\n body,\n input.idempotencyKey,\n )\n if (!created.url) {\n throw new Error('pricing: Stripe checkout response missing url')\n }\n return { sessionId: created.id, url: created.url }\n}\n\n/**\n * Create a Stripe customer-billing-portal session and return its URL.\n * The product calls this when a user clicks \"manage billing\" — the\n * portal handles cancel / change plan / update card without us\n * implementing those flows.\n */\nexport async function createBillingPortalUrl(\n client: StripeClient,\n input: { customerId: string; returnUrl: string; idempotencyKey: string },\n): Promise<{ sessionId: string; url: string }> {\n const created = await client.mutate<{ id: string; url: string }>(\n 'POST',\n '/billing_portal/sessions',\n {\n customer: input.customerId,\n return_url: input.returnUrl,\n },\n input.idempotencyKey,\n )\n return { sessionId: created.id, url: created.url }\n}\n","/**\n * Per-tenant Stripe configuration routing.\n *\n * Five product agents (legal, tax, gtm, creative, agent-builder) each\n * own a SEPARATE Stripe account. Reasons we pay the multi-account tax\n * rather than billing everyone through a single Tangle Stripe account:\n *\n * 1. Each product is a different LLC/legal entity for tax + dispute\n * handling. Customer chargebacks land on the product's account.\n * 2. Stripe Tax + Atlas are per-account; we can't share a single\n * Tax-collection setup across five SaaS products.\n * 3. Each product has its own pricing experiments; sharing one account\n * would force a shared products/prices namespace and surface\n * leak risk in the Stripe dashboard.\n *\n * The routing table maps `productId` (a Tangle-internal stable\n * identifier) to:\n * - Stripe Secret Key (`sk_live_…` or `rk_live_…`)\n * - Webhook signing secret (`whsec_…`) — used by the WebhookRouter's\n * `resolveSecret` callback.\n * - Optional success/cancel URL defaults the product wants used\n * unless the caller overrides per-checkout.\n *\n * Env-var convention is `STRIPE_SK_<PRODUCT_UPPER>` and\n * `STRIPE_WHSEC_<PRODUCT_UPPER>` — the resolver below honors that by\n * default. Consumers that store keys in a vault (Doppler, AWS Secrets\n * Manager) inject their own `TenantConfigResolver` instead.\n *\n * Critical invariant: this module NEVER caches resolved keys across\n * `getStripeClient()` calls without the consumer opting in. Stripe\n * encourages key rotation (Atlas docs); a cached `sk_…` outlives the\n * rotation. The default `EnvTenantConfigResolver` re-reads env every\n * call. Consumers that want a memoized cache wrap with\n * `memoizeResolver(resolver, ttlMs)`.\n */\n\nimport { ConfigError } from './errors.js'\n\n/** Stable product identifiers — kept in sync with the product registry.\n * Adding a product is a one-line addition; we centralize so a typo at\n * a call site (`'legal-agent'` vs `'legal'`) is a type error. */\nexport type ProductId =\n | 'legal'\n | 'tax'\n | 'gtm'\n | 'creative'\n | 'agent-builder'\n\nexport const PRODUCT_IDS: readonly ProductId[] = Object.freeze([\n 'legal',\n 'tax',\n 'gtm',\n 'creative',\n 'agent-builder',\n])\n\nexport interface TenantStripeConfig {\n productId: ProductId\n /** Stripe API secret key. Treat as opaque — do NOT log. */\n secretKey: string\n /** Webhook signing secret (`whsec_...`). */\n webhookSecret: string\n /** Price ids the product explicitly approved for checkout. */\n approvedPriceIds?: readonly string[]\n /** Optional default URLs the checkout/portal generators fall back to. */\n successUrl?: string\n cancelUrl?: string\n /** Free-form metadata threaded through to the product (e.g., the\n * Connect account id if you later migrate to Connect). */\n metadata?: Record<string, string>\n}\n\n/** Stateless resolver — called per `getStripeClient()` / `resolveSecret()`.\n * Implementations: read from env (default), read from a vault, read\n * from a workspace-scoped DB row (per-tenant Connect). */\nexport interface TenantConfigResolver {\n resolve(productId: ProductId): Promise<TenantStripeConfig | null> | TenantStripeConfig | null\n}\n\n/* ---------------------------------------------------------------------- */\n/* env resolver */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Reads `STRIPE_SK_<PRODUCT>` + `STRIPE_WHSEC_<PRODUCT>` from\n * `process.env`. Product id is upper-snake-cased (`agent-builder` →\n * `AGENT_BUILDER`).\n *\n * Optional defaults:\n * STRIPE_SUCCESS_URL_<PRODUCT>\n * STRIPE_CANCEL_URL_<PRODUCT>\n */\nexport class EnvTenantConfigResolver implements TenantConfigResolver {\n constructor(private readonly env: NodeJS.ProcessEnv = process.env) {}\n\n resolve(productId: ProductId): TenantStripeConfig | null {\n const key = envKey(productId)\n const sk = this.env[`STRIPE_SK_${key}`]\n const wh = this.env[`STRIPE_WHSEC_${key}`]\n if (!sk || !wh) return null\n const approvedPriceIds = (this.env[`STRIPE_APPROVED_PRICE_IDS_${key}`] ?? '')\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return {\n productId,\n secretKey: sk,\n webhookSecret: wh,\n ...(approvedPriceIds.length > 0 ? { approvedPriceIds } : {}),\n successUrl: this.env[`STRIPE_SUCCESS_URL_${key}`],\n cancelUrl: this.env[`STRIPE_CANCEL_URL_${key}`],\n }\n }\n}\n\n/**\n * Static resolver — pass a hardcoded map, useful for tests and for\n * deployments that pull from a vault at boot.\n */\nexport class StaticTenantConfigResolver implements TenantConfigResolver {\n constructor(private readonly table: Partial<Record<ProductId, TenantStripeConfig>>) {}\n resolve(productId: ProductId): TenantStripeConfig | null {\n return this.table[productId] ?? null\n }\n}\n\n/**\n * Memoize a resolver with a TTL. Used in production to avoid pounding\n * a remote vault on every webhook. Default 60s — short enough that a\n * key rotation lands within the next minute.\n */\nexport function memoizeResolver(inner: TenantConfigResolver, ttlMs = 60_000): TenantConfigResolver {\n const cache = new Map<ProductId, { config: TenantStripeConfig | null; expiresAt: number }>()\n return {\n async resolve(productId: ProductId) {\n const now = Date.now()\n const hit = cache.get(productId)\n if (hit && hit.expiresAt > now) return hit.config\n const config = await inner.resolve(productId)\n cache.set(productId, { config, expiresAt: now + ttlMs })\n return config\n },\n }\n}\n\n/* ---------------------------------------------------------------------- */\n/* the Stripe client handle */\n/* ---------------------------------------------------------------------- */\n\n/**\n * Thin Stripe HTTP client handle. We do NOT depend on the `stripe`\n * npm package — same rationale as `stripe-pack`: keep the install\n * footprint zero, use `fetch` directly. The handle carries the\n * resolved secret + a Stripe-spec base URL so call sites can issue\n * scoped requests without re-resolving for every operation in a\n * batch.\n *\n * Idempotency-Key forwarding: every mutation MUST include an\n * `idempotency-key` header. Stripe enforces a 24h replay window\n * keyed off it. The `mutate()` helper accepts the key explicitly to\n * make it impossible to forget.\n */\nexport interface StripeClient {\n productId: ProductId\n config: TenantStripeConfig\n /** GET request — returns parsed JSON or throws on non-2xx. */\n get<T = unknown>(path: string, query?: Record<string, string>): Promise<T>\n /** Form-urlencoded POST/DELETE with idempotency. */\n mutate<T = unknown>(\n method: 'POST' | 'DELETE',\n path: string,\n body: Record<string, string | number | boolean | undefined>,\n idempotencyKey: string,\n ): Promise<T>\n}\n\nconst STRIPE_API = 'https://api.stripe.com/v1'\n\n/**\n * Look up the Stripe client for a product. Throws `ConfigError` if the\n * resolver returns null — the product agent fails its startup health\n * check and the deploy is held back. NEVER silently falls back to a\n * shared key.\n */\nexport async function getStripeClient(\n productId: ProductId,\n resolver: TenantConfigResolver,\n): Promise<StripeClient> {\n const config = await resolver.resolve(productId)\n if (!config) {\n throw new ConfigError({\n message: `Stripe not configured for product '${productId}'. Set STRIPE_SK_${envKey(productId)} and STRIPE_WHSEC_${envKey(productId)}.`,\n context: { productId },\n })\n }\n return buildClient(config)\n}\n\n/** Build a client from an already-resolved config — for callers that\n * manage resolution themselves (e.g., long-lived workers that\n * resolved at startup). */\nexport function buildStripeClient(config: TenantStripeConfig): StripeClient {\n return buildClient(config)\n}\n\nfunction buildClient(config: TenantStripeConfig): StripeClient {\n const auth = `Bearer ${config.secretKey}`\n return {\n productId: config.productId,\n config,\n async get<T>(path: string, query?: Record<string, string>): Promise<T> {\n const qs = query ? `?${new URLSearchParams(query).toString()}` : ''\n const res = await fetch(`${STRIPE_API}${path}${qs}`, {\n headers: { authorization: auth },\n signal: AbortSignal.timeout(10_000),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe ${path} ${res.status}: ${text.slice(0, 200)}`)\n }\n return (await res.json()) as T\n },\n async mutate<T>(\n method: 'POST' | 'DELETE',\n path: string,\n body: Record<string, string | number | boolean | undefined>,\n idempotencyKey: string,\n ): Promise<T> {\n const form = new URLSearchParams()\n for (const [k, v] of Object.entries(body)) {\n if (v === undefined) continue\n form.set(k, String(v))\n }\n const init: RequestInit = {\n method,\n headers: {\n authorization: auth,\n 'idempotency-key': idempotencyKey,\n ...(method === 'POST' ? { 'content-type': 'application/x-www-form-urlencoded' } : {}),\n },\n signal: AbortSignal.timeout(15_000),\n }\n if (method === 'POST') init.body = form\n const res = await fetch(`${STRIPE_API}${path}`, init)\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe ${path} ${res.status}: ${text.slice(0, 200)}`)\n }\n return (await res.json()) as T\n },\n }\n}\n\n/**\n * `WebhookRouter.resolveSecret` adapter. The router calls this with\n * the provider id and headers; we extract the product id from a\n * header the gateway routes by (`x-tangle-product`) and look it up.\n *\n * Why a header and not the URL path: the router is provider-keyed,\n * not product-keyed, by design. Products inject the header in their\n * gateway layer (Hono middleware in our case). The header is\n * authenticated as part of the gateway's edge auth — Stripe's own\n * signature still has to verify against the secret we return here,\n * so a forged header alone can't bypass anything.\n */\nexport function makeStripeSecretResolver(resolver: TenantConfigResolver) {\n return async function resolveSecret(\n providerId: string,\n headers: { [name: string]: string | string[] | undefined },\n ): Promise<string | null> {\n if (providerId !== 'stripe') return null\n const productHeader = headers['x-tangle-product']\n const productId = Array.isArray(productHeader) ? productHeader[0] : productHeader\n if (!productId || !isProductId(productId)) return null\n const config = await resolver.resolve(productId)\n return config?.webhookSecret ?? null\n }\n}\n\nfunction isProductId(s: string): s is ProductId {\n return (PRODUCT_IDS as readonly string[]).includes(s)\n}\n\nfunction envKey(productId: ProductId): string {\n return productId.toUpperCase().replace(/-/g, '_')\n}\n","/**\n * Drop-in middleware for product agents.\n *\n * One primitive consumers wire into their HTTP layer (Hono, Express,\n * raw Workers `fetch` handler — middleware here is framework-neutral,\n * returns a `BillingGate` value the consumer chooses how to respond to):\n *\n * requireActiveSubscription({ workspaceId, store })\n * → 'allow' | { allowed: false, error: BillingError }\n *\n * Frameworks: we don't import Hono / Express. The middleware shape is a\n * pure async function returning a decision. The product wires it into\n * its framework with a 3-line adapter (see `examples/hono.ts`).\n *\n * Past-due policy: by default `requireActiveSubscription` allows\n * `past_due` (the dunning grace window — see `gateAccess` in\n * `subscription-state.ts`). Pass `denyPastDue: true` to override\n * per-route (e.g., legal-agent's \"file new petition\" gate where\n * irreversible actions justify a stricter rule).\n */\n\nimport { BillingError } from './errors.js'\nimport { decideBillingAccess } from '../billing-access-policy.js'\nimport {\n gateAccess,\n type SubscriptionRecord,\n type SubscriptionStore,\n} from './subscription-state.js'\n\n/* ---------------------------------------------------------------------- */\n/* requireActiveSubscription */\n/* ---------------------------------------------------------------------- */\n\nexport interface RequireActiveSubscriptionInput {\n workspaceId: string\n store: SubscriptionStore\n /** Parsed Platform proof for the owner or an explicitly named service/admin. */\n accessEvidence?: import('../billing-access-policy.js').TrustedPlatformEvidence\n /** Optional owner id to compare with Platform proof. */\n expectedUserId?: string\n /** Strict mode: reject `past_due`. Default false (allow with warn). */\n denyPastDue?: boolean\n}\n\nexport type SubscriptionGateResult =\n | { allowed: true; record: SubscriptionRecord; warn?: 'past_due' | 'trial_ending' }\n | { allowed: false; error: BillingError }\n\n/**\n * Gate decision for a route that requires an active subscription.\n *\n * Returns `{ allowed: true }` on `active` and on `past_due` (unless\n * `denyPastDue`). A `trialing` record is denied because product-funded\n * trials are disabled. Returns `{ allowed: false, error }` with a typed\n * `BillingError` for any other state.\n */\nexport async function requireActiveSubscription(\n input: RequireActiveSubscriptionInput,\n): Promise<SubscriptionGateResult> {\n const record = await input.store.load(input.workspaceId)\n if (!record) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'subscription_required',\n message: 'This workspace has no Stripe subscription.',\n context: { workspaceId: input.workspaceId },\n }),\n }\n }\n const accessDecision = decideBillingAccess({\n evidence: input.accessEvidence,\n expectedUserId: input.expectedUserId,\n })\n if (!accessDecision.allowed) {\n return {\n allowed: false,\n error: new BillingError({\n code: accessDecision.code,\n message: accessDecision.reason,\n context: { workspaceId: input.workspaceId },\n }),\n }\n }\n if (\n accessDecision.basis !== 'paid_subscription' &&\n accessDecision.principal.kind === 'human'\n ) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'paid_evidence_required',\n message: 'Active subscription access requires matching paid subscription evidence.',\n context: { workspaceId: input.workspaceId },\n }),\n }\n }\n if (\n input.accessEvidence?.funding.kind === 'paid_subscription' &&\n input.accessEvidence.funding.subscriptionId !== record.subscriptionId\n ) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'platform_evidence_subject_mismatch',\n message: 'Subscription evidence does not match the stored subscription.',\n context: { workspaceId: input.workspaceId, subscriptionId: record.subscriptionId },\n }),\n }\n }\n const decision = gateAccess(record.state)\n if (!decision.allowed) {\n return {\n allowed: false,\n error: new BillingError({\n code: decision.reason === 'trial_expired'\n ? 'trial_expired'\n : decision.reason === 'subscription_inactive'\n ? 'subscription_inactive'\n : decision.reason === 'subscription_past_due'\n ? 'subscription_past_due'\n : 'subscription_required',\n message: `Subscription is ${record.state}.`,\n context: {\n workspaceId: input.workspaceId,\n subscriptionId: record.subscriptionId,\n subscriptionState: record.state,\n },\n }),\n }\n }\n if (decision.warn === 'past_due' && input.denyPastDue) {\n return {\n allowed: false,\n error: new BillingError({\n code: 'subscription_past_due',\n message: 'Subscription is past due — this action requires a current payment method.',\n context: {\n workspaceId: input.workspaceId,\n subscriptionId: record.subscriptionId,\n subscriptionState: record.state,\n },\n }),\n }\n }\n return { allowed: true, record, warn: decision.warn }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAa,eAAb,cAAkC,wBAAwB;CACxD;CACA;CAEA,YAAY,OAKT;EACD,MAAM;GACJ,MAAM,qBAAqB,MAAM,IAAI;GACrC,SAAS,MAAM;GACf,QAAQ,qBAAqB,MAAM,IAAI;GACvC,YAAY,MAAM,cAAc,kBAAkB,MAAM,IAAI;GAC5D,UAAU,MAAM;EAClB,CAAC;EACD,KAAK,OAAO;EACZ,KAAK,cAAc,MAAM;EACzB,KAAK,UAAU,MAAM,WAAW,CAAC;CACnC;AACF;;;;;AAMA,IAAa,cAAb,cAAiC,aAAa;CAC5C,YAAY,OAA2D;EACrE,MAAM;GACJ,MAAM;GACN,SAAS,MAAM;GACf,SAAS,MAAM;GACf,YAAY;IAAE,MAAM;IAAmB,OAAO;GAAkB;EAClE,CAAC;EACD,KAAK,OAAO;CACd;AACF;AAEA,SAAS,qBAAq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