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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ node_modules/
dist/
dev-dist/
.wrangler/
# cf build output + generated types
.cloudflare/
.turbo/
.dev.vars
*.local
Expand Down
10 changes: 10 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ Use Conventional Commits with a type **and** scope: `<type>(<scope>): <imperativ

- All wrangler commands must be prefixed with `npx` (e.g. `npx wrangler d1 execute ...`)

## Worker Config (cf)

Each worker (`packages/{api,auth,admin,frontend}`) is configured by **`cloudflare.config.ts`** (Worker settings, bindings, vars, routes/domains, crons, DO `exports`) plus **`wrangler.config.ts`** (build settings: assets dir, source maps). That is what **`cf build` / `cf deploy`** and the Workers Builds deploy triggers read. Each package pins `cf` and `wrangler` (the Wrangler bundler must be installed per package, not hoisted).

- **`wrangler.toml` is retained and must be kept in sync** - `pnpm dev` still runs `wrangler dev --persist-to ../../.wrangler/state` (`cf dev` can't share one persist dir across workers yet, and the api reads auth's DB via `AUTH_DB`), and the e2e suites/ops scripts use `npx wrangler d1 execute <db> --local`. **Any binding/var/route change goes in both files.**
- D1 migrations: `pnpm migrate` / `node scripts/migrate.mjs <local|remote>` run `cf d1 migrations apply <DATABASE_ID>` (remote unless `--local`).
- `annex-api`'s `DocCollabRoom` is declared as `exports.durableObject({ storage: "legacy-kv" })` - it was created with `new_classes` (KV-backed). Never change it to `"sqlite"`.
- The frontend package depends on Vite, so `cf build` would run `vite build` instead of Wrangler; its deploy is `pnpm build && pnpm build:worker (cf-wrangler build) && cf deploy --prebuilt`.
- Secrets are still set with `npx wrangler secret put <NAME> --name <worker>`; `cf deploy` keeps existing secrets.

## Local D1 State

The dev servers use a shared wrangler state at the **monorepo root** (`/.wrangler/state`), not inside each package. This is set via `--persist-to ../../.wrangler/state` in each package's dev script.
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,19 +190,19 @@ secrets (a bare `secret put` is refused until the latest version is deployed):

```bash
cd packages/api
npx wrangler deploy
pnpm run deploy # cf deploy
npx wrangler secret put R2_ACCESS_KEY_ID
npx wrangler secret put R2_SECRET_ACCESS_KEY
```

Enter each value at the interactive prompt (do **not** pipe it in via
PowerShell - it appends a CRLF and corrupts the secret). Then set the two vars
in `packages/api/wrangler.toml` (`R2_BUCKET_NAME` is already there):
in `packages/api/cloudflare.config.ts` (`R2_BUCKET_NAME` is already there), and
mirror them in `packages/api/wrangler.toml` `[vars]` (still used by local dev):

```toml
[vars]
R2_BUCKET_NAME = "cubedocs-assets"
R2_ACCOUNT_ID = "<your-cloudflare-account-id>"
```ts
R2_BUCKET_NAME: bindings.text("cubedocs-assets"),
R2_ACCOUNT_ID: bindings.text("<your-cloudflare-account-id>"),
```

All four values must be present, or presigning stays off and video uses the
Expand Down
8 changes: 4 additions & 4 deletions docs/oauth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Annex secret is ever shared with a connected service.
`auth` - e.g. `AAAA auth 100::` (a placeholder; the Worker route handles the
request, the record just makes the hostname resolve to Cloudflare's edge).
The `auth.cubityfir.st/oauth/*` and `/.well-known/*` routes in
`packages/auth/wrangler.toml` attach the auth worker to those paths only -
`packages/auth/cloudflare.config.ts` attach the auth worker to those paths only -
nothing else on the auth worker is reachable at that host.

3. **Apply the migration** (creates `oauth_clients` + `oauth_codes`):
Expand All @@ -76,9 +76,9 @@ Annex secret is ever shared with a connected service.
`loadCurrentSession`, so the auth/api/admin triple-redeploy rule does *not*
apply here - but auth, api, and frontend each changed):
```bash
cd packages/auth && npx wrangler deploy # endpoints + routes + migration
cd packages/api && npx wrangler deploy # /oauth/authorize proxy
cd packages/frontend && pnpm build && npx wrangler deploy # /oauth/authorize SPA page
cd packages/auth && pnpm run deploy # endpoints + routes (cf deploy)
cd packages/api && pnpm run deploy # /oauth/authorize proxy
cd packages/frontend && pnpm run deploy # /oauth/authorize SPA page
```

5. **Smoke-test discovery + JWKS:**
Expand Down
4 changes: 2 additions & 2 deletions memories/Custom-Domains.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ Custom hostnames are created **non-wildcard** (`wildcard: false`) with **TXT DCV
1. **Enable Cloudflare for SaaS** on the `yourannex.com` zone (paid add-on).
2. **CNAME target**: create a proxied record `publish.yourannex.com AAAA 100::` (orange cloud) - the hostname customers point their CNAME at.
3. **Fallback origin**: set the zone's SaaS fallback origin to `publish.yourannex.com` (the same proxied record doubles as the fallback origin, so the apex stays free). Must reach **Active**.
4. **Worker route**: add `*/*` → `annex-frontend` on the `yourannex.com` zone (the "Workers as your fallback origin" pattern). This is declared in `packages/frontend/wrangler.toml` (`pattern="*/*" zone_name="yourannex.com"`), so deploying the frontend creates it.
5. **Config** (`packages/api/wrangler.toml`): `CF_ZONE_ID = "397deb54a68d306201a295d1793fe84c"`, `CUSTOM_DOMAIN_CNAME_TARGET = "publish.yourannex.com"`, and `wrangler secret put CF_API_TOKEN` (token scoped to the **yourannex.com** zone with **SSL and Certificates: Edit**).
4. **Worker route**: add `*/*` → `annex-frontend` on the `yourannex.com` zone (the "Workers as your fallback origin" pattern). This is declared in `packages/frontend/cloudflare.config.ts` (`triggers.fetch({ pattern: "*/*", zone: "yourannex.com" })`, mirrored in `wrangler.toml`), so deploying the frontend creates it.
5. **Config** (`packages/api/cloudflare.config.ts`, mirrored in `wrangler.toml`): `CF_ZONE_ID = "397deb54a68d306201a295d1793fe84c"`, `CUSTOM_DOMAIN_CNAME_TARGET = "publish.yourannex.com"`, and `wrangler secret put CF_API_TOKEN` (token scoped to the **yourannex.com** zone with **SSL and Certificates: Edit**).
6. Customers then add: a **CNAME** `their.domain → publish.yourannex.com`, plus the **TXT** ownership + SSL-DCV records shown in Site Settings.

**Cleanup of the old shared-zone setup:** delete the stale `*/*` Worker route on the `cubityfir.st` zone (wrangler won't remove it - it only manages routes in the frontend toml, which now targets `yourannex.com`). No carve-out routes (`*.cubityfir.st/*` → None) are needed once `cubityfir.st` has no `*/*`.
Expand Down
2 changes: 1 addition & 1 deletion memories/Ink-Stripe.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ The CLI prints a `whsec_...` at startup - that's what goes in `STRIPE_WEBHOOK_SE

## Production setup

- `STRIPE_INK_PRICE_ID` is in `packages/auth/wrangler.toml` `[vars]` (live price id - committed). `.dev.vars` overrides locally to the test-mode price id.
- `STRIPE_INK_PRICE_ID` is a `bindings.text` var in `packages/auth/cloudflare.config.ts` (mirrored in `wrangler.toml` `[vars]`) (live price id - committed). `.dev.vars` overrides locally to the test-mode price id.
- `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` set via `wrangler secret put` on the auth worker. `STRIPE_SECRET_KEY` also on admin worker.
- Webhook endpoint URL in Stripe Dashboard: `https://docs.cubityfir.st/stripe/webhook`. Subscribed events: `checkout.session.completed`, `customer.subscription.created/updated/deleted`, `invoice.paid`, `invoice.payment_failed`.
- Customer Portal must be configured separately in **live** mode (Settings → Billing → Customer portal). Test mode and live mode have different portal configs.
Expand Down
2 changes: 1 addition & 1 deletion memories/Oidc-Provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Generalizes the single-purpose admin handoff (`admin_handoffs`, 0009).
- **Issuer** = `https://auth.cubityfir.st` (dedicated identity host, decoupled
from the app origin which may migrate). The auth worker serves
`/oauth/{token,userinfo,jwks}` + `/.well-known/openid-configuration` there
directly via two `wrangler.toml` routes (`auth.cubityfir.st/oauth/*`,
directly via two routes in `packages/auth/cloudflare.config.ts` (`auth.cubityfir.st/oauth/*`,
`/.well-known/*`). Needs a **proxied** DNS record for `auth.cubityfir.st` on
the `cubityfir.st` zone.
- **authorization_endpoint** = `https://docs.cubityfir.st/oauth/authorize` - a
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"build": "concurrently \"pnpm --filter frontend build\" \"pnpm --filter api build\" \"pnpm --filter auth build\" \"pnpm --filter @annex/admin build\"",
"deploy": "concurrently \"pnpm --filter frontend deploy\" \"pnpm --filter api deploy\" \"pnpm --filter auth deploy\" \"pnpm --filter @annex/admin deploy\"",
"typecheck": "concurrently \"pnpm --filter frontend typecheck\" \"pnpm --filter api typecheck\" \"pnpm --filter auth typecheck\" \"pnpm --filter @annex/admin typecheck\" \"pnpm --filter @annex/admin-frontend typecheck\" \"pnpm --filter @annex/mcp typecheck\"",
"migrate": "pnpm --filter api migrate && pnpm --filter auth migrate",
"migrate": "pnpm --filter api migrate && pnpm --filter auth migrate",
"migrations:local": "node scripts/migrate.mjs local",
"migrations:remote": "node scripts/migrate.mjs remote",
"test": "concurrently \"pnpm --filter api test\" \"pnpm --filter auth test\" \"pnpm --filter frontend test\" \"pnpm --filter @annex/mcp test\" && pnpm test:e2e",
Expand All @@ -18,7 +18,7 @@
"devDependencies": {
"concurrently": "^9.0.0",
"typescript": "^5.5.0",
"wrangler": "^4.101.0"
"wrangler": "^4.156.0"
},
"packageManager": "pnpm@10.32.1",
"pnpm": {
Expand Down
105 changes: 105 additions & 0 deletions packages/admin/cloudflare.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { bindings, defineConfig, triggers } from "cf/config";

export default defineConfig({
accountId: "d843ae90cab33e54f4d284bc65d2fd6a",
worker: {
name: "annex-admin",
// Keep in lockstep with the auth worker's compatibilityDate: this worker
// imports auth source (session.ts/jwt.ts) cross-package, so runtime-behavior
// differences between dates would make shared code behave differently per
// worker.
compatibilityDate: "2026-02-24",
entrypoint: "src/index.ts",
workersDev: false,
// Asset directory (./dist, built by `pnpm build` from ./frontend) is a
// build setting - see wrangler.config.ts.
assets: {
htmlHandling: "auto-trailing-slash",
notFoundHandling: "single-page-application",
},
domains: [
"admin.cubityfir.st",
],
triggers: [
// Hourly: performs account deletions scheduled from the Users page once
// their grace window has passed (src/lib/userDeletion.ts
// runDueUserDeletions).
triggers.scheduled({
schedule: "17 * * * *",
}),
],
env: {
// Cloudflare-for-SaaS custom domains - used to release a site's custom
// hostname when an admin removes a domain or deletes the site (mirrors
// the api worker). MUST match the api worker's values (the dedicated
// yourannex.com zone - see memories/Custom-Domains.md), and CF_API_TOKEN
// must be scoped to that zone. When CF_ZONE_ID / CF_API_TOKEN are unset,
// the CF call is a safe no-op (the DB row is still removed).
CF_ZONE_ID: bindings.text("397deb54a68d306201a295d1793fe84c"),
CUSTOM_DOMAIN_CNAME_TARGET: bindings.text("cname.yourannex.com"),
DB: bindings.d1({
name: "cubedocs-main",
id: "267490be-7141-4d00-ab23-152742f2f6ef",
}),
// Read+write: unlike the API worker's read-only-by-convention AUTH_DB
// binding, the admin worker writes users (moderation/
// force_password_change), user_moderation_events, user_preferences
// (badges), user_billing (grant columns), and admin_audit_log directly.
// Credential/session/oauth_clients writes still go through the AUTH
// service binding. Migrations live only in packages/auth/migrations/.
AUTH_DB: bindings.d1({
name: "cubedocs-auth",
id: "db327d85-b8c2-4fed-adaa-25e748778c86",
}),
ASSETS: bindings.r2({
name: "cubedocs-assets",
}),
AUTH: bindings.worker({
worker: "annex-auth",
}),
// GA ratelimit bindings - simulated locally in dev. See the auth
// worker's cloudflare.config.ts.
// IP-keyed coarse abuse cap across every authenticated admin API route.
// Generous enough for an operator clicking around the dashboard; only
// bites scripted abuse with a stolen admin token.
RATE_LIMITER_ADMIN: bindings.rateLimit({
namespace: "2001",
simple: {
limit: 60,
period: 60,
},
}),
// Tighter, separate bucket for the unauthenticated handoff-exchange
// proxy (the only pre-auth endpoint that hits the auth worker + DB).
RATE_LIMITER_ADMIN_HANDOFF: bindings.rateLimit({
namespace: "2002",
simple: {
limit: 10,
period: 60,
},
}),
// Separate budget for the public avatar route: a 25-row dashboard page
// costs 25 avatar fetches, which previously drained the shared admin
// API budget and started 429ing the operator after ~2 searches/min.
RATE_LIMITER_AVATAR: bindings.rateLimit({
namespace: "2003",
simple: {
limit: 300,
period: 60,
},
}),
SITE_ASSETS: bindings.assets(),
// Secrets (set via `npx wrangler secret put <NAME> --name annex-admin`;
// existing secrets are kept across `cf deploy`):
// JWT_SECRET (same value as the auth worker's JWT_SECRET - the
// admin worker verifies sessions inline against
// AUTH_DB instead of calling auth's /verify route)
// STRIPE_SECRET_KEY (sk_test_... or sk_live_... - same value as auth
// worker; only used for admin-driven cancellations
// triggered from the user details panel)
// CF_API_TOKEN (same token as the api worker - zone-scoped, SSL
// and Certificates: Edit; only used to release a
// custom hostname on admin-driven site delete)
},
},
});
7 changes: 5 additions & 2 deletions packages/admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
"name": "@annex/admin",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"dev": "concurrently \"cd frontend && pnpm dev\" \"pnpm exec wrangler dev --port 8789 --persist-to ../../.wrangler/state\"",
"build": "cd frontend && pnpm build",
"deploy": "pnpm build && pnpm exec wrangler deploy",
"deploy": "pnpm build && cf deploy",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
Expand All @@ -16,8 +17,10 @@
"devDependencies": {
"@cloudflare/workers-types": "^4.0.0",
"@types/node": "^22.19.15",
"cf": "1.0.0-beta.26",
"concurrently": "^9.2.1",
"typescript": "^5.5.0",
"vitest": "^4.1.6"
"vitest": "^4.1.6",
"wrangler": "^4.156.0"
}
}
4 changes: 2 additions & 2 deletions packages/admin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface Env {
// schema change to users/sessions/user_billing/user_preferences columns
// read by loadCurrentSession requires redeploying auth + api + admin.
JWT_SECRET: string;
// IP-keyed rate limiters (Cloudflare ratelimit bindings - see wrangler.toml).
// IP-keyed rate limiters (Cloudflare ratelimit bindings - see cloudflare.config.ts).
// RATE_LIMITER_ADMIN gates every authenticated admin API route;
// RATE_LIMITER_ADMIN_HANDOFF gates the unauthenticated exchange proxy;
// RATE_LIMITER_AVATAR gates the public avatar route on its own budget so
Expand Down Expand Up @@ -214,7 +214,7 @@ export { app };

export default {
fetch: app.fetch,
// Hourly cron (see wrangler.toml [triggers]): performs account deletions
// Hourly cron (see cloudflare.config.ts triggers): performs account deletions
// scheduled from the Users page once their grace window has passed.
async scheduled(_controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
ctx.waitUntil(
Expand Down
2 changes: 1 addition & 1 deletion packages/admin/src/routes/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { AppEnv } from "../index";
// and write is forwarded. Note the admin worker does write OTHER auth-DB
// tables directly (users moderation, user_preferences badges, user_billing
// grants, admin_audit_log) - see the AUTH_DB write-boundary note in
// wrangler.toml / CLAUDE.md. `enforceAdmin` has already validated the
// cloudflare.config.ts / CLAUDE.md. `enforceAdmin` has already validated the
// session; the auth worker re-checks it as defence in depth.

const oauthRouter = new Hono<AppEnv>();
Expand Down
15 changes: 15 additions & 0 deletions packages/admin/wrangler.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { defineWranglerConfig } from "wrangler/experimental-config";

// Wrangler build settings for `cf build` / `cf deploy` (Worker config and
// bindings live in cloudflare.config.ts).
//
// Local dev (`pnpm dev`) still runs `wrangler dev --persist-to ../../.wrangler/state`
// against wrangler.toml: every worker must share one local state dir (the api
// worker reads the auth DB via AUTH_DB), and `cf dev` cannot set a persist
// directory yet (it always uses <package>/.wrangler/state).
export default defineWranglerConfig({
// Built by `pnpm build` (the admin SPA in ./frontend).
assetsDirectory: "./dist",
// Match the previous `wrangler deploy` default (no source map upload).
uploadSourceMaps: false,
});
8 changes: 8 additions & 0 deletions packages/admin/wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# NOTE: `cf build` / `cf deploy` (and Workers Builds) read ./cloudflare.config.ts
# (+ ./wrangler.config.ts for build settings) - that is the deploy source of truth.
# This file is kept for Wrangler commands that still need a config: local dev
# (`wrangler dev --persist-to ../../.wrangler/state`, because `cf dev` can't share
# one persist dir across workers yet) and `npx wrangler d1 execute <db> --local`
# used by the e2e suites and ops scripts. Keep every binding/var change mirrored
# in both files.

name = "annex-admin"
main = "src/index.ts"
# Keep in lockstep with the auth worker's compatibility_date: this worker
Expand Down
Loading
Loading