Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ jobs:
X_CLIENT_SECRET: ${{ secrets.OAUTH_X_CLIENT_SECRET }}
KIT_API_KEY: ${{ secrets.KIT_API_KEY }}
STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}
STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }}
run: >
node tools/ci/sync-worker-secrets.ts --env production --config
"$WRANGLER_CONFIG" --set-from-env COOKIE_SECRET
Expand All @@ -140,7 +141,8 @@ jobs:
GOOGLE_CLIENT_ID --set-from-env-optional GOOGLE_CLIENT_SECRET
--set-from-env-optional X_CLIENT_ID --set-from-env-optional
X_CLIENT_SECRET --set-from-env-optional KIT_API_KEY
--set-from-env-optional STRIPE_SECRET_KEY
--set-from-env-optional STRIPE_SECRET_KEY --set-from-env-optional
STRIPE_WEBHOOK_SECRET

- name: 🗄️ Apply D1 Migrations
env:
Expand Down
3 changes: 3 additions & 0 deletions docs/contributing/architecture/data-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,9 @@ Current retention policies:
any remaining rows.
- `audit_events`: global hashed auth/security audit events keep 180 days. They
are not user-owned D1 rows and remain independent of account deletion/export.
- `stripe_webhook_events`: platform Stripe webhook idempotency rows keep 30 days
by `processed_at`. They are not user-owned and remain independent of account
deletion/export.

Migration `0055-retention-indexes.sql` adds the global time-column indexes these
prunes order by (`created_at` / `day` / `month` / `started_at` across users);
Expand Down
49 changes: 40 additions & 9 deletions docs/contributing/architecture/entitlements.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,16 +343,47 @@ manual plans only.

Checkout sessions are created server-side for authenticated users via
`POST /account/billing/checkout.json` (Stripe Checkout Session,
`mode=subscription`, with a signed `client_reference_id`). Public Payment Links
were removed after a card-testing incident so checkout is not reachable without
a signed-in session. `GET /account/billing/success` verifies
`client_reference_id` before linking `users.stripe_customer_id`, then refreshes
`users.stripe_plan`. `GET /account/billing/portal` opens the Stripe customer
portal for linked customers.

`users.stripe_plan` stays fresh via an hourly cron lane
`mode=subscription`, with a signed `client_reference_id` and
`metadata.kody_stable_user_id`). Public Payment Links were removed after a
card-testing incident so checkout is not reachable without a signed-in session.
`GET /account/billing/success` verifies `client_reference_id` before linking
`users.stripe_customer_id`, then refreshes `users.stripe_plan`.
`GET /account/billing/portal` opens the Stripe customer portal for linked
customers.

### Webhooks (primary sync)

`POST /webhooks/stripe` is the primary path for linking customers and refreshing
plans when Stripe subscription state changes. It is unauthenticated and verifies
the `Stripe-Signature` header with `STRIPE_WEBHOOK_SECRET` (HMAC-SHA256 over
`${t}.${rawBody}`; ~300s timestamp tolerance). When the secret is unset, the
endpoint returns 503.

Handled event types:

- `checkout.session.completed` — resolve the user via `client_reference_id`
matching `createBillingLinkReference` (candidates from
`metadata.kody_stable_user_id`, existing `stripe_customer_id`, or customer
email), then run the same link+refresh helper as the success redirect
- `customer.subscription.updated` / `customer.subscription.deleted` — look up
the user by `users.stripe_customer_id` and call `refreshStripePlanForUser`
- `invoice.payment_failed` — same customer lookup + refresh (surfaces
`subscriptionStatus` such as `past_due` for UX; does not email users)
- Unknown event types — acknowledge `200` after process+record

Idempotency uses migration `0093-stripe-webhook-events.sql`
(`stripe_webhook_events.event_id` unique). Events are processed first (handlers
are idempotent), then recorded. A UNIQUE conflict after a successful process is
treated as duplicate success (`200`). Process failures return `500` without
inserting so Stripe can retry. Rows older than 30 days are pruned by retention.

### Poll backup

`users.stripe_plan` also stays fresh via an hourly cron lane
(`refreshStaleStripePlans`: 25 users/sweep, 1h staleness) and an on-page refresh
when `/account/billing` loads with data older than 60s. Migration
every time `/account/billing` loads (always calls Stripe so non-persisted
`cancel_at` / `subscriptionStatus` stay current). Keep the poll as a backup if a
webhook is missed or the success URL is never hit. Migration
`0066-stripe-billing.sql` adds `stripe_customer_id` (unique partial index),
`stripe_plan`, and `stripe_plan_refreshed_at`.

Expand Down
6 changes: 4 additions & 2 deletions docs/contributing/architecture/primitives.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ primitives:
- packages/worker/src/repo/repo-session-cleanup.ts
- packages/worker/src/app/retention.ts
- packages/worker/src/app/auth-denial-alerts.ts
- packages/worker/src/app/email-delivery-alerts.ts
- packages/worker/src/usage/aggregate-rollups.ts
docs:
- docs/contributing/architecture/data-storage.md
Expand Down Expand Up @@ -143,10 +144,11 @@ primitives:
group: auth
name: Stripe billing
summary:
Authenticated Checkout Session creation, customer linking, and
subscription→plan sync.
Authenticated Checkout Session creation, Stripe webhooks, customer
linking, and subscription→plan sync (cron poll as backup).
code:
- packages/worker/src/billing/
- packages/worker/src/app/handlers/stripe-webhook.ts
docs:
- docs/contributing/architecture/entitlements.md

Expand Down
4 changes: 4 additions & 0 deletions docs/contributing/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ safely. Manual `users.plan` grants and invite-assigned plans still work.
- `STRIPE_SECRET_KEY` — Stripe secret API key. Required for checkout linking,
portal sessions, and `stripe_plan` refresh. Synced as a Worker secret from the
GitHub Actions secret of the same name on production deploy when set.
- `STRIPE_WEBHOOK_SECRET` — Stripe endpoint signing secret (`whsec_...`) for
`POST /webhooks/stripe`. When unset, the webhook endpoint returns 503. Synced
as a Worker secret from the GitHub Actions secret of the same name on
production deploy when set.
- `STRIPE_API_BASE_URL` — optional API base URL; defaults to
`https://api.stripe.com` when unset. Override for tests/mocks.
- `STRIPE_PRO_PRICE_ID` — Stripe Price id used to map active/trialing
Expand Down
15 changes: 14 additions & 1 deletion docs/contributing/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@ MCP auth denials in the last 60 minutes cross a threshold (default 50). A KV
cooldown prevents re-paging on the same sustained spike. Charts on
`/admin/insights` remain the browse surface; the email is the page.

A second hourly lane (`email_delivery_alert`, implemented by
`checkEmailDeliveryBurstAndNotify` in
`packages/worker/src/app/email-delivery-alerts.ts`) pages admins when
platform-wide Cloudflare Email Sending outcomes of `complained` or `bounced` in
the last 60 minutes cross a threshold (default 20). Those match the
outbound-abuse reputation signals (`failed` / `rejected` are not counted).
Cooldown is 6 hours via `BUNDLE_ARTIFACTS_KV`. This complements the per-user
outbound pause in `outbound-abuse.ts` — that path stops one account; the cron
pages when the shared sending domain is under platform-wide pressure. Review the
Email delivery health chart on `/admin/insights`.

**Deliberately not recorded:** rejections that happen before a grant resolves —
a missing, empty, or unparseable bearer token. Those are reachable by any
anonymous request, so auditing them would let a stranger drive unbounded D1
Expand Down Expand Up @@ -211,7 +222,9 @@ blast radius:
is idempotent (only transitions NULL), the send path rejects while paused, and
the audited `resume_email_outbound` admin action clears it after review. The
`/admin/insights` "Email delivery health" chart shows platform-wide outcome
trends so reputation trouble is visible before providers act on it.
trends so reputation trouble is visible before providers act on it. The hourly
`email_delivery_alert` cron pages admins on a platform-wide burst (see above)
without replacing this per-user pause.
- **Compute quotas.** `execute_calls_per_day` and `outbound_fetches_per_day`
entitlements bound sandbox compute and egress volume per user per day (see
[`architecture/entitlements.md`](./architecture/entitlements.md)).
Expand Down
5 changes: 5 additions & 0 deletions docs/contributing/setup-manifest.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ automatically:
- `STRIPE_SECRET_KEY` (optional Worker secret; enables Stripe checkout linking,
billing portal, and `users.stripe_plan` refresh. When unset, billing degrades
to manual plans.)
- `STRIPE_WEBHOOK_SECRET` (optional Worker secret; Stripe webhook signing secret
for `POST /webhooks/stripe`. When unset, the webhook endpoint returns 503.)
- `STRIPE_API_BASE_URL` (optional; defaults to `https://api.stripe.com`.
Override for tests/mocks.)
- `STRIPE_PRO_PRICE_ID` (optional Worker var; Stripe Price id mapped to the
Expand Down Expand Up @@ -302,6 +304,9 @@ Configure these GitHub Actions secrets and variables for workflows:
for account billing. Production deploy syncs it when set. The Pro price id is
a Worker var committed in `packages/worker/wrangler.jsonc`, not a GitHub
secret.)
- `STRIPE_WEBHOOK_SECRET` (optional GitHub / Worker secret; Stripe endpoint
signing secret (`whsec_...`) for platform billing webhooks at
`POST /webhooks/stripe`. Production deploy syncs it when set.)
- `SENTRY_AUTH_TOKEN` (optional GitHub **secret**; Sentry auth token with
`project:releases` / source map upload permissions — used only by CI to run
`npm run sentry:upload-sourcemaps` after deploy)
Expand Down
3 changes: 3 additions & 0 deletions packages/worker/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ X_CLIENT_SECRET=MOCK_X_CLIENT_SECRET
# "Billing is not configured" notice, and success/portal/cron skip safely.
# Checkout sessions are created server-side for authenticated users.
# STRIPE_SECRET_KEY=sk_test_...
# Platform webhook signing secret for POST /webhooks/stripe (whsec_...).
# When unset, the webhook endpoint returns 503.
# STRIPE_WEBHOOK_SECRET=whsec_...
# STRIPE_API_BASE_URL=https://api.stripe.com
# STRIPE_PRO_PRICE_ID=price_...

Loading
Loading