[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AW2TXFDAX1XX85SSZZQRHS":3,"skill-same:01M7AW2TXFDAX1XX85SSZZQRHS":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7AW2TXFDAX1XX85SSZZQRHS","betterauth",null,"Stand up, migrate to, or debug Better Auth on Cloudflare Workers + D1 — the auth stack behind improvebayarea.com and example.com. Use when building auth into a NEW site from scratch (ordered greenfield path + the verified core D1 schema), when adding auth to an existing Worker, migrating off a hosted provider, wiring Google\u002FApple social sign-in, adding passkeys\u002F2FA\u002Fmagic-link\u002Femail-OTP, writing a plugin's D1 migration, or debugging \"Invalid token\", \"account_not_linked\", a native iOS sign-in that fails after the OAuth sheet succeeds, a social button that won't appear inside a Capacitor webview, a \"Turn on two-factor\" button that does nothing, a passkey ceremony that reports \"cancelled or timed out\", or a CORRECT password that reports the session did not stick. Encodes the traps that cost real deploy cycles on both sites, each with the probe that proves it.","barkleesanders\u002Fclaude-code-starter","barkleesanders","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F30680901?v=4","01M7AW019CGBYWDA8MFJEN1JXC","Barklee Sanders","01M7AW01A5H994ASJ2QZPW67AV",4,"MIT","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fbetterauth\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: betterauth\ndescription: >-\n  Stand up, migrate to, or debug Better Auth on Cloudflare Workers + D1 — the auth\n  stack behind improvebayarea.com and example.com. Use when building auth into a\n  NEW site from scratch (ordered greenfield path + the verified core D1 schema), when\n  adding auth to an existing Worker, migrating off a hosted provider, wiring\n  Google\u002FApple social sign-in, adding\n  passkeys\u002F2FA\u002Fmagic-link\u002Femail-OTP, writing a plugin's D1 migration, or debugging\n  \"Invalid token\", \"account_not_linked\", a native iOS sign-in that fails after the\n  OAuth sheet succeeds, a social button that won't appear inside a Capacitor\n  webview, a \"Turn on two-factor\" button that does nothing, a passkey ceremony that\n  reports \"cancelled or timed out\", or a CORRECT password that reports the session\n  did not stick. Encodes the traps that cost real deploy cycles on both sites, each\n  with the probe that proves it.\n---\n\n# Better Auth on Cloudflare Workers + D1\n\nBoth of the user's auth-bearing sites declare **better-auth `^1.6.25`** on a Worker\nwith a D1 binding. This skill is the delta between \"the docs\" and \"what actually\nbroke.\"\n\n**Read the traps before writing code.** Every one below cost at least one deploy\ncycle, and each carries the command that proves it rather than an assertion.\n\n## Mandatory security baseline for every site and every ship\n\nLoad `~\u002F.claude\u002Fskills\u002Fshared\u002Fbetterauth-security-baseline.md` before implementation.\nEvery Better Auth site must propagate authentication email failures through the actual HTTP\nhandler, explicitly protect OTP storage, hash magic-link tokens when enabled, and enforce\nsecond-factor challenges for enrolled users across every enabled primary sign-in path without\nleaking provisional sessions or bearer tokens. A throwing email helper alone is insufficient\non SDK versions whose `runInBackgroundOrAwait` catches the rejection.\n\nNew sites must include real-SDK regression tests and `betterauth.security.json`, wire the full\nsecurity gate into every deploy entrypoint, and release via `\u002Fship`. Existing sites run the\nsame gate on **every ship**, even on a non-auth diff:\n\n```sh\nnode \"$HOME\u002Ftools\u002Fbetterauth\u002Fbetterauth\" security --repo \"$PWD\" --json\n```\n\nOnly exit 0 permits release; missing\u002Funmeasured\u002Ffailed tests block. Static configuration\nchecks and health routes do not replace behavior tests. Read the shared reference and CLI\nREADME for the mutation contract, transition behavior, and scope limitations.\n\n## Current state (verify, don't trust this table — it is a cache)\n\nVerified 2026-08-05.\n\n| | improvebayarea.com | example.com |\n|---|---|---|\n| Repo | `~\u002Ftools\u002Fimprovebayarea` | `~\u002FAIVA-Frontend` |\n| Auth file | `src\u002Fauth.ts` | `src\u002Fworker\u002Fauth.ts` |\n| Shape | Hono SSR, inline client JS in `src\u002Fui.ts` | React SPA + Hono SSR |\n| **Installed** better-auth | **1.6.26** | **1.6.25** |\n| Plugins | `bearer`, `magicLink`, `emailOTP`, `twoFactor`, `passkey` | `bearer`, `emailOTP`, `twoFactor`, `passkey` |\n| Native social | **yes** — `@capgo\u002Fcapacitor-social-login`, live | plugin installed + SPM-linked, **no JS call site** |\n| Native audience fix | Google + Apple (Trap 1) | Apple present; **Google still absent** — no iOS OAuth client exists yet |\n\n⚠️ **Identical `^1.6.25` ranges, different installed versions.** Adding\n`@better-auth\u002Fpasskey@^1.6.26` to IBA let npm re-resolve the caret and float core\nto 1.6.26; AIVA never re-installed and sits at 1.6.25. `package.json` therefore\n**cannot** tell you what is running — the plugin schema you transcribe a migration\nfrom (Trap 8) is the *installed* one. Always read `node_modules`.\n\nRe-check with:\n```bash\nnode -e \"const p=require('.\u002Fpackage.json').dependencies;\nconsole.log('range:',p['better-auth'],'| installed:',require('better-auth\u002Fpackage.json').version)\"\ngrep -nE \"socialProviders|plugins: \\[\" -A 20 \u003Cauth-file>\n```\n\n⚠️ **npm latest has moved past this table — re-check before pinning a NEW project (added 2026-08-30).**\nVerified live on 2026-08-30: **`better-auth` latest on npm is `1.7.2`** (published 2026-08-26), while\nboth sites above are still on **1.6.26 \u002F 1.6.25** — a minor version behind. The table is accurate about\n*these two sites*; it is NOT a version recommendation for a greenfield build, and reading it as one is\nexactly the mistake it invites. This bit for real: on 2026-08-30 a new Workers project was briefed with\n`better-auth ^1.6.26` copied straight out of this file, 25 days stale, and the pin had to be corrected\nmid-build.\n\n**So for any NEW site, resolve the version from the registry, not from here:**\n```bash\ncurl -s https:\u002F\u002Fregistry.npmjs.org\u002Fbetter-auth | python3 -c \"import json,sys;d=json.load(sys.stdin);v=d['dist-tags']['latest'];print(v, d['time'][v][:10])\"\n```\nThen install, and transcribe every plugin migration from the schema in `node_modules` (Trap 8) — a\n1.6.x → 1.7.x jump can move a core or plugin table, and this file documents the 1.6.x shape.\n\n## Standing up a NEW site (do it in this order)\n\nMost of this skill is written from two live migrations, so it reads as \"fix the\nthing that broke.\" On a greenfield site nothing has broken yet — follow this order\nand most traps never fire. Traps 7 (id preservation) and the decommission section\ndo not apply at all; skip them.\n\n| # | Step | The trap it pre-empts |\n|---|---|---|\n| 1 | Create the D1 database + binding `DB`; write the **core schema** migration (below) and apply it `--remote` | Plugin\u002Fcore code writes these tables on first use; a missing column is a generic 500 (Trap 11) |\n| 2 | `openssl rand -base64 32 \\| wrangler secret put BETTER_AUTH_SECRET` | — |\n| 3 | `createAuth(env)` per request + mount both verbs on `\u002Fapi\u002Fauth\u002F*` | Trap 2 |\n| 4 | Prove it before adding anything: `\u002Fapi\u002Fauth\u002Fok` → 200, wrong password → 401 | A green build is not a working auth route |\n| 5 | Add providers ONE at a time, each with its own migration when it has tables | Trap 11 — transcribe DDL from the **installed** package |\n| 6 | Add the Capacitor shell LAST, if there is one | Traps 1, 3, 4, 5 all live here and all need a new binary |\n\n**Decide two things on day one, because changing them later invalidates live\ncredentials:** `advanced.cookiePrefix` (renaming it signs every user out) and\n`PASSKEY_RP_ID` (changing it invalidates every registered passkey — they are bound\nto the RP id).\n\n### The core schema — verified against prod, not transcribed from docs\n\n> ⚠️ **THIS DDL IS 1.6.x AND IS WRONG FOR better-auth 1.7.x (added 2026-08-30).**\n> Measured by reading the INSTALLED 1.7.2 package — `@better-auth\u002Fcore\u002Fdist\u002Fdb\u002Fget-tables.mjs`\n> (`buildAuthTables`) and `...\u002Fdb\u002Fschema\u002Faccount.mjs` (`accountSchema`) — **not** from docs:\n>\n> 1. **NEW REQUIRED COLUMN** on `account`: `issuer text NOT NULL` (`accountSchema` declares\n>    `issuer: z.string()` with no `.nullish()`, so it is mandatory).\n> 2. **NEW UNIQUE INDEX** `(issuer, accountId)`.\n> 3. Field **order** changed: `issuer, accountId, providerId, userId, …`.\n>\n> Apply the DDL below unmodified against 1.7.x and **every account write 500s** with\n> `no such column: issuer` — visible only in `wrangler tail`, never in the response body.\n> That is Trap 11 biting the *core* schema rather than a plugin's.\n>\n> **So do what Trap 11 already tells you to do for plugins, and do it for core too:\n> transcribe from `node_modules`, not from this file.** The block below is a reference for\n> shape and constraints, not a copy-paste source. Re-derive before every new build:\n> ```bash\n> node -e \"console.log(require('better-auth\u002Fpackage.json').version)\"\n> grep -rn 'issuer' node_modules\u002F@better-auth\u002Fcore\u002Fdist\u002Fdb\u002Fschema\u002Faccount.mjs\n> ```\n\n\nbetter-auth needs four tables before any plugin. This is improvebayarea's applied\nmigration, confirmed live on 2026-08-05 via\n`wrangler d1 execute \u003Cdb> --remote --command 'PRAGMA table_info(\"user\")'`:\n\n```sql\nCREATE TABLE IF NOT EXISTS \"user\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"name\" text NOT NULL,\n  \"email\" text NOT NULL UNIQUE,   \"emailVerified\" integer NOT NULL,\n  \"image\" text, \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL\n);\nCREATE TABLE IF NOT EXISTS \"session\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"expiresAt\" date NOT NULL,\n  \"token\" text NOT NULL UNIQUE,   \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL,\n  \"ipAddress\" text, \"userAgent\" text,\n  \"userId\" text NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE\n);\nCREATE TABLE IF NOT EXISTS \"account\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"accountId\" text NOT NULL, \"providerId\" text NOT NULL,\n  \"userId\" text NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE,\n  \"accessToken\" text, \"refreshToken\" text, \"idToken\" text,\n  \"accessTokenExpiresAt\" date, \"refreshTokenExpiresAt\" date,\n  \"scope\" text, \"password\" text, \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL\n);\nCREATE TABLE IF NOT EXISTS \"verification\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"identifier\" text NOT NULL, \"value\" text NOT NULL,\n  \"expiresAt\" date NOT NULL, \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL\n);\nCREATE INDEX IF NOT EXISTS \"session_userId_idx\"          ON \"session\"      (\"userId\");\nCREATE INDEX IF NOT EXISTS \"account_userId_idx\"          ON \"account\"      (\"userId\");\nCREATE INDEX IF NOT EXISTS \"verification_identifier_idx\" ON \"verification\" (\"identifier\");\n```\n\n`ON DELETE CASCADE` on `session.userId`\u002F`account.userId` is what makes account\ndeletion actually delete — same reasoning as Trap 11, one level down.\n\n🛑 **Plugins ADD COLUMNS TO `user`, they do not only add tables.** The prod `user`\ntable has **8** columns against the 7 above: `twoFactor()` appends\n`twoFactorEnabled`. So a column-count assertion against this DDL will \"fail\" on a\ncorrect database once a plugin is enabled — count against the **installed plugin\nset**, not this snippet. That is also why the `ALTER TABLE \"user\" ADD COLUMN` in a\nplugin migration must go LAST (Trap 11): SQLite has no `ADD COLUMN IF NOT EXISTS`.\n\n### `trustedOriginsFor` — referenced everywhere, so here it is\n\n```ts\nexport function trustedOriginsFor(env: AuthEnv): string[] {\n  return [\n    \"https:\u002F\u002Fexample.com\",\n    \"https:\u002F\u002Fwww.example.com\",\n    \"capacitor:\u002F\u002Flocalhost\",          \u002F\u002F Capacitor webview — see below\n  ];\n}\n```\n\n**`trustedOrigins` and `PASSKEY_ORIGINS` are different lists and must stay\ndifferent.** `trustedOrigins` is better-auth's CSRF\u002Fredirect allowlist and legitimately\nincludes `capacitor:\u002F\u002Flocalhost`. `passkey({ origin })` is WebAuthn's `expectedOrigin`\nand must contain **only** secure HTTPS origins whose registrable domain matches\n`rpID` — putting `capacitor:\u002F\u002Flocalhost` there is a lie the browser rejects anyway,\nand it hides the real failure (Trap 9). Include `www.` in both.\n\n---\n\n## The working baseline\n\n```ts\nexport function createAuth(env: AuthEnv) {\n  if (!env.BETTER_AUTH_SECRET) throw new Error(\"BETTER_AUTH_SECRET not set\");\n  if (!env.DB) throw new Error(\"D1 binding DB is not configured\");\n\n  return betterAuth({\n    secret: env.BETTER_AUTH_SECRET,\n    baseURL: env.BETTER_AUTH_URL || \"https:\u002F\u002Fexample.com\",\n    basePath: \"\u002Fapi\u002Fauth\",\n    database: env.DB,            \u002F\u002F see Trap 2\n    telemetry: { enabled: false },\n    trustedOrigins: trustedOriginsFor(env),\n    advanced: { cookiePrefix: \"app\" },\n    plugins: [bearer(), \u002F* … *\u002F],\n  });\n}\n```\n\nMount in Hono — **both verbs**, the whole subtree:\n```ts\napp.on([\"GET\", \"POST\"], \"\u002Fapi\u002Fauth\u002F*\", async (c) => createAuth(c.env).handler(c.req.raw));\n```\n\nSecrets: `BETTER_AUTH_SECRET`, plus `GOOGLE_CLIENT_ID`\u002F`GOOGLE_CLIENT_SECRET`,\n`APPLE_CLIENT_ID`\u002F`APPLE_CLIENT_SECRET` per provider. `wrangler secret put` each —\nnever `vars`. **Obtaining them is the actual work — see the next section.**\n\n---\n\n## Provisioning the credentials (the part the docs skip)\n\nGetting these is most of the setup cost. Order matters; each step has a trap.\n\n### 0. `BETTER_AUTH_SECRET`\n```bash\nopenssl rand -base64 32 | wrangler secret put BETTER_AUTH_SECRET\n```\nNever echo it into the transcript. Verify shape only: `wrangler secret list` shows\n`secret_text`.\n\n### 1. Google — you need TWO clients, and only one has a secret\n\n| Client type | Used by | Has a secret? |\n|---|---|---|\n| **Web application** | browser redirect flow; this is `GOOGLE_CLIENT_ID` | yes → `GOOGLE_CLIENT_SECRET` |\n| **iOS** | native `GIDSignIn` in the Capacitor shell | **no** — public by design, ships in the bundle |\n\nConsole: `https:\u002F\u002Fconsole.cloud.google.com\u002Fapis\u002Fcredentials?authuser=1`\n(**`authuser=1` matters** — `authuser=0` can land on an MFA-enrollment gate.)\n\n**Creating the CLIENT is still browser-only** (no API — see the enumeration below). But the\n**consent screen** around it is now scriptable: `gauth-console` (in **`\u002Fgcli`**) drives it\nthrough the real logged-in Chrome. Prefer it over hand-clicking:\n\n```bash\ngauth-console status  \u003Cgcp-project>            # read-only: publish state + branding fields\ngauth-console set     \u003Cgcp-project> privacy|homepage|terms|contact \u003Cvalue>\ngauth-console publish \u003Cgcp-project> --confirm  # refuses unless genuinely ready\n```\nThis is the Google analogue of what `siwa` does for Apple. Note the asymmetry and do not\ngeneralise: Apple's Services ID + Return URLs remain genuinely browser-only, so\n`siwa portal` printing those two steps is still correct.\n\n- Web client → Authorized redirect URI `https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle`.\n- iOS client → bind to the bundle id + team id. Its **reversed** id is the\n  `CFBundleURLScheme` (Trap 3). Put both ids in one shared module so the shell-side\n  id and the server-side accepted audience (Trap 1) can never drift.\n\n**🛑 Google caps a client at TWO client secrets, and delete requires disable first.**\nThe trash icon is inert until the secret is disabled — that is a two-step UI, not a\nbroken button. So when rotating: confirm the stale secret is unused, **disable** it,\n**then** delete, then add the new one. Plan this before you hit the cap.\n\n**Never let a secret value into the transcript.** Pipe it:\n```bash\npbpaste | tr -d '\\n' | wrangler secret put GOOGLE_CLIENT_SECRET\n```\nVerify by shape, never by printing: `wrangler secret list | grep GOOGLE_CLIENT_SECRET`.\nIf you must confirm a value came through, use a boolean test (does string X appear:\ntrue\u002Ffalse) — **never return the surrounding text**, \"scrubbed\" or otherwise.\n\n### 2. Apple — a Services ID plus a JWT you mint yourself\n\n`APPLE_CLIENT_ID` is the **Services ID** (e.g. `com.improvebayarea.signin`), *not*\nthe app bundle id. `APPLE_APP_BUNDLE_ID` is separately needed for the native\naudience (Trap 1).\n\nRegister the return URL under the Services ID → *Sign in with Apple* → Configure:\n**the ⊕ button REGISTERS a new Website URL; the dropdown only LISTS what is already\nattached.** Editing the visible field and pressing Save is a silent no-op — this\nlooks exactly like a broken form. Add `https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fcallback\u002Fapple`, then\n**reload and re-read the list** to confirm it stuck.\n\n`APPLE_CLIENT_SECRET` is **not issued by Apple** — it is a self-signed **ES256 JWT**\nyou generate from a `.p8` Sign-in-with-Apple key, and Apple caps it at **6 months**.\nThe JWT signature must be raw 64-byte `r||s` (ieee-p1363), not DER — hand-rolling\nthat is where people lose an afternoon.\n\n**Drive the whole Apple side with `siwa`** (`~\u002Ftools\u002Fsiwa\u002Fsiwa`, on PATH), which\nwraps every step below. Add the site once to `~\u002F.config\u002Fsiwa\u002Fsites.json`\n(`host, services_id, team_id, key_id, p8, worker_repo, worker_name`), then:\n\n```bash\nsiwa portal   \u003Csite>   # prints the 2 web-only steps (Services ID + Return URL)\nsiwa domain-file \u003Csite> ~\u002FDownloads\u002Fapple-developer-domain-association.txt\nsiwa secret   \u003Csite>   # mint JWT -> both APPLE_* secrets -> deploy -> register expiry\nsiwa probe    \u003Csite>   # ask APPLE whether the credential chain is valid\nsiwa verify   \u003Csite>   # live: assoc file + Apple button + flow -> appleid.apple.com\nsiwa rotate   \u003Csite>   # the 6-month re-mint (same as secret + probe)\n```\n\n`siwa secret` shells out to the same `apple-client-secret.mjs` generator (one\nimplementation, one place to fix) and never prints the JWT — only its length and\nexpiry. **`betterauth` stays read-only and `siwa` owns the mutations**; that split\nis deliberate, so don't teach `betterauth` to write secrets.\n\n🛑 **`siwa probe` is the cheapest real proof the credential chain works, and its\nPASS is an ERROR string.** It POSTs a deliberately-bogus authorization code to\n`https:\u002F\u002Fappleid.apple.com\u002Fauth\u002Ftoken`:\n\n| Apple's `error` | Means |\n|---|---|\n| **`invalid_grant`** | ✅ Apple **accepted** the client secret and refused only the fake code — the `.p8` \u002F `key_id` \u002F `team_id` \u002F Services-ID chain is CORRECT |\n| `invalid_client` | ❌ Apple rejected the **credential** itself |\n\nSame shape as the APNs `BadDeviceToken` trick: make the credential the only thing\nunder test. No browser, no sign-in, no side effect — so it is free to run often.\n\n⚠️ **The Worker's auth gate will break Apple's domain verification if you let it.**\nApple fetches `\u002F.well-known\u002Fapple-developer-domain-association.txt`\n**unauthenticated**. A session gate that allows only `\u002Flogin` and `\u002Fapi\u002Fauth\u002F*`\nredirects that path to `\u002Flogin`, and Apple reads the 302 as a failure with nothing\nin your logs explaining why. Allow the directory through explicitly:\n\n```ts\nif (path.startsWith('\u002F.well-known\u002F')) return next();   \u002F\u002F BEFORE the session check\n```\nProof it worked, on imessage-bridge: that path went **302 → 404** after the fix\n(404 = reaching the asset layer, file not installed yet). Same allowance covers\n`security.txt` and ACME challenges. Safe to expose — the directory only ever holds\nvalues that are public by design.\n\n⚠️ **A SIWA `.p8` is a TEAM-level key.** One key signs JWTs for *any* Services ID\nin that team, so an existing key (e.g. `~\u002F.asc\u002Fkeys\u002FAuthKey_Z5JJTW7C94-siwa-improvebayarea.p8`,\nteam `2KJ8W6N44B`) is reusable for a new site — a new Apple Developer account or key\nis NOT required. The Services ID goes in the JWT's `sub`; the key only signs.\n\n### 3. Register every expiring secret for rotation — MANDATORY\n\nApple gives **no warning** and the failure is opaque: sign-in simply stops, site-wide\n*and* in the app. Add an entry to `~\u002Ftools\u002Fsecret-expiry\u002Fsecrets.json` with `name`,\n`expires`, `owner`, `impact`, and a copy-pasteable `renew` command, then **scp it to\nthe mac-mini** — the mini is the cron host, so an entry only on the laptop never\nalerts. Both sites are already registered; copy an existing entry's shape.\n\nDerive `expires` from the **earlier** plausible mint date, so the alert fires early\nrather than late.\n\n### 4. Decommission the old provider — no half-configs\n\nAfter cutover, delete the old secret (`wrangler secret delete CLERK_SECRET_KEY`),\nstrip its hosts from the CSP, remove the packages, and drop the DNS record. Audit\nwith `wrangler secret list` — a leftover key is both a live credential and a lie\nabout which system is in charge.\n\n> **Verified 2026-08-05: both sites are now clean.** `CLERK_SECRET_KEY` deleted from\n> both Workers (`wrangler secret list` shows it absent while `BETTER_AUTH_SECRET`\n> remains — always assert the control, or you cannot tell \"deleted\" from \"list\n> broke\"). All 10 dangling DNS records removed across both zones; `dig @1.1.1.1`\n> returns NXDOMAIN for `clerk`, `accounts`, `clkmail`, `clk._domainkey`,\n> `clk2._domainkey` on each.\n>\n> **Two lessons worth more than the result:**\n>\n> 1. **A source grep is the WRONG instrument for decommissioning.** Both codebases\n>    had zero `@clerk\u002F*` packages and zero `env.CLERK_*` reads — a grep said \"clean\"\n>    while a live credential was still bound to production and 10 CNAMEs still\n>    pointed into a deleted third-party tenant (a textbook subdomain-takeover\n>    setup). The binding and the zone are the ground truth; the imports are not.\n>    Audit with `wrangler secret list` and `dig`, not `grep`.\n> 2. **Check the DKIM\u002Fmail records too, not just the auth hosts.** The obvious two\n>    are `clerk` and `accounts`; the easy misses are `clkmail` + the two\n>    `clk*._domainkey` CNAMEs. Before deleting them, confirm the domain's SPF does\n>    not reference the vendor and that the real senders' selectors still resolve —\n>    then removing them breaks no mail.\n\n---\n\n## Trap 0 — Interpret Google audience restrictions using the actual scopes\n\n**Corrected 2026-09-09 against Google's current primary documentation.** Testing normally\nrestricts authorization to up to 100 listed test users, with seven-day authorization expiry.\nHowever, requests limited to `openid`, email, and profile (including Sign in with Google)\nare exempt from the test-user-list, warning, and seven-day-expiry behavior. Any additional\nscope removes that exception. The lifetime cap for unapproved sensitive\u002Frestricted scopes\nis a separate rule. Never claim a login-only site cannot sign in its 101st user from the\nTesting label alone; inspect the actual outgoing scopes.\n\nSource: https:\u002F\u002Fsupport.google.com\u002Fcloud\u002Fanswer\u002F15549945?hl=en (fetched 2026-09-09).\nProvider status is still separate from secrets\u002Fschema\u002Froute health; a green local check\ndoes not establish the console policy or end-to-end sign-in.\n\n```bash\ngauth-console status \u003Cgcp-project>     # read-only; prints publish state + what is blocking it\n```\n\n**The publish gate is NOT what the form's `required` flags say.** On\n`console.cloud.google.com\u002Fauth\u002Fbranding` the fields render:\n\n| Field | form says | actually gates publish? |\n|---|---|---|\n| App name | `required=true` | yes |\n| Authorized domain | `required=true` | yes |\n| Email addresses (dev contact) | `required=true` | yes |\n| **Application home page** | `required=false` | **YES** |\n| **Application privacy policy** | `required=false` | **YES** |\n| Application terms of service | `required=false` | no |\n\nThose `required=false` flags are *Testing-mode* validation. \"Publish app\" on `\u002Fauth\u002Faudience`\nstays `aria-disabled=\"true\"` until home page **and** privacy policy are also set — proven by\nelimination (contact email → still blocked; + home page → still blocked; + privacy → ready).\nSo **shipping a privacy policy page is an auth dependency, not a legal nicety.**\n\nTwo reading traps if you check this by hand instead of with `gauth-console`: the button\nreports `disabled === false` while visually greyed (read `aria-disabled`), and the form's\ninputs live in **shadow DOM**, so `document.querySelectorAll('input')` returns `[]` and a\nnaive probe concludes the fields do not exist. Full trap list: **`\u002Fgcli`**.\n\n## Trap 1 — Native iOS social sign-in: the id token audience is NOT your web client\n\n**The single most expensive trap. It has bitten Apple and Google separately.**\n\nGoogle\u002FApple mint an id token whose `aud` is **whichever client asked for it**. The\nbrowser flow asks as your *web* client; a native iOS sheet asks as the *iOS* client\n(Google) or the *bundle id* (Apple). Better Auth's default verifiers check\n`aud === options.clientId` and nothing else, so a **fully successful** OAuth\nround-trip is then rejected by your own server.\n\nThe symptom is maximally misleading: the user completes the Google sheet, Google\nemails *\"You shared some Google Account data with \u003Capp>\"*, and the app shows\n**\"Could not sign in with Google. Invalid token.\"**\n\n🛑 **Corrected 2026-08-05 — the earlier advice here was wrong, and it shipped\nthe bug to production.** This skill used to say Apple had a \"first-class option\"\n(`appBundleIdentifier`) while Google did not. Reading the installed source,\n`@better-auth\u002Fcore\u002Fdist\u002Fsocial-providers\u002Fapple.mjs:63`:\n\n```js\naudience: options.audience?.length ? options.audience\n        : options.appBundleIdentifier ? options.appBundleIdentifier\n        : options.clientId,\n```\n\n`appBundleIdentifier` **REPLACES** the audience — it does not add one. Setting it\nmakes the bundle id the *only* valid audience and silently drops the web Services\nID. The `audience` **ARRAY** takes precedence over both and is the only form that\naccepts each. So Apple and Google get the **same** shape, not different ones:\n\n```ts\napple: {\n  clientId: env.APPLE_CLIENT_ID as string,\n  clientSecret: env.APPLE_CLIENT_SECRET as string,\n  audience: [env.APPLE_CLIENT_ID as string, APPLE_APP_BUNDLE_ID], \u002F\u002F ← BOTH\n},\ngoogle: {\n  clientId: env.GOOGLE_CLIENT_ID as string,\n  clientSecret: env.GOOGLE_CLIENT_SECRET as string,\n  async verifyIdToken(token: string, nonce?: string) {\n    const claims = await verifyGoogleIdToken({\n      token,\n      audience: [env.GOOGLE_CLIENT_ID as string, GOOGLE_IOS_CLIENT_ID], \u002F\u002F jose takes an array\n      nonce,\n    });\n    return Boolean(claims);\n  },\n},\n```\n`import { verifyGoogleIdToken } from \"better-auth\u002Fsocial-providers\"`.\n\n**Two failure modes this exact trap produced on improvebayarea (fixed `e4a486f`):**\n\n1. **An OPTIONAL env var made a REQUIRED audience vanish.** The provider spread\n   `appBundleIdentifier` conditionally on `env.APPLE_APP_BUNDLE_ID` — a var never\n   set on the Worker. The spread no-opped, the comment above it described a\n   configuration that did not exist, and every native Apple sign-in was rejected.\n   **A bundle id is public and must always be present, so it belongs in a\n   constant, not a secret.** `wrangler secret list` is what proves an env-gated\n   config is actually live; the source alone cannot.\n2. **Apple can be LIVE-broken while Google is only latent.** Capability gating is\n   per-provider: on IBA `nativeSocialAvailable('google')` checks a shell UA token,\n   but `nativeSocialAvailable('apple')` is just `Boolean(AUTH_SOCIAL.apple)`\n   (`src\u002Fui.ts:1919`) — so Apple takes the native id-token path in *every* in-app\n   webview, unconditionally. **Check each provider's gate separately; do not\n   assume the one you audited represents the others.**\n\n**This is not a weakening.** It calls Better Auth's own verifier — JWKS signature,\nissuer, expiry, 1h max age and nonce all still enforced. Only the audience\nallowlist widens, to *your own* second client. That is Google's documented pattern\nfor a backend serving several platforms. Assert the set is exactly your clients so\na wildcard can never creep in.\n\n**Do NOT \"fix\" it with the plugin's `iOSServerClientId`.** That maps to GIDSignIn's\n`serverClientID`, which the SDK sends as the OAuth **`audience` request parameter**\n(`GIDSignIn.m:896`) to obtain a `serverAuthCode`; whether it also rewrites the id\ntoken's `aud` is undocumented — the plugin's own docs tie the field to offline mode.\nAccepting both audiences is correct regardless, which is why it is the right fix.\n\n**Probe (proves the deployed verifier, costs nothing — a failed sign-in has no side effect):**\n```bash\nHDR=$(printf '{\"alg\":\"RS256\",\"kid\":\"k\"}' | base64 | tr '+\u002F' '-_' | tr -d '=')\nPAY=$(printf '{\"aud\":\"PROBE.apps.googleusercontent.com\",\"iss\":\"https:\u002F\u002Faccounts.google.com\",\"exp\":%d}' $(($(date +%s)+600)) | base64 | tr '+\u002F' '-_' | tr -d '=')\ncurl -s -X POST https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fsign-in\u002Fsocial -H 'Content-Type: application\u002Fjson' \\\n  -d \"{\\\"provider\\\":\\\"google\\\",\\\"idToken\\\":{\\\"token\\\":\\\"$HDR.$PAY.sig\\\"}}\"\n```\nExpect 401. Then read `wrangler tail` for the discriminator (Trap 6).\n\n---\n\n## Trap 2 — Instantiate PER REQUEST; hand D1 in raw\n\n`env.DB` is scoped to one invocation. A module-level singleton captures the first\nrequest's binding and silently breaks on every later one. `createAuth(env)` does no\nI\u002FO, so per-request is cheap.\n\nPass the binding **directly** as `database: env.DB` — `@better-auth\u002Fkysely-adapter`\ndetects the `batch\u002Fexec\u002Fprepare` surface and wraps it in its own `D1SqliteDialect`\n(`@better-auth\u002Fkysely-adapter\u002Fdist\u002Findex.mjs:67-69`). No dialect construction needed.\n\n---\n\n## Trap 3 — Capacitor: no URL scheme means the app CRASHES, not \"fails\"\n\nNative Google requires the reversed client id in `Info.plist`:\n```xml\n\u003Ckey>CFBundleURLTypes\u003C\u002Fkey>\n\u003Carray>\u003Cdict>\n  \u003Ckey>CFBundleURLSchemes\u003C\u002Fkey>\n  \u003Carray>\u003Cstring>com.googleusercontent.apps.NNNN-xxxx\u003C\u002Fstring>\u003C\u002Farray>\n\u003C\u002Fdict>\u003C\u002Farray>\n```\nWithout it GoogleSignIn raises **`NSInvalidArgumentException`** (`GIDSignIn.m:733`)\n— an uncaught ObjC exception that kills the app. There is no alternative path and\nno graceful degradation: enabling the button in a build lacking the scheme crashes\nevery install that taps it.\n\nThe scheme is **compiled in**, so this always needs a new TestFlight build.\n\n⚠️ `mobile\u002Fios\u002FApp\u002FApp\u002Fcapacitor.config.json` is **gitignored** and regenerated by\n`npx cap sync ios`. Archiving without syncing produces a binary missing whatever you\njust added to `capacitor.config.ts` — with no error anywhere. Verify in the archive:\n```bash\n\u002Fusr\u002Flibexec\u002FPlistBuddy -c \"Print :CFBundleURLTypes:0:CFBundleURLSchemes:0\" \u003CApp>.app\u002FInfo.plist\ngrep -o '\"appendUserAgent\"[^,]*' \u003CApp>.app\u002Fcapacitor.config.json\n```\n\n---\n\n## Trap 4 — Remote-URL wrap: capability tokens, never a boolean flag\n\nWhen `server.url` points at the live site, **the web layer is served to every\ninstall at once, old and new.** A site-side `const NATIVE_READY = true` therefore\nswitches the feature on inside already-installed builds that lack the native\ncapability — the exact dead-end (or crash) the flag was meant to prevent.\n\nInvert it: the **shell declares** what it can do, the site reacts.\n```ts\n\u002F\u002F capacitor.config.ts — add ONLY in the commit that adds the capability to the binary\nappendUserAgent: \"MyApp nativeGoogleAuth\u002F1\",\n```\n```js\nfunction shellDeclaresNativeGoogle() {\n  try { return (navigator.userAgent || '').includes('nativeGoogleAuth\u002F1'); }\n  catch (e) { return false; }\n}\n```\nA build without the capability never emits the token, so a stale install cannot opt\nin. No version arithmetic, no deploy ordering. Safari lacks it too — correct, since\nbrowsers use the web flow.\n\nProve the token actually reaches the page (server-side is ground truth):\n```bash\nwrangler tail --format json   # then load the app; read event.request.headers['user-agent']\n```\n\n---\n\n## Trap 5 — A JS gate is not enough: CSS can override it\n\nSites that hide social buttons inside webviews often do it in **CSS**:\n```css\nhtml[data-native-shell] #btn-social-google { display: none !important; }\n```\nThat beats any JS capability check. On improvebayarea the JS gate returned `true`,\nevery condition passed, and the button still did not render — `display:none\n!important` won, and a test asserted the unconditional rule, locking the bug in.\n\nFix by excluding capable shells at the selector level and setting the attribute only\nwhen the capability is real:\n```css\nhtml[data-native-shell]:not([data-native-google]) #btn-social-google { display: none !important; }\n```\n**Never conclude a social button works from source review.** Run it and look.\n\n---\n\n## Trap 6 — \"Invalid token\" is one string for many causes: ship a discriminator\n\nBetter Auth collapses audience mismatch, bad signature, and expiry into one\n`{\"message\":\"Invalid token\",\"code\":\"INVALID_TOKEN\"}`. Every single-cause fix then\nlooks byte-identical to no fix — Pattern #32.\n\nLog the measurable properties on the rejection path. **Non-PII only** — an id token\nis full of user data:\n```ts\nif (!claims) {\n  let aud = \"\u003Cunparseable>\", iss = \"\u003Cunparseable>\";\n  let expired: boolean | \"unknown\" = \"unknown\";\n  try {\n    const j = JSON.parse(atob((token.split(\".\")[1] ?? \"\").replace(\u002F-\u002Fg,\"+\").replace(\u002F_\u002Fg,\"\u002F\")));\n    if (typeof j.aud === \"string\") aud = j.aud;\n    if (typeof j.iss === \"string\") iss = j.iss;\n    if (typeof j.exp === \"number\") expired = j.exp * 1000 \u003C Date.now();\n  } catch { \u002F* placeholders ARE the signal *\u002F }\n  console.warn(JSON.stringify({ event: \"google_id_token_rejected\", aud, iss, expired,\n    audAccepted: [webId, iosId].includes(aud), nonceSupplied: Boolean(nonce), tokenLen: token.length }));\n}\n```\nLog `aud`\u002F`iss`\u002F`exp` — never `sub`, `email`, `name`, or the token. The unverified\ndecode is for logging only; trust still comes solely from the verifier above it.\n\n---\n\n## Trap 7 — Migrating off Clerk: preserve the user ids\n\nApp data is FK'd to the old provider's user id. Import users with\n`id = \u003Cold provider id>` via direct D1 inserts — **zero FK re-keying**, and social\naccounts relink on first sign-in because the OAuth apps (and therefore `sub`) are\nunchanged. Set `account.accountLinking.trustedProviders` for providers that verify\nthe email, or the true owner hits `account_not_linked`.\n\nPassword hashes are **dashboard-export only** (the Backend API never exposes\n`password_digest`), and Clerk's `password_hasher` is an enum of ~15 algorithms, not\njust bcrypt. Import a credential row **only** for hashes you can actually verify;\nfor anything else send a reset email rather than writing a credential that can never\nmatch — that failure surfaces as a generic \"invalid password\" with nothing in the logs.\n\n**A provider migration silently drops credential types while leaving their\ninfrastructure standing.** On IBA the Clerk-era AASA + Associated-Domains\nentitlement for passkeys (`dadfdf3`) survived the cutover; the *credentials* did\nnot — `2ba98c0` carried `bearer`\u002F`magicLink`\u002F`emailOTP` and nothing else. The\nhonest short-term fix then *hid* the gap: `b96dd0f` rewrote the privacy page to\nstop claiming passkeys, which was correct (never overclaim) but left a product\nregression looking like a settled decision. **After any auth migration, diff the\nOLD provider's enabled credential types against your new `plugins:` array** — the\ndashboard's feature list, not your memory of it.\n\n---\n\n## Trap 8 — `twoFactor()` defaults to demanding a password almost nobody has\n\n`\u002Ftwo-factor\u002Fenable` calls `shouldRequirePassword`\n(`node_modules\u002Fbetter-auth\u002Fdist\u002Futils\u002Fpassword.mjs`) and, by default, **refuses to\nenrol an account that cannot supply its password**. On a deployment where accounts\narrive by Clerk import (`password_enabled=false`), social, magic link, email OTP,\nor passkey — i.e. essentially all of them — 2FA is rendered **visible in the UI and\npermanently unreachable**. Nothing errors at deploy time; the button simply never\nworks, for everyone.\n\n```ts\ntwoFactor({\n  issuer: APP_DISPLAY_NAME,\n  allowPasswordless: true,   \u002F\u002F ← load-bearing, not a convenience\n}),\n```\n\n**This is not a weakening.** The flag's other branch still demands the password\nwhenever a credential account *has* one — it relaxes the check only where there is\nnothing to check. Assert both halves, or a future default-flip silently becomes an\naccount-takeover:\n\n```\nenrol with NO password        → 200, secret written\nenrol with a WRONG password   → 400, nothing written   ← the half that matters\nanonymous caller              → 401\n```\n\nAlso assert, against a real instance: the stored secret does **not** contain the\nplaintext handed to the app (D1 is a separate blast radius from the Worker), and\nminting a secret does **not** flip `twoFactorEnabled` (a mistyped setup must not\nlock the user out of their own password sign-in).\n\n---\n\n## Trap 9 — `passkey({ origin })` left unset is attacker-controlled\n\nOmit `origin` and the plugin falls back to the request's own `Origin` header — and\nthat value is handed straight to the verifier as `expectedOrigin`. Verified in the\ninstalled source (`@better-auth\u002Fpasskey\u002Fdist\u002Findex.mjs`, 1.6.26):\n\n```js\n321:  const origin = options?.origin || ctx.headers?.get(\"origin\") || \"\";   \u002F\u002F register\n337:        expectedOrigin: origin,\n414:  const origin = options?.origin || ctx.headers?.get(\"origin\") || \"\";   \u002F\u002F authenticate\n436:      expectedOrigin: origin,\n```\n\nSo the check becomes \"does the origin match the origin the caller sent\" — which is\nnot a check. Pin it to a literal allowlist:\n\n```ts\nexport const PASSKEY_RP_ID  = \"improvebayarea.com\";\nexport const PASSKEY_ORIGINS = [\n  \"https:\u002F\u002Fimprovebayarea.com\",\n  \"https:\u002F\u002Fwww.improvebayarea.com\",   \u002F\u002F registrable suffix matches the RP id\n] as const;\n\npasskey({ rpID: PASSKEY_RP_ID, rpName: APP_DISPLAY_NAME, origin: [...PASSKEY_ORIGINS] }),\n```\n\n**Passkey origins are NOT `trustedOrigins`, and the difference is load-bearing.**\nWebAuthn requires a secure HTTPS origin whose registrable domain matches `rpID`.\n`capacitor:\u002F\u002Flocalhost` belongs in `trustedOrigins` and must **never** appear here\n— the browser rejects it anyway, so listing it only hides the real failure. Omitting\n`www.` is the opposite mistake: a passkey registered there fails verification with an\nopaque 400.\n\nProbe the deployed config for free — a failed ceremony has no side effect:\n```bash\ncurl -s -o \u002Fdev\u002Fnull -w '%{http_code}\\n' \\\n  https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fpasskey\u002Fgenerate-register-options\n# 404 = plugin NOT loaded · 401 = loaded, demanding auth (correct)\n```\nThat **404 → 401 transition is the cheapest proof a plugin actually shipped** — far\nbetter than reading the diff. Capture the 404 *before* deploying so you have a\nbefore\u002Fafter, and re-check after >30s (Worker propagation false-negatives an\nimmediate curl).\n\n🛑 **The probe's HTTP method is PER-ROUTE — a GET-only sweep reports working plugins\nas missing.** Corrected 2026-08-05 after this exact false negative: `GET\n\u002Ftwo-factor\u002Fenable` returns **404**, `POST` returns **401**. Three live plugins on IBA\nread as \"not loaded\" under a GET-only probe. Use the method the route actually\ndeclares (`betterauth health` encodes the per-route table), and treat a 404 from the\nwrong verb as *no information*, not evidence of absence.\n\n---\n\n## Trap 10 — Enabling 2FA makes a CORRECT password look like a broken session\n\nOnce 2FA is on, `\u002Fsign-in\u002Femail` answers **200 with no session** and a\n`twoFactorRedirect` payload; better-auth deletes the half-made session\n(`...\u002Fplugins\u002Ftwo-factor\u002Findex.mjs:266`). Client code that infers \"signed in\" from\n`res.ok` therefore tells a user who typed the **right** password that the session\ndid not stick — an opaque failure on the happy path. Handle `twoFactorRedirect`\nexplicitly, and surface backup codes from the challenge itself, since that is the\nonly screen a locked-out user can still reach.\n\n**Scope it honestly in product copy.** better-auth challenges **only**\n`\u002Fsign-in\u002Femail` (`...\u002Ftwo-factor\u002Findex.mjs:222`). Magic link, email code, Apple,\nGoogle and passkey sign-in are **not** second-factored. Say the code guards *the\npassword*, not *the account* — and lock the phrasing with a test so a later\ncopy-edit cannot widen the claim.\n\n---\n\n## Trap 11 — Plugin tables: transcribe the DDL from installed source, and CASCADE\n\nA plugin's storage is your migration to write. Getting a column wrong does **not**\nfail loudly: the adapter throws inside the handler, better-auth returns a generic\n500, and `no such column` appears only in `wrangler tail` under `logs[]` — never\n`exceptions[]`. Transcribe from the **installed** package (Trap: the two sites are on\ndifferent versions):\n\n| Table | Source of truth |\n|---|---|\n| `passkey` | `node_modules\u002F@better-auth\u002Fpasskey\u002Fdist\u002Findex.mjs` (`#region src\u002Fschema.ts`) |\n| `twoFactor` | `node_modules\u002Fbetter-auth\u002Fdist\u002Fplugins\u002Ftwo-factor\u002Fschema.mjs` |\n| `user.twoFactorEnabled` | same twoFactor schema, `user.fields` block |\n\nType mapping (established empirically against better-auth driving SQLite):\n`string`→`text`, `number`→`integer`, `boolean`→`integer` (0\u002F1, **never** a boolean\nliteral), `date`→`date` (ISO-8601 TEXT at rest).\n\n**`ON DELETE CASCADE` is required, not decorative.** `internalAdapter.deleteUser`\n(`better-auth\u002Fdist\u002Fdb\u002Finternal-adapter.mjs:164-175`) deletes only session\u002Faccount\u002F\nuser rows and knows nothing about plugin tables. Without it, \"delete my account\"\nleaves a live `credentialID` behind — breaking the erasure your privacy page\npromises, and 500ing `\u002Fpasskey\u002Fverify-authentication` when it matches a row whose\nowner is gone.\n\n**Put the one non-idempotent statement LAST.** SQLite has no\n`ADD COLUMN IF NOT EXISTS`, so `ALTER TABLE \"user\" ADD COLUMN \"twoFactorEnabled\"`\naborts the batch on a re-run (`duplicate column name` — harmless, but it stops\neverything after it). Everything above it is `IF NOT EXISTS`, so a first run has\nalready created every table and index before this can fail.\n\n**Tests must read `migrations\u002F` — never a hand-copied `CREATE TABLE`.** A second\nsource of truth in the test file had already drifted a column on IBA, which is how\nthis change first surfaced as `table user has no column named twoFactorEnabled`.\n\n---\n\n## Trap 12 — \"single-tenant\" is a comment, not a control: `enabled: true` ships an OPEN SIGNUP route, and authenticating is not authorizing\n\n**Found 2026-08-30 building `agentprofile`. It was a HIGH-severity unauthenticated\nfull-owner compromise, and the code carried a comment asserting the opposite.**\n\nTwo independent halves. Either one alone is the whole vulnerability.\n\n**Half 1 — `emailAndPassword: { enabled: true }` publishes `POST \u002Fsign-up\u002Femail`.**\nThe only gate in the installed package is:\n\n```js\n\u002F\u002F node_modules\u002Fbetter-auth\u002Fdist\u002Fapi\u002Froutes\u002Fsign-up.mjs\nif (!ctx.context.options.emailAndPassword?.enabled ||\n    ctx.context.options.emailAndPassword?.disableSignUp) throw APIError.from(\"BAD_REQUEST\", ...)\n```\n\nSo `enabled: true` without `disableSignUp: true` is a live, public account-creation\nendpoint. And it hands back a usable session immediately — `createSession` then\n`setSessionCookie` then a body containing `token` — because `autoSignIn` defaults on and\n`requireEmailVerification` is unset. With the `bearer()` plugin that token also works as\nan `Authorization` header.\n\n**`trustedOrigins` does NOT save you.** The CSRF middleware short-circuits:\n`if (headers.has(\"cookie\")) return await validateOrigin(ctx)` — a plain `curl` sends no\ncookie — and it then only validates when a `Sec-Fetch-*`, `origin`, or `referer` header is\npresent. A bare `curl` supplies none of those, so the function returns having validated\nnothing and `trustedOrigins` is never consulted.\n\n**Half 2 — a middleware that only checks `session !== null` authenticates without\nauthorizing.** This shape is the bug:\n\n```ts\nconst session = await createAuth(c.env).api.getSession({ headers: c.req.raw.headers });\nif (session === null) return jsonError(401, ...);\nc.set('owner', { userId: session.user.id });   \u002F\u002F \u003C-- ANY valid session is now \"the owner\"\n```\n\nThere is no comparison against a designated owner. On a single-tenant app that means the\n*second* account created — by anyone — has full owner authority: read every stored record,\nmint API tokens with every scope, and **approve its own pending approvals**, which defeats\nany human-in-the-loop gate you built on top of it.\n\n### The probe (three greps, ~20 seconds)\n\n```bash\ngrep -rn 'disableSignUp' src\u002F                      # ZERO hits + enabled:true  => signup is LIVE\ngrep -rn 'session\\.user\\.id' src\u002F                  # only an assignment, no comparison => no owner\ngrep -rniE 'owner_?user_?id|ownerUserId' src\u002F wrangler.jsonc   # ZERO => no owner is configured\n```\n\n### The fix — apply BOTH\n\n```ts\nemailAndPassword: { enabled: true, disableSignUp: true },\n```\nthen seed the owner out of band (a one-shot CLI insert of `user` + `account` with a hashed\npassword), **and** make the middleware authorize:\n```ts\nif (session === null || session.user.id !== c.get('config').ownerUserId) {\n  return jsonError(401, 'unauthenticated', 'Owner session required.');\n}\n```\nAlso narrow the mount — `app.on([...], `${AUTH_BASE_PATH}\u002F*`, ...)` republishes every route\nany future plugin adds. Allowlist `\u002Fsign-in\u002Femail`, `\u002Fsign-out`, `\u002Fget-session`.\n\n### Arm the tests by deleting the guard\n\n`POST \u002Fapi\u002Fauth\u002Fsign-up\u002Femail` must return 4xx — delete `disableSignUp` and it must go red.\nA session for a non-owner id must be rejected on every protected route — delete the\n`ownerUserId` comparison and it must go red.\n\n### The meta-lesson\n\nThe source comment said *\"Single-tenant by construction … There is no public signup route to\nleave open,\"* the README said *\"There is no signup route and no second user. That is the\nproduct, not a gap,\"* and the middleware docblock called itself *\"the one place where 'is\nthis the owner' is decided.\"* All three were false, and each **read as verification while\nverifying nothing**. A comment asserting an invariant is not an invariant. If a property\nmatters, there is a test that fails when it stops holding — otherwise it is a wish.\n\n## Passkeys in a Capacitor shell: usually NO new build (contrast Traps 3–4)\n\nNative *social* needs a compiled-in URL scheme, so it always needs a new archive.\nPasskeys usually do **not** — and the distinction is the shell's `server.url`:\n\n- **Remote-URL wrap** (`server.url: \"https:\u002F\u002F\u003Csite>\"`): the webview's WebAuthn origin\n  *is* the real HTTPS origin, so the whole ceremony is site-side and reaches\n  installed binaries on a Worker deploy.\n- The only native prerequisite is the **Associated Domains entitlement**\n  (`webcredentials:\u003Cdomain>`) plus the AASA file. Both are **relying-party based**, so\n  they survive an auth-provider migration untouched — Clerk-era bindings work for\n  Better Auth with no change.\n\nVerify the binding before debugging any JS ceremony (30 seconds, catches the\n\"registration was cancelled or timed out\" class):\n```bash\ncurl -s https:\u002F\u002F\u003Csite>\u002F.well-known\u002Fapple-app-site-association | python3 -m json.tool | grep -A3 webcredentials\ngrep -A3 associated-domains mobile\u002Fios\u002FApp\u002FApp\u002FApp.entitlements\n```\n**These are THREE different things — name which you verified.** Entitlement present in\nthe repo ≠ present in the *signed* build ≠ the capability enabled on the bundle id.\n\n🛑 **The portal capability IS API-checkable — do not claim it is browser-only.**\nCorrected 2026-08-05; the earlier version of this skill said it could not be verified\nwithout an archive, and that was wrong:\n```bash\nasc capabilities --bundle-id com.\u003Capp>   # ASSOCIATED_DOMAINS \u002F APPLE_ID_AUTH, ~2s\n```\nVerified live: both `com.improvebayarea.app` and `com.example.app` report\n`ASSOCIATED_DOMAINS` + `APPLE_ID_AUTH` enabled. What genuinely has **no** API is the\nServices ID's **Return URLs** (Sign in with Apple config) and Google's OAuth **client\nsecrets** — those two, and only those, need the browser recipes in `betterauth portal`.\n\n---\n\n## `betterauth` — the enforcement layer for everything below\n\nThis skill explains *why*; **`~\u002Ftools\u002Fbetterauth\u002Fbetterauth` checks it mechanically.**\nRead-only by design (it reports, you fix — it never mutates a secret or a schema).\nRun it before trusting any claim in the \"Current state\" table, which is a cache.\n\n```bash\nbetterauth all                # every check, human-readable\nbetterauth all --json         # for scripts\u002Fcron\nbetterauth drift              # installed version per site vs npm latest + CROSS-SITE skew\nbetterauth secrets            # required\u002Fmissing, stale (CLERK_*), expiry via secret-expiry\nbetterauth schema             # remote D1 PRAGMA vs the INSTALLED plugin schemas\nbetterauth health             # \u002Fapi\u002Fauth\u002Fok + per-plugin route probe (correct verb per route)\nbetterauth portal             # Apple capabilities via asc API + the 2 genuinely-no-API recipes\nbetterauth consent            # Google audience\u002Fpublish state; interpret with requested scopes\nbetterauth security --repo \"$PWD\" --json  # required full behavior + mutation gate before every ship\n```\n\n**Two CLIs, one boundary — do not blur it.** `betterauth` DIAGNOSES (read-only:\nno `secret put`, no D1 writes, no deploy); **`siwa` REMEDIATES the Apple half**\n(mints the JWT, sets `APPLE_*`, deploys, rotates). So `betterauth secrets` telling\nyou `APPLE_CLIENT_SECRET` is missing or expiring is answered by `siwa secret \u003Csite>`\n\u002F `siwa rotate \u003Csite>` — that is the intended hand-off, and it is why `betterauth`\nmust never grow a write path.\n\n| Question | Tool |\n|---|---|\n| Is Apple configured \u002F expiring \u002F drifted? | `betterauth secrets` · `betterauth portal` |\n| Do the audience and requested scopes permit intended users? | `betterauth consent` plus actual OAuth scopes (Trap 0) |\n| Is the *credential chain* actually valid to Apple? | **`siwa probe \u003Csite>`** (`invalid_grant` = PASS) |\n| Make it work \u002F rotate it | **`siwa secret`** · **`siwa rotate`** |\n| Is it live end-to-end right now? | **`siwa verify \u003Csite>`** (or `betterauth health` for all routes) |\n\n⚠️ **Sign-in-with-Apple has NO API for the Services ID or its Return URLs — this is\nmeasured, not assumed.** `asc capabilities` (App Store Connect CLI, 24 modelled\ncapabilities over a 1263-endpoint schema index) has **no entry** for either; the only\nDeveloper-Portal capability it reaches via web session is `PRIVATE_CLOUD_COMPUTE`,\nand `bundleIdCapabilities` is the only API-backed signing surface. Probing the\nplausible internal endpoints with an owner token also fails:\n`oauthconfig.googleapis.com\u002Fv1\u002Fprojects\u002F\u003Cp>\u002Fclients` → **404**,\n`clientauthconfig.googleapis.com\u002F...` → **404**, `iap.googleapis.com` brands → 403.\n\n🛑 **That 403 proves NOTHING and must not be cited as evidence (corrected 2026-08-31).**\nA 403 from a `*.googleapis.com` endpoint is almost always `SERVICE_DISABLED` — \"this API\nis not enabled on your project\" — which is a *project-config* state, not a statement about\nwhether the endpoint exists. Reading it as absence cost a wrong diagnosis on 2026-08-31.\nThree probes are a **sample** anyway; the claim needs the denominator:\n\n**ENUMERATED, not sampled** — the full Google discovery corpus (528 items,\n`https:\u002F\u002Fwww.googleapis.com\u002Fdiscovery\u002Fv1\u002Fapis`) contains **no** `clientauthconfig`, **no**\n`oauthconfig`, **no** `consentscreen`. `oauth2 v2` exists but has exactly three methods\n(`tokeninfo`, `userinfo`, `userinfo\u002Fv2\u002Fme`) — it CONSUMES tokens and cannot create clients.\nThe only client-admin API Google ever shipped was the IAP OAuth Admin API, and `gcloud`'s\nown `--help` says it was **permanently shut down 2026-03-19** (\"New projects will not be\nable to use these APIs\"). Terraform `google_iap_brand`\u002F`google_iap_client` wrap that same\ndead API. Google's migration doc states it verbatim: *\"If your application requires a custom\nClient ID for branding or external access, use the Google Cloud console to create the Client\nID.\"* — https:\u002F\u002Fdocs.cloud.google.com\u002Fiap\u002Fdocs\u002Fdeprecations\u002Fmigrate-oauth-client\nSee **`\u002Fgcli`** for the enumeration command and the rest of the Google-side tooling. So a\n\"fully automated Apple setup\" is not buildable — `siwa portal` printing the two\nbrowser steps IS the correct design, not a shortcoming. Don't try to generate an\nAPI-wrapper CLI for it (the CLI-printing-press route dead-ends here for exactly\nthis reason).\n\n**Exit codes are the contract**: `0` clean · `1` finding · `2` usage · **`3` could not\ndetermine**. 3 is the important one — a check that could not run must never read as\nclean. Config lives in `sites.json`; a third site is one entry, not a code change.\n\nWeekly Hermes cron on the mac-mini (`4e8f2ca8fbca`, Mon 09:00) alerts **only on\nchange**. It must live on the mini — a job registered only on the laptop never fires.\n\n⚠️ **`wrangler secret list` without `--name` is host-dependent.** Same repo, same\ncommit, same account: 12 secrets on the laptop, `[]` **with exit 0** on the mini. That\nsilently produces confident false \"secret not set\" findings. Always pass `--name`, and\nsanity-gate it: zero secrets while `\u002Fapi\u002Fauth\u002Fok` returns 200 is impossible → report\nindeterminate, not a finding.\n\n⚠️ **`require('better-auth\u002Fpackage.json')` throws** — the package's `exports` map does\nnot expose it, so a naive version read reports installed packages as `NOT_INSTALLED`.\nRead `node_modules\u002Fbetter-auth\u002Fpackage.json` by path.\n\n---\n\n## Verification recipes\n\n| Claim | Probe |\n|---|---|\n| Auth routes are live | `curl -o \u002Fdev\u002Fnull -w '%{http_code}' https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fok` |\n| Bad creds rejected | `POST \u002Fapi\u002Fauth\u002Fsign-in\u002Femail` with a wrong password → expect 401 |\n| **A plugin actually shipped** | `curl` its route: **404 = not loaded, 401 = loaded**. Capture the 404 *before* deploy for a before\u002Fafter. |\n| The deployed verifier is the new one | Trap 1 probe + `wrangler tail` for the discriminator |\n| The shell emits its capability token | `wrangler tail --format json` → request `user-agent` |\n| Plugin tables exist **in prod** | `PRAGMA table_info(\u003Ct>)` on `--remote`. The migration file and the LOCAL D1 are not proof. |\n| A social button actually renders | Run the app; screenshot. Source review cannot see CSS overrides. |\n| A passkey\u002F2FA **write** works | Only a real enrolment proves it. Schema + a clean route response do **not** — that is the exact schema-drift shape. Say so rather than implying coverage. |\n\n⚠️ **On an SPA-shaped site, HTTP 200 does NOT prove a path exists — and that can\ninvalidate a \"is it deployed?\" check.** Measured 2026-08-05, same account, two shapes:\n\n| Request | example.com (SPA + assets fallback) | improvebayarea.com (Hono SSR, no fallback) |\n|---|---|---|\n| `\u002Fdefinitely-not-a-real-path-xyz123` | **200 `text\u002Fhtml`** | 404 `text\u002Fplain` |\n| `\u002Fopenapi\u002Fadmin.json` (repo-only file) | **200 `text\u002Fhtml`** | 404 `text\u002Fplain` |\n| `\u002Fapi\u002Fauth\u002Fdefinitely-not-a-route` | **404** | **404** |\n\nThe SPA's catch-all serves `index.html` for anything unmatched, so\n`curl -o \u002Fdev\u002Fnull -w '%{http_code}'` reports 200 for a file that was never\ndeployed. This cost a wrong conclusion in this very session: an OpenAPI spec was\nread as \"served in production\" off a 200 that was really the SPA shell. **Assert\n`content_type` (or grep the body for something only the real artifact contains) —\nnever status alone** when the path is a static file on an SPA.\n\n**This is also exactly why the 404→401 plugin probe above still works:**\n`\u002Fapi\u002Fauth\u002F*` is claimed by the Worker *before* the asset fallback, so an unknown\nauth route genuinely 404s on both shapes. The probe is safe for `\u002Fapi\u002Fauth\u002F**` and\nunsafe for everything else. Confirm your own site's shape once with a nonsense path\nbefore trusting any status-only check.\n\n⚠️ `wrangler tail --format json` is **pretty-printed, not JSONL** — line-wise grep\nmatches nothing. Parse with a brace-matching decoder and fail loudly at 0 objects; a\ntail that wrote 0 bytes never connected, so its silence proves nothing. Check *which*\nrequests it captured before trusting \"0 errors\" — a tail that missed the new route\nsays nothing about the new code.\n\n⚠️ **A post-deploy curl inside ~30s false-negatives** (Worker propagation). Observed\n2026-08-05: `\u002Fprivacy` grepped 0 occurrences of new copy immediately after deploy and\n3 occurrences 30s later. Re-check before calling a gate failed.\n\n⚠️ **A health check written in Python gets 403 from Cloudflare on its own User-Agent.**\nMeasured 2026-08-17 against `imessage.example.com`: default `Python-urllib\u002F3.x`\n→ **403**, browser UA → **200**, `curl` → **200**. Every check in the script then\nreports a FALSE FAILURE (\"association file not served\", \"no Apple button\") against a\nperfectly healthy deployment. Set a browser UA, and **positive-control any urllib\nresult against `curl` before believing a failure** — the 403 is a property of your\nclient, not of the site. (`siwa` pins a UA for exactly this reason.)\n\n⚠️ **Never detect a social button by searching the page for the provider's name.**\n`\"apple\" in html` matches **`-apple-system`** in the CSS `font-family`, so the check\nreported the Apple button PRESENT while both `APPLE_*` secrets were unset — a check\nthat cannot fail. Anchor on the markup the renderer emits only for a *configured*\nprovider (here `data-provider=\"apple\"`), and cover it with a negative control that\nincludes the font-stack string. Same failure family as Trap 5: **source\u002Fsubstring\nreview cannot tell you what rendered.**\n\n⚠️ **A gate that exits 0 with zero output is indistinguishable from a gate that never\nran.** Socket aliases `npx`, so `npx tsc --noEmit` can emit only Socket's banner.\nProve the instrument: inject a deliberate error, confirm non-zero, remove it, confirm\nzero, confirm the tree is clean. Or call the binary directly\n(`.\u002Fnode_modules\u002F.bin\u002Ftsc`) — and note Socket eats `--dry-run`, so\n`npx wrangler deploy --dry-run` never reaches wrangler.\n\n## Hard rules\n\n- **Never** put `KEY|SECRET|TOKEN|PASSWORD` in wrangler `vars` — `wrangler secret put`.\n- **Never** widen an audience\u002Fissuer set beyond clients you own, and assert the exact set in a test.\n- **Never** use Apple's `appBundleIdentifier` — it REPLACES the audience (apple.mjs:63). Use the `audience` array so the web Services ID stays valid, and assert `appBundleIdentifier` is undefined.\n- **Never** gate a value that must ALWAYS be present behind an optional env var. A public identifier (bundle id, client id) belongs in a constant; an unset var turns a required audience into no audience, silently.\n- **Never** report native social working from source review — the CSS and the binary both get a vote.\n- A native-capability change needs a **new build**; a site-side change does not. Say which one you shipped.\n- **Never** leave `passkey({ origin })` unset — that hands the verifier's expected origin to the caller (Trap 9).\n- **Never** transcribe a plugin migration from memory or a blog — read the **installed** package's schema; the two sites are on different versions (Trap 11).\n- **Apply the remote D1 migration BEFORE the code deploys**, and prove it with `PRAGMA table_info` on `--remote`. Plugin code writes these tables on first use.\n- **Never** claim an auth feature works from a green route check. Schema present + route reachable ≠ a write succeeds ≠ the iOS ceremony completes. Name which of the three you verified.\n- **Never** widen 2FA's advertised scope past `\u002Fsign-in\u002Femail` — magic link, email code, Apple, Google and passkey are not second-factored (Trap 10).\n- **Never** hand-roll the Apple client secret or the Apple setup steps — route through `siwa` (`siwa portal` → `domain-file` → `secret` → `probe` → `verify`), and treat `siwa probe`'s `invalid_grant` as the PASS. Keep `betterauth` read-only; `siwa` owns the writes.\n- **Never** let the session gate swallow `\u002F.well-known\u002F` — Apple's domain verification fetches it unauthenticated, and a 302 there fails silently.\n- **Never** trust a Python-based auth health check that reports a failure until you have re-run the same URL through `curl` (Cloudflare 403s the default urllib UA), and never detect a provider button by substring — `-apple-system` in the font stack makes `\"apple\" in html` a check that cannot fail.\n","# Better Auth on Cloudflare Workers + D1\n\nBoth of the user's auth-bearing sites declare **better-auth `^1.6.25`** on a Worker\nwith a D1 binding. This skill is the delta between \"the docs\" and \"what actually\nbroke.\"\n\n**Read the traps before writing code.** Every one below cost at least one deploy\ncycle, and each carries the command that proves it rather than an assertion.\n\n## Mandatory security baseline for every site and every ship\n\nLoad `~\u002F.claude\u002Fskills\u002Fshared\u002Fbetterauth-security-baseline.md` before implementation.\nEvery Better Auth site must propagate authentication email failures through the actual HTTP\nhandler, explicitly protect OTP storage, hash magic-link tokens when enabled, and enforce\nsecond-factor challenges for enrolled users across every enabled primary sign-in path without\nleaking provisional sessions or bearer tokens. A throwing email helper alone is insufficient\non SDK versions whose `runInBackgroundOrAwait` catches the rejection.\n\nNew sites must include real-SDK regression tests and `betterauth.security.json`, wire the full\nsecurity gate into every deploy entrypoint, and release via `\u002Fship`. Existing sites run the\nsame gate on **every ship**, even on a non-auth diff:\n\n```sh\nnode \"$HOME\u002Ftools\u002Fbetterauth\u002Fbetterauth\" security --repo \"$PWD\" --json\n```\n\nOnly exit 0 permits release; missing\u002Funmeasured\u002Ffailed tests block. Static configuration\nchecks and health routes do not replace behavior tests. Read the shared reference and CLI\nREADME for the mutation contract, transition behavior, and scope limitations.\n\n## Current state (verify, don't trust this table — it is a cache)\n\nVerified 2026-08-05.\n\n| | improvebayarea.com | example.com |\n|---|---|---|\n| Repo | `~\u002Ftools\u002Fimprovebayarea` | `~\u002FAIVA-Frontend` |\n| Auth file | `src\u002Fauth.ts` | `src\u002Fworker\u002Fauth.ts` |\n| Shape | Hono SSR, inline client JS in `src\u002Fui.ts` | React SPA + Hono SSR |\n| **Installed** better-auth | **1.6.26** | **1.6.25** |\n| Plugins | `bearer`, `magicLink`, `emailOTP`, `twoFactor`, `passkey` | `bearer`, `emailOTP`, `twoFactor`, `passkey` |\n| Native social | **yes** — `@capgo\u002Fcapacitor-social-login`, live | plugin installed + SPM-linked, **no JS call site** |\n| Native audience fix | Google + Apple (Trap 1) | Apple present; **Google still absent** — no iOS OAuth client exists yet |\n\n⚠️ **Identical `^1.6.25` ranges, different installed versions.** Adding\n`@better-auth\u002Fpasskey@^1.6.26` to IBA let npm re-resolve the caret and float core\nto 1.6.26; AIVA never re-installed and sits at 1.6.25. `package.json` therefore\n**cannot** tell you what is running — the plugin schema you transcribe a migration\nfrom (Trap 8) is the *installed* one. Always read `node_modules`.\n\nRe-check with:\n```bash\nnode -e \"const p=require('.\u002Fpackage.json').dependencies;\nconsole.log('range:',p['better-auth'],'| installed:',require('better-auth\u002Fpackage.json').version)\"\ngrep -nE \"socialProviders|plugins: \\[\" -A 20 \u003Cauth-file>\n```\n\n⚠️ **npm latest has moved past this table — re-check before pinning a NEW project (added 2026-08-30).**\nVerified live on 2026-08-30: **`better-auth` latest on npm is `1.7.2`** (published 2026-08-26), while\nboth sites above are still on **1.6.26 \u002F 1.6.25** — a minor version behind. The table is accurate about\n*these two sites*; it is NOT a version recommendation for a greenfield build, and reading it as one is\nexactly the mistake it invites. This bit for real: on 2026-08-30 a new Workers project was briefed with\n`better-auth ^1.6.26` copied straight out of this file, 25 days stale, and the pin had to be corrected\nmid-build.\n\n**So for any NEW site, resolve the version from the registry, not from here:**\n```bash\ncurl -s https:\u002F\u002Fregistry.npmjs.org\u002Fbetter-auth | python3 -c \"import json,sys;d=json.load(sys.stdin);v=d['dist-tags']['latest'];print(v, d['time'][v][:10])\"\n```\nThen install, and transcribe every plugin migration from the schema in `node_modules` (Trap 8) — a\n1.6.x → 1.7.x jump can move a core or plugin table, and this file documents the 1.6.x shape.\n\n## Standing up a NEW site (do it in this order)\n\nMost of this skill is written from two live migrations, so it reads as \"fix the\nthing that broke.\" On a greenfield site nothing has broken yet — follow this order\nand most traps never fire. Traps 7 (id preservation) and the decommission section\ndo not apply at all; skip them.\n\n| # | Step | The trap it pre-empts |\n|---|---|---|\n| 1 | Create the D1 database + binding `DB`; write the **core schema** migration (below) and apply it `--remote` | Plugin\u002Fcore code writes these tables on first use; a missing column is a generic 500 (Trap 11) |\n| 2 | `openssl rand -base64 32 \\| wrangler secret put BETTER_AUTH_SECRET` | — |\n| 3 | `createAuth(env)` per request + mount both verbs on `\u002Fapi\u002Fauth\u002F*` | Trap 2 |\n| 4 | Prove it before adding anything: `\u002Fapi\u002Fauth\u002Fok` → 200, wrong password → 401 | A green build is not a working auth route |\n| 5 | Add providers ONE at a time, each with its own migration when it has tables | Trap 11 — transcribe DDL from the **installed** package |\n| 6 | Add the Capacitor shell LAST, if there is one | Traps 1, 3, 4, 5 all live here and all need a new binary |\n\n**Decide two things on day one, because changing them later invalidates live\ncredentials:** `advanced.cookiePrefix` (renaming it signs every user out) and\n`PASSKEY_RP_ID` (changing it invalidates every registered passkey — they are bound\nto the RP id).\n\n### The core schema — verified against prod, not transcribed from docs\n\n> ⚠️ **THIS DDL IS 1.6.x AND IS WRONG FOR better-auth 1.7.x (added 2026-08-30).**\n> Measured by reading the INSTALLED 1.7.2 package — `@better-auth\u002Fcore\u002Fdist\u002Fdb\u002Fget-tables.mjs`\n> (`buildAuthTables`) and `...\u002Fdb\u002Fschema\u002Faccount.mjs` (`accountSchema`) — **not** from docs:\n>\n> 1. **NEW REQUIRED COLUMN** on `account`: `issuer text NOT NULL` (`accountSchema` declares\n>    `issuer: z.string()` with no `.nullish()`, so it is mandatory).\n> 2. **NEW UNIQUE INDEX** `(issuer, accountId)`.\n> 3. Field **order** changed: `issuer, accountId, providerId, userId, …`.\n>\n> Apply the DDL below unmodified against 1.7.x and **every account write 500s** with\n> `no such column: issuer` — visible only in `wrangler tail`, never in the response body.\n> That is Trap 11 biting the *core* schema rather than a plugin's.\n>\n> **So do what Trap 11 already tells you to do for plugins, and do it for core too:\n> transcribe from `node_modules`, not from this file.** The block below is a reference for\n> shape and constraints, not a copy-paste source. Re-derive before every new build:\n> ```bash\n> node -e \"console.log(require('better-auth\u002Fpackage.json').version)\"\n> grep -rn 'issuer' node_modules\u002F@better-auth\u002Fcore\u002Fdist\u002Fdb\u002Fschema\u002Faccount.mjs\n> ```\n\n\nbetter-auth needs four tables before any plugin. This is improvebayarea's applied\nmigration, confirmed live on 2026-08-05 via\n`wrangler d1 execute \u003Cdb> --remote --command 'PRAGMA table_info(\"user\")'`:\n\n```sql\nCREATE TABLE IF NOT EXISTS \"user\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"name\" text NOT NULL,\n  \"email\" text NOT NULL UNIQUE,   \"emailVerified\" integer NOT NULL,\n  \"image\" text, \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL\n);\nCREATE TABLE IF NOT EXISTS \"session\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"expiresAt\" date NOT NULL,\n  \"token\" text NOT NULL UNIQUE,   \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL,\n  \"ipAddress\" text, \"userAgent\" text,\n  \"userId\" text NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE\n);\nCREATE TABLE IF NOT EXISTS \"account\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"accountId\" text NOT NULL, \"providerId\" text NOT NULL,\n  \"userId\" text NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE,\n  \"accessToken\" text, \"refreshToken\" text, \"idToken\" text,\n  \"accessTokenExpiresAt\" date, \"refreshTokenExpiresAt\" date,\n  \"scope\" text, \"password\" text, \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL\n);\nCREATE TABLE IF NOT EXISTS \"verification\" (\n  \"id\" text NOT NULL PRIMARY KEY, \"identifier\" text NOT NULL, \"value\" text NOT NULL,\n  \"expiresAt\" date NOT NULL, \"createdAt\" date NOT NULL, \"updatedAt\" date NOT NULL\n);\nCREATE INDEX IF NOT EXISTS \"session_userId_idx\"          ON \"session\"      (\"userId\");\nCREATE INDEX IF NOT EXISTS \"account_userId_idx\"          ON \"account\"      (\"userId\");\nCREATE INDEX IF NOT EXISTS \"verification_identifier_idx\" ON \"verification\" (\"identifier\");\n```\n\n`ON DELETE CASCADE` on `session.userId`\u002F`account.userId` is what makes account\ndeletion actually delete — same reasoning as Trap 11, one level down.\n\n🛑 **Plugins ADD COLUMNS TO `user`, they do not only add tables.** The prod `user`\ntable has **8** columns against the 7 above: `twoFactor()` appends\n`twoFactorEnabled`. So a column-count assertion against this DDL will \"fail\" on a\ncorrect database once a plugin is enabled — count against the **installed plugin\nset**, not this snippet. That is also why the `ALTER TABLE \"user\" ADD COLUMN` in a\nplugin migration must go LAST (Trap 11): SQLite has no `ADD COLUMN IF NOT EXISTS`.\n\n### `trustedOriginsFor` — referenced everywhere, so here it is\n\n```ts\nexport function trustedOriginsFor(env: AuthEnv): string[] {\n  return [\n    \"https:\u002F\u002Fexample.com\",\n    \"https:\u002F\u002Fwww.example.com\",\n    \"capacitor:\u002F\u002Flocalhost\",          \u002F\u002F Capacitor webview — see below\n  ];\n}\n```\n\n**`trustedOrigins` and `PASSKEY_ORIGINS` are different lists and must stay\ndifferent.** `trustedOrigins` is better-auth's CSRF\u002Fredirect allowlist and legitimately\nincludes `capacitor:\u002F\u002Flocalhost`. `passkey({ origin })` is WebAuthn's `expectedOrigin`\nand must contain **only** secure HTTPS origins whose registrable domain matches\n`rpID` — putting `capacitor:\u002F\u002Flocalhost` there is a lie the browser rejects anyway,\nand it hides the real failure (Trap 9). Include `www.` in both.\n\n---\n\n## The working baseline\n\n```ts\nexport function createAuth(env: AuthEnv) {\n  if (!env.BETTER_AUTH_SECRET) throw new Error(\"BETTER_AUTH_SECRET not set\");\n  if (!env.DB) throw new Error(\"D1 binding DB is not configured\");\n\n  return betterAuth({\n    secret: env.BETTER_AUTH_SECRET,\n    baseURL: env.BETTER_AUTH_URL || \"https:\u002F\u002Fexample.com\",\n    basePath: \"\u002Fapi\u002Fauth\",\n    database: env.DB,            \u002F\u002F see Trap 2\n    telemetry: { enabled: false },\n    trustedOrigins: trustedOriginsFor(env),\n    advanced: { cookiePrefix: \"app\" },\n    plugins: [bearer(), \u002F* … *\u002F],\n  });\n}\n```\n\nMount in Hono — **both verbs**, the whole subtree:\n```ts\napp.on([\"GET\", \"POST\"], \"\u002Fapi\u002Fauth\u002F*\", async (c) => createAuth(c.env).handler(c.req.raw));\n```\n\nSecrets: `BETTER_AUTH_SECRET`, plus `GOOGLE_CLIENT_ID`\u002F`GOOGLE_CLIENT_SECRET`,\n`APPLE_CLIENT_ID`\u002F`APPLE_CLIENT_SECRET` per provider. `wrangler secret put` each —\nnever `vars`. **Obtaining them is the actual work — see the next section.**\n\n---\n\n## Provisioning the credentials (the part the docs skip)\n\nGetting these is most of the setup cost. Order matters; each step has a trap.\n\n### 0. `BETTER_AUTH_SECRET`\n```bash\nopenssl rand -base64 32 | wrangler secret put BETTER_AUTH_SECRET\n```\nNever echo it into the transcript. Verify shape only: `wrangler secret list` shows\n`secret_text`.\n\n### 1. Google — you need TWO clients, and only one has a secret\n\n| Client type | Used by | Has a secret? |\n|---|---|---|\n| **Web application** | browser redirect flow; this is `GOOGLE_CLIENT_ID` | yes → `GOOGLE_CLIENT_SECRET` |\n| **iOS** | native `GIDSignIn` in the Capacitor shell | **no** — public by design, ships in the bundle |\n\nConsole: `https:\u002F\u002Fconsole.cloud.google.com\u002Fapis\u002Fcredentials?authuser=1`\n(**`authuser=1` matters** — `authuser=0` can land on an MFA-enrollment gate.)\n\n**Creating the CLIENT is still browser-only** (no API — see the enumeration below). But the\n**consent screen** around it is now scriptable: `gauth-console` (in **`\u002Fgcli`**) drives it\nthrough the real logged-in Chrome. Prefer it over hand-clicking:\n\n```bash\ngauth-console status  \u003Cgcp-project>            # read-only: publish state + branding fields\ngauth-console set     \u003Cgcp-project> privacy|homepage|terms|contact \u003Cvalue>\ngauth-console publish \u003Cgcp-project> --confirm  # refuses unless genuinely ready\n```\nThis is the Google analogue of what `siwa` does for Apple. Note the asymmetry and do not\ngeneralise: Apple's Services ID + Return URLs remain genuinely browser-only, so\n`siwa portal` printing those two steps is still correct.\n\n- Web client → Authorized redirect URI `https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle`.\n- iOS client → bind to the bundle id + team id. Its **reversed** id is the\n  `CFBundleURLScheme` (Trap 3). Put both ids in one shared module so the shell-side\n  id and the server-side accepted audience (Trap 1) can never drift.\n\n**🛑 Google caps a client at TWO client secrets, and delete requires disable first.**\nThe trash icon is inert until the secret is disabled — that is a two-step UI, not a\nbroken button. So when rotating: confirm the stale secret is unused, **disable** it,\n**then** delete, then add the new one. Plan this before you hit the cap.\n\n**Never let a secret value into the transcript.** Pipe it:\n```bash\npbpaste | tr -d '\\n' | wrangler secret put GOOGLE_CLIENT_SECRET\n```\nVerify by shape, never by printing: `wrangler secret list | grep GOOGLE_CLIENT_SECRET`.\nIf you must confirm a value came through, use a boolean test (does string X appear:\ntrue\u002Ffalse) — **never return the surrounding text**, \"scrubbed\" or otherwise.\n\n### 2. Apple — a Services ID plus a JWT you mint yourself\n\n`APPLE_CLIENT_ID` is the **Services ID** (e.g. `com.improvebayarea.signin`), *not*\nthe app bundle id. `APPLE_APP_BUNDLE_ID` is separately needed for the native\naudience (Trap 1).\n\nRegister the return URL under the Services ID → *Sign in with Apple* → Configure:\n**the ⊕ button REGISTERS a new Website URL; the dropdown only LISTS what is already\nattached.** Editing the visible field and pressing Save is a silent no-op — this\nlooks exactly like a broken form. Add `https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fcallback\u002Fapple`, then\n**reload and re-read the list** to confirm it stuck.\n\n`APPLE_CLIENT_SECRET` is **not issued by Apple** — it is a self-signed **ES256 JWT**\nyou generate from a `.p8` Sign-in-with-Apple key, and Apple caps it at **6 months**.\nThe JWT signature must be raw 64-byte `r||s` (ieee-p1363), not DER — hand-rolling\nthat is where people lose an afternoon.\n\n**Drive the whole Apple side with `siwa`** (`~\u002Ftools\u002Fsiwa\u002Fsiwa`, on PATH), which\nwraps every step below. Add the site once to `~\u002F.config\u002Fsiwa\u002Fsites.json`\n(`host, services_id, team_id, key_id, p8, worker_repo, worker_name`), then:\n\n```bash\nsiwa portal   \u003Csite>   # prints the 2 web-only steps (Services ID + Return URL)\nsiwa domain-file \u003Csite> ~\u002FDownloads\u002Fapple-developer-domain-association.txt\nsiwa secret   \u003Csite>   # mint JWT -> both APPLE_* secrets -> deploy -> register expiry\nsiwa probe    \u003Csite>   # ask APPLE whether the credential chain is valid\nsiwa verify   \u003Csite>   # live: assoc file + Apple button + flow -> appleid.apple.com\nsiwa rotate   \u003Csite>   # the 6-month re-mint (same as secret + probe)\n```\n\n`siwa secret` shells out to the same `apple-client-secret.mjs` generator (one\nimplementation, one place to fix) and never prints the JWT — only its length and\nexpiry. **`betterauth` stays read-only and `siwa` owns the mutations**; that split\nis deliberate, so don't teach `betterauth` to write secrets.\n\n🛑 **`siwa probe` is the cheapest real proof the credential chain works, and its\nPASS is an ERROR string.** It POSTs a deliberately-bogus authorization code to\n`https:\u002F\u002Fappleid.apple.com\u002Fauth\u002Ftoken`:\n\n| Apple's `error` | Means |\n|---|---|\n| **`invalid_grant`** | ✅ Apple **accepted** the client secret and refused only the fake code — the `.p8` \u002F `key_id` \u002F `team_id` \u002F Services-ID chain is CORRECT |\n| `invalid_client` | ❌ Apple rejected the **credential** itself |\n\nSame shape as the APNs `BadDeviceToken` trick: make the credential the only thing\nunder test. No browser, no sign-in, no side effect — so it is free to run often.\n\n⚠️ **The Worker's auth gate will break Apple's domain verification if you let it.**\nApple fetches `\u002F.well-known\u002Fapple-developer-domain-association.txt`\n**unauthenticated**. A session gate that allows only `\u002Flogin` and `\u002Fapi\u002Fauth\u002F*`\nredirects that path to `\u002Flogin`, and Apple reads the 302 as a failure with nothing\nin your logs explaining why. Allow the directory through explicitly:\n\n```ts\nif (path.startsWith('\u002F.well-known\u002F')) return next();   \u002F\u002F BEFORE the session check\n```\nProof it worked, on imessage-bridge: that path went **302 → 404** after the fix\n(404 = reaching the asset layer, file not installed yet). Same allowance covers\n`security.txt` and ACME challenges. Safe to expose — the directory only ever holds\nvalues that are public by design.\n\n⚠️ **A SIWA `.p8` is a TEAM-level key.** One key signs JWTs for *any* Services ID\nin that team, so an existing key (e.g. `~\u002F.asc\u002Fkeys\u002FAuthKey_Z5JJTW7C94-siwa-improvebayarea.p8`,\nteam `2KJ8W6N44B`) is reusable for a new site — a new Apple Developer account or key\nis NOT required. The Services ID goes in the JWT's `sub`; the key only signs.\n\n### 3. Register every expiring secret for rotation — MANDATORY\n\nApple gives **no warning** and the failure is opaque: sign-in simply stops, site-wide\n*and* in the app. Add an entry to `~\u002Ftools\u002Fsecret-expiry\u002Fsecrets.json` with `name`,\n`expires`, `owner`, `impact`, and a copy-pasteable `renew` command, then **scp it to\nthe mac-mini** — the mini is the cron host, so an entry only on the laptop never\nalerts. Both sites are already registered; copy an existing entry's shape.\n\nDerive `expires` from the **earlier** plausible mint date, so the alert fires early\nrather than late.\n\n### 4. Decommission the old provider — no half-configs\n\nAfter cutover, delete the old secret (`wrangler secret delete CLERK_SECRET_KEY`),\nstrip its hosts from the CSP, remove the packages, and drop the DNS record. Audit\nwith `wrangler secret list` — a leftover key is both a live credential and a lie\nabout which system is in charge.\n\n> **Verified 2026-08-05: both sites are now clean.** `CLERK_SECRET_KEY` deleted from\n> both Workers (`wrangler secret list` shows it absent while `BETTER_AUTH_SECRET`\n> remains — always assert the control, or you cannot tell \"deleted\" from \"list\n> broke\"). All 10 dangling DNS records removed across both zones; `dig @1.1.1.1`\n> returns NXDOMAIN for `clerk`, `accounts`, `clkmail`, `clk._domainkey`,\n> `clk2._domainkey` on each.\n>\n> **Two lessons worth more than the result:**\n>\n> 1. **A source grep is the WRONG instrument for decommissioning.** Both codebases\n>    had zero `@clerk\u002F*` packages and zero `env.CLERK_*` reads — a grep said \"clean\"\n>    while a live credential was still bound to production and 10 CNAMEs still\n>    pointed into a deleted third-party tenant (a textbook subdomain-takeover\n>    setup). The binding and the zone are the ground truth; the imports are not.\n>    Audit with `wrangler secret list` and `dig`, not `grep`.\n> 2. **Check the DKIM\u002Fmail records too, not just the auth hosts.** The obvious two\n>    are `clerk` and `accounts`; the easy misses are `clkmail` + the two\n>    `clk*._domainkey` CNAMEs. Before deleting them, confirm the domain's SPF does\n>    not reference the vendor and that the real senders' selectors still resolve —\n>    then removing them breaks no mail.\n\n---\n\n## Trap 0 — Interpret Google audience restrictions using the actual scopes\n\n**Corrected 2026-09-09 against Google's current primary documentation.** Testing normally\nrestricts authorization to up to 100 listed test users, with seven-day authorization expiry.\nHowever, requests limited to `openid`, email, and profile (including Sign in with Google)\nare exempt from the test-user-list, warning, and seven-day-expiry behavior. Any additional\nscope removes that exception. The lifetime cap for unapproved sensitive\u002Frestricted scopes\nis a separate rule. Never claim a login-only site cannot sign in its 101st user from the\nTesting label alone; inspect the actual outgoing scopes.\n\nSource: https:\u002F\u002Fsupport.google.com\u002Fcloud\u002Fanswer\u002F15549945?hl=en (fetched 2026-09-09).\nProvider status is still separate from secrets\u002Fschema\u002Froute health; a green local check\ndoes not establish the console policy or end-to-end sign-in.\n\n```bash\ngauth-console status \u003Cgcp-project>     # read-only; prints publish state + what is blocking it\n```\n\n**The publish gate is NOT what the form's `required` flags say.** On\n`console.cloud.google.com\u002Fauth\u002Fbranding` the fields render:\n\n| Field | form says | actually gates publish? |\n|---|---|---|\n| App name | `required=true` | yes |\n| Authorized domain | `required=true` | yes |\n| Email addresses (dev contact) | `required=true` | yes |\n| **Application home page** | `required=false` | **YES** |\n| **Application privacy policy** | `required=false` | **YES** |\n| Application terms of service | `required=false` | no |\n\nThose `required=false` flags are *Testing-mode* validation. \"Publish app\" on `\u002Fauth\u002Faudience`\nstays `aria-disabled=\"true\"` until home page **and** privacy policy are also set — proven by\nelimination (contact email → still blocked; + home page → still blocked; + privacy → ready).\nSo **shipping a privacy policy page is an auth dependency, not a legal nicety.**\n\nTwo reading traps if you check this by hand instead of with `gauth-console`: the button\nreports `disabled === false` while visually greyed (read `aria-disabled`), and the form's\ninputs live in **shadow DOM**, so `document.querySelectorAll('input')` returns `[]` and a\nnaive probe concludes the fields do not exist. Full trap list: **`\u002Fgcli`**.\n\n## Trap 1 — Native iOS social sign-in: the id token audience is NOT your web client\n\n**The single most expensive trap. It has bitten Apple and Google separately.**\n\nGoogle\u002FApple mint an id token whose `aud` is **whichever client asked for it**. The\nbrowser flow asks as your *web* client; a native iOS sheet asks as the *iOS* client\n(Google) or the *bundle id* (Apple). Better Auth's default verifiers check\n`aud === options.clientId` and nothing else, so a **fully successful** OAuth\nround-trip is then rejected by your own server.\n\nThe symptom is maximally misleading: the user completes the Google sheet, Google\nemails *\"You shared some Google Account data with \u003Capp>\"*, and the app shows\n**\"Could not sign in with Google. Invalid token.\"**\n\n🛑 **Corrected 2026-08-05 — the earlier advice here was wrong, and it shipped\nthe bug to production.** This skill used to say Apple had a \"first-class option\"\n(`appBundleIdentifier`) while Google did not. Reading the installed source,\n`@better-auth\u002Fcore\u002Fdist\u002Fsocial-providers\u002Fapple.mjs:63`:\n\n```js\naudience: options.audience?.length ? options.audience\n        : options.appBundleIdentifier ? options.appBundleIdentifier\n        : options.clientId,\n```\n\n`appBundleIdentifier` **REPLACES** the audience — it does not add one. Setting it\nmakes the bundle id the *only* valid audience and silently drops the web Services\nID. The `audience` **ARRAY** takes precedence over both and is the only form that\naccepts each. So Apple and Google get the **same** shape, not different ones:\n\n```ts\napple: {\n  clientId: env.APPLE_CLIENT_ID as string,\n  clientSecret: env.APPLE_CLIENT_SECRET as string,\n  audience: [env.APPLE_CLIENT_ID as string, APPLE_APP_BUNDLE_ID], \u002F\u002F ← BOTH\n},\ngoogle: {\n  clientId: env.GOOGLE_CLIENT_ID as string,\n  clientSecret: env.GOOGLE_CLIENT_SECRET as string,\n  async verifyIdToken(token: string, nonce?: string) {\n    const claims = await verifyGoogleIdToken({\n      token,\n      audience: [env.GOOGLE_CLIENT_ID as string, GOOGLE_IOS_CLIENT_ID], \u002F\u002F jose takes an array\n      nonce,\n    });\n    return Boolean(claims);\n  },\n},\n```\n`import { verifyGoogleIdToken } from \"better-auth\u002Fsocial-providers\"`.\n\n**Two failure modes this exact trap produced on improvebayarea (fixed `e4a486f`):**\n\n1. **An OPTIONAL env var made a REQUIRED audience vanish.** The provider spread\n   `appBundleIdentifier` conditionally on `env.APPLE_APP_BUNDLE_ID` — a var never\n   set on the Worker. The spread no-opped, the comment above it described a\n   configuration that did not exist, and every native Apple sign-in was rejected.\n   **A bundle id is public and must always be present, so it belongs in a\n   constant, not a secret.** `wrangler secret list` is what proves an env-gated\n   config is actually live; the source alone cannot.\n2. **Apple can be LIVE-broken while Google is only latent.** Capability gating is\n   per-provider: on IBA `nativeSocialAvailable('google')` checks a shell UA token,\n   but `nativeSocialAvailable('apple')` is just `Boolean(AUTH_SOCIAL.apple)`\n   (`src\u002Fui.ts:1919`) — so Apple takes the native id-token path in *every* in-app\n   webview, unconditionally. **Check each provider's gate separately; do not\n   assume the one you audited represents the others.**\n\n**This is not a weakening.** It calls Better Auth's own verifier — JWKS signature,\nissuer, expiry, 1h max age and nonce all still enforced. Only the audience\nallowlist widens, to *your own* second client. That is Google's documented pattern\nfor a backend serving several platforms. Assert the set is exactly your clients so\na wildcard can never creep in.\n\n**Do NOT \"fix\" it with the plugin's `iOSServerClientId`.** That maps to GIDSignIn's\n`serverClientID`, which the SDK sends as the OAuth **`audience` request parameter**\n(`GIDSignIn.m:896`) to obtain a `serverAuthCode`; whether it also rewrites the id\ntoken's `aud` is undocumented — the plugin's own docs tie the field to offline mode.\nAccepting both audiences is correct regardless, which is why it is the right fix.\n\n**Probe (proves the deployed verifier, costs nothing — a failed sign-in has no side effect):**\n```bash\nHDR=$(printf '{\"alg\":\"RS256\",\"kid\":\"k\"}' | base64 | tr '+\u002F' '-_' | tr -d '=')\nPAY=$(printf '{\"aud\":\"PROBE.apps.googleusercontent.com\",\"iss\":\"https:\u002F\u002Faccounts.google.com\",\"exp\":%d}' $(($(date +%s)+600)) | base64 | tr '+\u002F' '-_' | tr -d '=')\ncurl -s -X POST https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fsign-in\u002Fsocial -H 'Content-Type: application\u002Fjson' \\\n  -d \"{\\\"provider\\\":\\\"google\\\",\\\"idToken\\\":{\\\"token\\\":\\\"$HDR.$PAY.sig\\\"}}\"\n```\nExpect 401. Then read `wrangler tail` for the discriminator (Trap 6).\n\n---\n\n## Trap 2 — Instantiate PER REQUEST; hand D1 in raw\n\n`env.DB` is scoped to one invocation. A module-level singleton captures the first\nrequest's binding and silently breaks on every later one. `createAuth(env)` does no\nI\u002FO, so per-request is cheap.\n\nPass the binding **directly** as `database: env.DB` — `@better-auth\u002Fkysely-adapter`\ndetects the `batch\u002Fexec\u002Fprepare` surface and wraps it in its own `D1SqliteDialect`\n(`@better-auth\u002Fkysely-adapter\u002Fdist\u002Findex.mjs:67-69`). No dialect construction needed.\n\n---\n\n## Trap 3 — Capacitor: no URL scheme means the app CRASHES, not \"fails\"\n\nNative Google requires the reversed client id in `Info.plist`:\n```xml\n\u003Ckey>CFBundleURLTypes\u003C\u002Fkey>\n\u003Carray>\u003Cdict>\n  \u003Ckey>CFBundleURLSchemes\u003C\u002Fkey>\n  \u003Carray>\u003Cstring>com.googleusercontent.apps.NNNN-xxxx\u003C\u002Fstring>\u003C\u002Farray>\n\u003C\u002Fdict>\u003C\u002Farray>\n```\nWithout it GoogleSignIn raises **`NSInvalidArgumentException`** (`GIDSignIn.m:733`)\n— an uncaught ObjC exception that kills the app. There is no alternative path and\nno graceful degradation: enabling the button in a build lacking the scheme crashes\nevery install that taps it.\n\nThe scheme is **compiled in**, so this always needs a new TestFlight build.\n\n⚠️ `mobile\u002Fios\u002FApp\u002FApp\u002Fcapacitor.config.json` is **gitignored** and regenerated by\n`npx cap sync ios`. Archiving without syncing produces a binary missing whatever you\njust added to `capacitor.config.ts` — with no error anywhere. Verify in the archive:\n```bash\n\u002Fusr\u002Flibexec\u002FPlistBuddy -c \"Print :CFBundleURLTypes:0:CFBundleURLSchemes:0\" \u003CApp>.app\u002FInfo.plist\ngrep -o '\"appendUserAgent\"[^,]*' \u003CApp>.app\u002Fcapacitor.config.json\n```\n\n---\n\n## Trap 4 — Remote-URL wrap: capability tokens, never a boolean flag\n\nWhen `server.url` points at the live site, **the web layer is served to every\ninstall at once, old and new.** A site-side `const NATIVE_READY = true` therefore\nswitches the feature on inside already-installed builds that lack the native\ncapability — the exact dead-end (or crash) the flag was meant to prevent.\n\nInvert it: the **shell declares** what it can do, the site reacts.\n```ts\n\u002F\u002F capacitor.config.ts — add ONLY in the commit that adds the capability to the binary\nappendUserAgent: \"MyApp nativeGoogleAuth\u002F1\",\n```\n```js\nfunction shellDeclaresNativeGoogle() {\n  try { return (navigator.userAgent || '').includes('nativeGoogleAuth\u002F1'); }\n  catch (e) { return false; }\n}\n```\nA build without the capability never emits the token, so a stale install cannot opt\nin. No version arithmetic, no deploy ordering. Safari lacks it too — correct, since\nbrowsers use the web flow.\n\nProve the token actually reaches the page (server-side is ground truth):\n```bash\nwrangler tail --format json   # then load the app; read event.request.headers['user-agent']\n```\n\n---\n\n## Trap 5 — A JS gate is not enough: CSS can override it\n\nSites that hide social buttons inside webviews often do it in **CSS**:\n```css\nhtml[data-native-shell] #btn-social-google { display: none !important; }\n```\nThat beats any JS capability check. On improvebayarea the JS gate returned `true`,\nevery condition passed, and the button still did not render — `display:none\n!important` won, and a test asserted the unconditional rule, locking the bug in.\n\nFix by excluding capable shells at the selector level and setting the attribute only\nwhen the capability is real:\n```css\nhtml[data-native-shell]:not([data-native-google]) #btn-social-google { display: none !important; }\n```\n**Never conclude a social button works from source review.** Run it and look.\n\n---\n\n## Trap 6 — \"Invalid token\" is one string for many causes: ship a discriminator\n\nBetter Auth collapses audience mismatch, bad signature, and expiry into one\n`{\"message\":\"Invalid token\",\"code\":\"INVALID_TOKEN\"}`. Every single-cause fix then\nlooks byte-identical to no fix — Pattern #32.\n\nLog the measurable properties on the rejection path. **Non-PII only** — an id token\nis full of user data:\n```ts\nif (!claims) {\n  let aud = \"\u003Cunparseable>\", iss = \"\u003Cunparseable>\";\n  let expired: boolean | \"unknown\" = \"unknown\";\n  try {\n    const j = JSON.parse(atob((token.split(\".\")[1] ?? \"\").replace(\u002F-\u002Fg,\"+\").replace(\u002F_\u002Fg,\"\u002F\")));\n    if (typeof j.aud === \"string\") aud = j.aud;\n    if (typeof j.iss === \"string\") iss = j.iss;\n    if (typeof j.exp === \"number\") expired = j.exp * 1000 \u003C Date.now();\n  } catch { \u002F* placeholders ARE the signal *\u002F }\n  console.warn(JSON.stringify({ event: \"google_id_token_rejected\", aud, iss, expired,\n    audAccepted: [webId, iosId].includes(aud), nonceSupplied: Boolean(nonce), tokenLen: token.length }));\n}\n```\nLog `aud`\u002F`iss`\u002F`exp` — never `sub`, `email`, `name`, or the token. The unverified\ndecode is for logging only; trust still comes solely from the verifier above it.\n\n---\n\n## Trap 7 — Migrating off Clerk: preserve the user ids\n\nApp data is FK'd to the old provider's user id. Import users with\n`id = \u003Cold provider id>` via direct D1 inserts — **zero FK re-keying**, and social\naccounts relink on first sign-in because the OAuth apps (and therefore `sub`) are\nunchanged. Set `account.accountLinking.trustedProviders` for providers that verify\nthe email, or the true owner hits `account_not_linked`.\n\nPassword hashes are **dashboard-export only** (the Backend API never exposes\n`password_digest`), and Clerk's `password_hasher` is an enum of ~15 algorithms, not\njust bcrypt. Import a credential row **only** for hashes you can actually verify;\nfor anything else send a reset email rather than writing a credential that can never\nmatch — that failure surfaces as a generic \"invalid password\" with nothing in the logs.\n\n**A provider migration silently drops credential types while leaving their\ninfrastructure standing.** On IBA the Clerk-era AASA + Associated-Domains\nentitlement for passkeys (`dadfdf3`) survived the cutover; the *credentials* did\nnot — `2ba98c0` carried `bearer`\u002F`magicLink`\u002F`emailOTP` and nothing else. The\nhonest short-term fix then *hid* the gap: `b96dd0f` rewrote the privacy page to\nstop claiming passkeys, which was correct (never overclaim) but left a product\nregression looking like a settled decision. **After any auth migration, diff the\nOLD provider's enabled credential types against your new `plugins:` array** — the\ndashboard's feature list, not your memory of it.\n\n---\n\n## Trap 8 — `twoFactor()` defaults to demanding a password almost nobody has\n\n`\u002Ftwo-factor\u002Fenable` calls `shouldRequirePassword`\n(`node_modules\u002Fbetter-auth\u002Fdist\u002Futils\u002Fpassword.mjs`) and, by default, **refuses to\nenrol an account that cannot supply its password**. On a deployment where accounts\narrive by Clerk import (`password_enabled=false`), social, magic link, email OTP,\nor passkey — i.e. essentially all of them — 2FA is rendered **visible in the UI and\npermanently unreachable**. Nothing errors at deploy time; the button simply never\nworks, for everyone.\n\n```ts\ntwoFactor({\n  issuer: APP_DISPLAY_NAME,\n  allowPasswordless: true,   \u002F\u002F ← load-bearing, not a convenience\n}),\n```\n\n**This is not a weakening.** The flag's other branch still demands the password\nwhenever a credential account *has* one — it relaxes the check only where there is\nnothing to check. Assert both halves, or a future default-flip silently becomes an\naccount-takeover:\n\n```\nenrol with NO password        → 200, secret written\nenrol with a WRONG password   → 400, nothing written   ← the half that matters\nanonymous caller              → 401\n```\n\nAlso assert, against a real instance: the stored secret does **not** contain the\nplaintext handed to the app (D1 is a separate blast radius from the Worker), and\nminting a secret does **not** flip `twoFactorEnabled` (a mistyped setup must not\nlock the user out of their own password sign-in).\n\n---\n\n## Trap 9 — `passkey({ origin })` left unset is attacker-controlled\n\nOmit `origin` and the plugin falls back to the request's own `Origin` header — and\nthat value is handed straight to the verifier as `expectedOrigin`. Verified in the\ninstalled source (`@better-auth\u002Fpasskey\u002Fdist\u002Findex.mjs`, 1.6.26):\n\n```js\n321:  const origin = options?.origin || ctx.headers?.get(\"origin\") || \"\";   \u002F\u002F register\n337:        expectedOrigin: origin,\n414:  const origin = options?.origin || ctx.headers?.get(\"origin\") || \"\";   \u002F\u002F authenticate\n436:      expectedOrigin: origin,\n```\n\nSo the check becomes \"does the origin match the origin the caller sent\" — which is\nnot a check. Pin it to a literal allowlist:\n\n```ts\nexport const PASSKEY_RP_ID  = \"improvebayarea.com\";\nexport const PASSKEY_ORIGINS = [\n  \"https:\u002F\u002Fimprovebayarea.com\",\n  \"https:\u002F\u002Fwww.improvebayarea.com\",   \u002F\u002F registrable suffix matches the RP id\n] as const;\n\npasskey({ rpID: PASSKEY_RP_ID, rpName: APP_DISPLAY_NAME, origin: [...PASSKEY_ORIGINS] }),\n```\n\n**Passkey origins are NOT `trustedOrigins`, and the difference is load-bearing.**\nWebAuthn requires a secure HTTPS origin whose registrable domain matches `rpID`.\n`capacitor:\u002F\u002Flocalhost` belongs in `trustedOrigins` and must **never** appear here\n— the browser rejects it anyway, so listing it only hides the real failure. Omitting\n`www.` is the opposite mistake: a passkey registered there fails verification with an\nopaque 400.\n\nProbe the deployed config for free — a failed ceremony has no side effect:\n```bash\ncurl -s -o \u002Fdev\u002Fnull -w '%{http_code}\\n' \\\n  https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fpasskey\u002Fgenerate-register-options\n# 404 = plugin NOT loaded · 401 = loaded, demanding auth (correct)\n```\nThat **404 → 401 transition is the cheapest proof a plugin actually shipped** — far\nbetter than reading the diff. Capture the 404 *before* deploying so you have a\nbefore\u002Fafter, and re-check after >30s (Worker propagation false-negatives an\nimmediate curl).\n\n🛑 **The probe's HTTP method is PER-ROUTE — a GET-only sweep reports working plugins\nas missing.** Corrected 2026-08-05 after this exact false negative: `GET\n\u002Ftwo-factor\u002Fenable` returns **404**, `POST` returns **401**. Three live plugins on IBA\nread as \"not loaded\" under a GET-only probe. Use the method the route actually\ndeclares (`betterauth health` encodes the per-route table), and treat a 404 from the\nwrong verb as *no information*, not evidence of absence.\n\n---\n\n## Trap 10 — Enabling 2FA makes a CORRECT password look like a broken session\n\nOnce 2FA is on, `\u002Fsign-in\u002Femail` answers **200 with no session** and a\n`twoFactorRedirect` payload; better-auth deletes the half-made session\n(`...\u002Fplugins\u002Ftwo-factor\u002Findex.mjs:266`). Client code that infers \"signed in\" from\n`res.ok` therefore tells a user who typed the **right** password that the session\ndid not stick — an opaque failure on the happy path. Handle `twoFactorRedirect`\nexplicitly, and surface backup codes from the challenge itself, since that is the\nonly screen a locked-out user can still reach.\n\n**Scope it honestly in product copy.** better-auth challenges **only**\n`\u002Fsign-in\u002Femail` (`...\u002Ftwo-factor\u002Findex.mjs:222`). Magic link, email code, Apple,\nGoogle and passkey sign-in are **not** second-factored. Say the code guards *the\npassword*, not *the account* — and lock the phrasing with a test so a later\ncopy-edit cannot widen the claim.\n\n---\n\n## Trap 11 — Plugin tables: transcribe the DDL from installed source, and CASCADE\n\nA plugin's storage is your migration to write. Getting a column wrong does **not**\nfail loudly: the adapter throws inside the handler, better-auth returns a generic\n500, and `no such column` appears only in `wrangler tail` under `logs[]` — never\n`exceptions[]`. Transcribe from the **installed** package (Trap: the two sites are on\ndifferent versions):\n\n| Table | Source of truth |\n|---|---|\n| `passkey` | `node_modules\u002F@better-auth\u002Fpasskey\u002Fdist\u002Findex.mjs` (`#region src\u002Fschema.ts`) |\n| `twoFactor` | `node_modules\u002Fbetter-auth\u002Fdist\u002Fplugins\u002Ftwo-factor\u002Fschema.mjs` |\n| `user.twoFactorEnabled` | same twoFactor schema, `user.fields` block |\n\nType mapping (established empirically against better-auth driving SQLite):\n`string`→`text`, `number`→`integer`, `boolean`→`integer` (0\u002F1, **never** a boolean\nliteral), `date`→`date` (ISO-8601 TEXT at rest).\n\n**`ON DELETE CASCADE` is required, not decorative.** `internalAdapter.deleteUser`\n(`better-auth\u002Fdist\u002Fdb\u002Finternal-adapter.mjs:164-175`) deletes only session\u002Faccount\u002F\nuser rows and knows nothing about plugin tables. Without it, \"delete my account\"\nleaves a live `credentialID` behind — breaking the erasure your privacy page\npromises, and 500ing `\u002Fpasskey\u002Fverify-authentication` when it matches a row whose\nowner is gone.\n\n**Put the one non-idempotent statement LAST.** SQLite has no\n`ADD COLUMN IF NOT EXISTS`, so `ALTER TABLE \"user\" ADD COLUMN \"twoFactorEnabled\"`\naborts the batch on a re-run (`duplicate column name` — harmless, but it stops\neverything after it). Everything above it is `IF NOT EXISTS`, so a first run has\nalready created every table and index before this can fail.\n\n**Tests must read `migrations\u002F` — never a hand-copied `CREATE TABLE`.** A second\nsource of truth in the test file had already drifted a column on IBA, which is how\nthis change first surfaced as `table user has no column named twoFactorEnabled`.\n\n---\n\n## Trap 12 — \"single-tenant\" is a comment, not a control: `enabled: true` ships an OPEN SIGNUP route, and authenticating is not authorizing\n\n**Found 2026-08-30 building `agentprofile`. It was a HIGH-severity unauthenticated\nfull-owner compromise, and the code carried a comment asserting the opposite.**\n\nTwo independent halves. Either one alone is the whole vulnerability.\n\n**Half 1 — `emailAndPassword: { enabled: true }` publishes `POST \u002Fsign-up\u002Femail`.**\nThe only gate in the installed package is:\n\n```js\n\u002F\u002F node_modules\u002Fbetter-auth\u002Fdist\u002Fapi\u002Froutes\u002Fsign-up.mjs\nif (!ctx.context.options.emailAndPassword?.enabled ||\n    ctx.context.options.emailAndPassword?.disableSignUp) throw APIError.from(\"BAD_REQUEST\", ...)\n```\n\nSo `enabled: true` without `disableSignUp: true` is a live, public account-creation\nendpoint. And it hands back a usable session immediately — `createSession` then\n`setSessionCookie` then a body containing `token` — because `autoSignIn` defaults on and\n`requireEmailVerification` is unset. With the `bearer()` plugin that token also works as\nan `Authorization` header.\n\n**`trustedOrigins` does NOT save you.** The CSRF middleware short-circuits:\n`if (headers.has(\"cookie\")) return await validateOrigin(ctx)` — a plain `curl` sends no\ncookie — and it then only validates when a `Sec-Fetch-*`, `origin`, or `referer` header is\npresent. A bare `curl` supplies none of those, so the function returns having validated\nnothing and `trustedOrigins` is never consulted.\n\n**Half 2 — a middleware that only checks `session !== null` authenticates without\nauthorizing.** This shape is the bug:\n\n```ts\nconst session = await createAuth(c.env).api.getSession({ headers: c.req.raw.headers });\nif (session === null) return jsonError(401, ...);\nc.set('owner', { userId: session.user.id });   \u002F\u002F \u003C-- ANY valid session is now \"the owner\"\n```\n\nThere is no comparison against a designated owner. On a single-tenant app that means the\n*second* account created — by anyone — has full owner authority: read every stored record,\nmint API tokens with every scope, and **approve its own pending approvals**, which defeats\nany human-in-the-loop gate you built on top of it.\n\n### The probe (three greps, ~20 seconds)\n\n```bash\ngrep -rn 'disableSignUp' src\u002F                      # ZERO hits + enabled:true  => signup is LIVE\ngrep -rn 'session\\.user\\.id' src\u002F                  # only an assignment, no comparison => no owner\ngrep -rniE 'owner_?user_?id|ownerUserId' src\u002F wrangler.jsonc   # ZERO => no owner is configured\n```\n\n### The fix — apply BOTH\n\n```ts\nemailAndPassword: { enabled: true, disableSignUp: true },\n```\nthen seed the owner out of band (a one-shot CLI insert of `user` + `account` with a hashed\npassword), **and** make the middleware authorize:\n```ts\nif (session === null || session.user.id !== c.get('config').ownerUserId) {\n  return jsonError(401, 'unauthenticated', 'Owner session required.');\n}\n```\nAlso narrow the mount — `app.on([...], `${AUTH_BASE_PATH}\u002F*`, ...)` republishes every route\nany future plugin adds. Allowlist `\u002Fsign-in\u002Femail`, `\u002Fsign-out`, `\u002Fget-session`.\n\n### Arm the tests by deleting the guard\n\n`POST \u002Fapi\u002Fauth\u002Fsign-up\u002Femail` must return 4xx — delete `disableSignUp` and it must go red.\nA session for a non-owner id must be rejected on every protected route — delete the\n`ownerUserId` comparison and it must go red.\n\n### The meta-lesson\n\nThe source comment said *\"Single-tenant by construction … There is no public signup route to\nleave open,\"* the README said *\"There is no signup route and no second user. That is the\nproduct, not a gap,\"* and the middleware docblock called itself *\"the one place where 'is\nthis the owner' is decided.\"* All three were false, and each **read as verification while\nverifying nothing**. A comment asserting an invariant is not an invariant. If a property\nmatters, there is a test that fails when it stops holding — otherwise it is a wish.\n\n## Passkeys in a Capacitor shell: usually NO new build (contrast Traps 3–4)\n\nNative *social* needs a compiled-in URL scheme, so it always needs a new archive.\nPasskeys usually do **not** — and the distinction is the shell's `server.url`:\n\n- **Remote-URL wrap** (`server.url: \"https:\u002F\u002F\u003Csite>\"`): the webview's WebAuthn origin\n  *is* the real HTTPS origin, so the whole ceremony is site-side and reaches\n  installed binaries on a Worker deploy.\n- The only native prerequisite is the **Associated Domains entitlement**\n  (`webcredentials:\u003Cdomain>`) plus the AASA file. Both are **relying-party based**, so\n  they survive an auth-provider migration untouched — Clerk-era bindings work for\n  Better Auth with no change.\n\nVerify the binding before debugging any JS ceremony (30 seconds, catches the\n\"registration was cancelled or timed out\" class):\n```bash\ncurl -s https:\u002F\u002F\u003Csite>\u002F.well-known\u002Fapple-app-site-association | python3 -m json.tool | grep -A3 webcredentials\ngrep -A3 associated-domains mobile\u002Fios\u002FApp\u002FApp\u002FApp.entitlements\n```\n**These are THREE different things — name which you verified.** Entitlement present in\nthe repo ≠ present in the *signed* build ≠ the capability enabled on the bundle id.\n\n🛑 **The portal capability IS API-checkable — do not claim it is browser-only.**\nCorrected 2026-08-05; the earlier version of this skill said it could not be verified\nwithout an archive, and that was wrong:\n```bash\nasc capabilities --bundle-id com.\u003Capp>   # ASSOCIATED_DOMAINS \u002F APPLE_ID_AUTH, ~2s\n```\nVerified live: both `com.improvebayarea.app` and `com.example.app` report\n`ASSOCIATED_DOMAINS` + `APPLE_ID_AUTH` enabled. What genuinely has **no** API is the\nServices ID's **Return URLs** (Sign in with Apple config) and Google's OAuth **client\nsecrets** — those two, and only those, need the browser recipes in `betterauth portal`.\n\n---\n\n## `betterauth` — the enforcement layer for everything below\n\nThis skill explains *why*; **`~\u002Ftools\u002Fbetterauth\u002Fbetterauth` checks it mechanically.**\nRead-only by design (it reports, you fix — it never mutates a secret or a schema).\nRun it before trusting any claim in the \"Current state\" table, which is a cache.\n\n```bash\nbetterauth all                # every check, human-readable\nbetterauth all --json         # for scripts\u002Fcron\nbetterauth drift              # installed version per site vs npm latest + CROSS-SITE skew\nbetterauth secrets            # required\u002Fmissing, stale (CLERK_*), expiry via secret-expiry\nbetterauth schema             # remote D1 PRAGMA vs the INSTALLED plugin schemas\nbetterauth health             # \u002Fapi\u002Fauth\u002Fok + per-plugin route probe (correct verb per route)\nbetterauth portal             # Apple capabilities via asc API + the 2 genuinely-no-API recipes\nbetterauth consent            # Google audience\u002Fpublish state; interpret with requested scopes\nbetterauth security --repo \"$PWD\" --json  # required full behavior + mutation gate before every ship\n```\n\n**Two CLIs, one boundary — do not blur it.** `betterauth` DIAGNOSES (read-only:\nno `secret put`, no D1 writes, no deploy); **`siwa` REMEDIATES the Apple half**\n(mints the JWT, sets `APPLE_*`, deploys, rotates). So `betterauth secrets` telling\nyou `APPLE_CLIENT_SECRET` is missing or expiring is answered by `siwa secret \u003Csite>`\n\u002F `siwa rotate \u003Csite>` — that is the intended hand-off, and it is why `betterauth`\nmust never grow a write path.\n\n| Question | Tool |\n|---|---|\n| Is Apple configured \u002F expiring \u002F drifted? | `betterauth secrets` · `betterauth portal` |\n| Do the audience and requested scopes permit intended users? | `betterauth consent` plus actual OAuth scopes (Trap 0) |\n| Is the *credential chain* actually valid to Apple? | **`siwa probe \u003Csite>`** (`invalid_grant` = PASS) |\n| Make it work \u002F rotate it | **`siwa secret`** · **`siwa rotate`** |\n| Is it live end-to-end right now? | **`siwa verify \u003Csite>`** (or `betterauth health` for all routes) |\n\n⚠️ **Sign-in-with-Apple has NO API for the Services ID or its Return URLs — this is\nmeasured, not assumed.** `asc capabilities` (App Store Connect CLI, 24 modelled\ncapabilities over a 1263-endpoint schema index) has **no entry** for either; the only\nDeveloper-Portal capability it reaches via web session is `PRIVATE_CLOUD_COMPUTE`,\nand `bundleIdCapabilities` is the only API-backed signing surface. Probing the\nplausible internal endpoints with an owner token also fails:\n`oauthconfig.googleapis.com\u002Fv1\u002Fprojects\u002F\u003Cp>\u002Fclients` → **404**,\n`clientauthconfig.googleapis.com\u002F...` → **404**, `iap.googleapis.com` brands → 403.\n\n🛑 **That 403 proves NOTHING and must not be cited as evidence (corrected 2026-08-31).**\nA 403 from a `*.googleapis.com` endpoint is almost always `SERVICE_DISABLED` — \"this API\nis not enabled on your project\" — which is a *project-config* state, not a statement about\nwhether the endpoint exists. Reading it as absence cost a wrong diagnosis on 2026-08-31.\nThree probes are a **sample** anyway; the claim needs the denominator:\n\n**ENUMERATED, not sampled** — the full Google discovery corpus (528 items,\n`https:\u002F\u002Fwww.googleapis.com\u002Fdiscovery\u002Fv1\u002Fapis`) contains **no** `clientauthconfig`, **no**\n`oauthconfig`, **no** `consentscreen`. `oauth2 v2` exists but has exactly three methods\n(`tokeninfo`, `userinfo`, `userinfo\u002Fv2\u002Fme`) — it CONSUMES tokens and cannot create clients.\nThe only client-admin API Google ever shipped was the IAP OAuth Admin API, and `gcloud`'s\nown `--help` says it was **permanently shut down 2026-03-19** (\"New projects will not be\nable to use these APIs\"). Terraform `google_iap_brand`\u002F`google_iap_client` wrap that same\ndead API. Google's migration doc states it verbatim: *\"If your application requires a custom\nClient ID for branding or external access, use the Google Cloud console to create the Client\nID.\"* — https:\u002F\u002Fdocs.cloud.google.com\u002Fiap\u002Fdocs\u002Fdeprecations\u002Fmigrate-oauth-client\nSee **`\u002Fgcli`** for the enumeration command and the rest of the Google-side tooling. So a\n\"fully automated Apple setup\" is not buildable — `siwa portal` printing the two\nbrowser steps IS the correct design, not a shortcoming. Don't try to generate an\nAPI-wrapper CLI for it (the CLI-printing-press route dead-ends here for exactly\nthis reason).\n\n**Exit codes are the contract**: `0` clean · `1` finding · `2` usage · **`3` could not\ndetermine**. 3 is the important one — a check that could not run must never read as\nclean. Config lives in `sites.json`; a third site is one entry, not a code change.\n\nWeekly Hermes cron on the mac-mini (`4e8f2ca8fbca`, Mon 09:00) alerts **only on\nchange**. It must live on the mini — a job registered only on the laptop never fires.\n\n⚠️ **`wrangler secret list` without `--name` is host-dependent.** Same repo, same\ncommit, same account: 12 secrets on the laptop, `[]` **with exit 0** on the mini. That\nsilently produces confident false \"secret not set\" findings. Always pass `--name`, and\nsanity-gate it: zero secrets while `\u002Fapi\u002Fauth\u002Fok` returns 200 is impossible → report\nindeterminate, not a finding.\n\n⚠️ **`require('better-auth\u002Fpackage.json')` throws** — the package's `exports` map does\nnot expose it, so a naive version read reports installed packages as `NOT_INSTALLED`.\nRead `node_modules\u002Fbetter-auth\u002Fpackage.json` by path.\n\n---\n\n## Verification recipes\n\n| Claim | Probe |\n|---|---|\n| Auth routes are live | `curl -o \u002Fdev\u002Fnull -w '%{http_code}' https:\u002F\u002F\u003Csite>\u002Fapi\u002Fauth\u002Fok` |\n| Bad creds rejected | `POST \u002Fapi\u002Fauth\u002Fsign-in\u002Femail` with a wrong password → expect 401 |\n| **A plugin actually shipped** | `curl` its route: **404 = not loaded, 401 = loaded**. Capture the 404 *before* deploy for a before\u002Fafter. |\n| The deployed verifier is the new one | Trap 1 probe + `wrangler tail` for the discriminator |\n| The shell emits its capability token | `wrangler tail --format json` → request `user-agent` |\n| Plugin tables exist **in prod** | `PRAGMA table_info(\u003Ct>)` on `--remote`. The migration file and the LOCAL D1 are not proof. |\n| A social button actually renders | Run the app; screenshot. Source review cannot see CSS overrides. |\n| A passkey\u002F2FA **write** works | Only a real enrolment proves it. Schema + a clean route response do **not** — that is the exact schema-drift shape. Say so rather than implying coverage. |\n\n⚠️ **On an SPA-shaped site, HTTP 200 does NOT prove a path exists — and that can\ninvalidate a \"is it deployed?\" check.** Measured 2026-08-05, same account, two shapes:\n\n| Request | example.com (SPA + assets fallback) | improvebayarea.com (Hono SSR, no fallback) |\n|---|---|---|\n| `\u002Fdefinitely-not-a-real-path-xyz123` | **200 `text\u002Fhtml`** | 404 `text\u002Fplain` |\n| `\u002Fopenapi\u002Fadmin.json` (repo-only file) | **200 `text\u002Fhtml`** | 404 `text\u002Fplain` |\n| `\u002Fapi\u002Fauth\u002Fdefinitely-not-a-route` | **404** | **404** |\n\nThe SPA's catch-all serves `index.html` for anything unmatched, so\n`curl -o \u002Fdev\u002Fnull -w '%{http_code}'` reports 200 for a file that was never\ndeployed. This cost a wrong conclusion in this very session: an OpenAPI spec was\nread as \"served in production\" off a 200 that was really the SPA shell. **Assert\n`content_type` (or grep the body for something only the real artifact contains) —\nnever status alone** when the path is a static file on an SPA.\n\n**This is also exactly why the 404→401 plugin probe above still works:**\n`\u002Fapi\u002Fauth\u002F*` is claimed by the Worker *before* the asset fallback, so an unknown\nauth route genuinely 404s on both shapes. The probe is safe for `\u002Fapi\u002Fauth\u002F**` and\nunsafe for everything else. Confirm your own site's shape once with a nonsense path\nbefore trusting any status-only check.\n\n⚠️ `wrangler tail --format json` is **pretty-printed, not JSONL** — line-wise grep\nmatches nothing. Parse with a brace-matching decoder and fail loudly at 0 objects; a\ntail that wrote 0 bytes never connected, so its silence proves nothing. Check *which*\nrequests it captured before trusting \"0 errors\" — a tail that missed the new route\nsays nothing about the new code.\n\n⚠️ **A post-deploy curl inside ~30s false-negatives** (Worker propagation). Observed\n2026-08-05: `\u002Fprivacy` grepped 0 occurrences of new copy immediately after deploy and\n3 occurrences 30s later. Re-check before calling a gate failed.\n\n⚠️ **A health check written in Python gets 403 from Cloudflare on its own User-Agent.**\nMeasured 2026-08-17 against `imessage.example.com`: default `Python-urllib\u002F3.x`\n→ **403**, browser UA → **200**, `curl` → **200**. Every check in the script then\nreports a FALSE FAILURE (\"association file not served\", \"no Apple button\") against a\nperfectly healthy deployment. Set a browser UA, and **positive-control any urllib\nresult against `curl` before believing a failure** — the 403 is a property of your\nclient, not of the site. (`siwa` pins a UA for exactly this reason.)\n\n⚠️ **Never detect a social button by searching the page for the provider's name.**\n`\"apple\" in html` matches **`-apple-system`** in the CSS `font-family`, so the check\nreported the Apple button PRESENT while both `APPLE_*` secrets were unset — a check\nthat cannot fail. Anchor on the markup the renderer emits only for a *configured*\nprovider (here `data-provider=\"apple\"`), and cover it with a negative control that\nincludes the font-stack string. Same failure family as Trap 5: **source\u002Fsubstring\nreview cannot tell you what rendered.**\n\n⚠️ **A gate that exits 0 with zero output is indistinguishable from a gate that never\nran.** Socket aliases `npx`, so `npx tsc --noEmit` can emit only Socket's banner.\nProve the instrument: inject a deliberate error, confirm non-zero, remove it, confirm\nzero, confirm the tree is clean. Or call the binary directly\n(`.\u002Fnode_modules\u002F.bin\u002Ftsc`) — and note Socket eats `--dry-run`, so\n`npx wrangler deploy --dry-run` never reaches wrangler.\n\n## Hard rules\n\n- **Never** put `KEY|SECRET|TOKEN|PASSWORD` in wrangler `vars` — `wrangler secret put`.\n- **Never** widen an audience\u002Fissuer set beyond clients you own, and assert the exact set in a test.\n- **Never** use Apple's `appBundleIdentifier` — it REPLACES the audience (apple.mjs:63). Use the `audience` array so the web Services ID stays valid, and assert `appBundleIdentifier` is undefined.\n- **Never** gate a value that must ALWAYS be present behind an optional env var. A public identifier (bundle id, client id) belongs in a constant; an unset var turns a required audience into no audience, silently.\n- **Never** report native social working from source review — the CSS and the binary both get a vote.\n- A native-capability change needs a **new build**; a site-side change does not. Say which one you shipped.\n- **Never** leave `passkey({ origin })` unset — that hands the verifier's expected origin to the caller (Trap 9).\n- **Never** transcribe a plugin migration from memory or a blog — read the **installed** package's schema; the two sites are on different versions (Trap 11).\n- **Apply the remote D1 migration BEFORE the code deploys**, and prove it with `PRAGMA table_info` on `--remote`. Plugin code writes these tables on first use.\n- **Never** claim an auth feature works from a green route check. Schema present + route reachable ≠ a write succeeds ≠ the iOS ceremony completes. Name which of the three you verified.\n- **Never** widen 2FA's advertised scope past `\u002Fsign-in\u002Femail` — magic link, email code, Apple, Google and passkey are not second-factored (Trap 10).\n- **Never** hand-roll the Apple client secret or the Apple setup steps — route through `siwa` (`siwa portal` → `domain-file` → `secret` → `probe` → `verify`), and treat `siwa probe`'s `invalid_grant` as the PASS. Keep `betterauth` read-only; `siwa` owns the writes.\n- **Never** let the session gate swallow `\u002F.well-known\u002F` — Apple's domain verification fetches it unauthenticated, and a 302 there fails silently.\n- **Never** trust a Python-based auth health check that reports a failure until you have re-run the same URL through `curl` (Cloudflare 403s the default urllib UA), and never detect a provider button by substring — `-apple-system` in the font stack makes `\"apple\" in html` a check that cannot fail.\n",{"name":5,"description":7},"main","e7b39d448c7d905feed2b044d3ccdf60822596ab","skills\u002Fbetterauth",0,"https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter","https:\u002F\u002Fgithub.com\u002Fbarkleesanders","barkleesanders.com","Stay Hungry, Stay Foolish","2026-11-06 08:47:06",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add barkleesanders\u002Fclaude-code-starter --skill betterauth",{"tool":39,"command":40},"bunx","bunx skills add barkleesanders\u002Fclaude-code-starter --skill betterauth",{"tool":42,"command":43},"pnpm","pnpm dlx skills add barkleesanders\u002Fclaude-code-starter --skill betterauth","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fbetterauth\u002FSKILL.md",true,[],[48,54,61,68,75,82],{"skillNo":49,"name":50,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7AWV75B37B6YKG7ZKGZ783F","zi-search","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fzi-search\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7AWTZA3JGK1T7V1HS543FG7","visualise","Render inline interactive visuals — SVG diagrams, HTML widgets, charts, and explainers — directly in the conversation. Use this skill whenever the user asks to visualize, diagram, chart, illustrate, or explain something visually, or when an explanation would genuinely benefit from a spatial\u002Finteractive diagram rather than text. Also triggers for: flowcharts, architecture diagrams, data visualizations, interactive explainers, comparison layouts, UI mockups, and any request containing 'show me', 'draw', 'map out', 'visualize', or 'diagram'. Even when the user doesn't explicitly ask for a visual, use this skill proactively when the topic has spatial, sequential, or systemic relationships that a diagram would clarify better than prose.","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fvisualise\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7AWTR056C3P9R3VS8YVM2WX","video","When the user wants to create, generate, or produce video content using AI tools or programmatic frameworks. Also use when the user mentions 'video production,' 'AI video,' 'Remotion,' 'Hyperframes,' 'HeyGen,' 'Synthesia,' 'Veo,' 'Runway,' 'Kling,' 'Pika,' 'video generation,' 'AI avatar,' 'talking head video,' 'programmatic video,' 'video template,' 'explainer video,' 'product demo video,' 'video pipeline,' or 'make me a video.' Use this for video creation, generation, and production workflows. For video content strategy and what to post, see social-content. For paid video ad creative, see ad-creative.","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fvideo\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7AWTHTWBMTYZPMHHEYX3TTG","manim-video","Production pipeline for mathematical and technical animations using Manim Community Edition. Creates 3Blue1Brown-style explainer videos, algorithm visualizations, equation derivations, architecture diagrams, and data stories. Use when users request: animated explanations, math animations, concept visualizations, algorithm walkthroughs, technical explainers, 3Blue1Brown style videos, or any programmatic animation with geometric\u002Fmathematical content.","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fvideo-use\u002Fskills\u002Fmanim-video\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7AWTCXDJ9NWFQW51ENM8A2Z","video-use","Edit any video by conversation. Transcribe, cut, color grade, generate overlay animations, burn subtitles — for talking heads, montages, tutorials, travel, interviews. No presets, no menus. Ask questions, confirm the plan, execute, iterate, persist. Production-correctness rules are hard; everything else is artistic freedom.","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fvideo-use\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7AWTA1D5FP895S33GHSA2G5","ui-improver","https:\u002F\u002Fgithub.com\u002Fbarkleesanders\u002Fclaude-code-starter\u002Fblob\u002Fmain\u002Fskills\u002Fui-improver\u002FSKILL.md",[],[]]