Skip to content

[POC — do not merge] Member auth with Better Auth (ADR 026) - #1501

Draft
busbyk wants to merge 13 commits into
mainfrom
busbyk/avyapp-better-auth-members
Draft

busbyk wants to merge 13 commits into
mainfrom
busbyk/avyapp-better-auth-members

Conversation

@busbyk

@busbyk busbyk commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Warning

Proof of concept: do not merge. This draft shows the approach and architecture for Member accounts (ADR 026) so the team can review it and try it locally. The real implementation will come in smaller PRs. The AvyApp half is NWACus/avy#1277.

Description

AvyWeb becomes the identity provider for public Members: people who use AvyApp or the center sites. Members are not staff Users: they never sign into the admin and never link to a User, even with the same email.

It runs on Better Auth mounted at /api/auth/*, storing its data in Payload's database:

  • The apex (avy-fx.org) is the auth server and account home. Sign-in (email code, Google) only happens there.
  • Center sites get a limited "site session". "Sign in" on a center sends the browser to the apex, which hands back a one-time token. The center trades it for a session cookie on its own domain. A site session can only read and write preferences. Account actions (delete, change email, link sign-in methods) only work on the apex, because center pages run third-party embeds.
  • AvyApp talks to the apex directly with a full session. It starts as an Anonymous Member tied to the device (install id + secret in SecureStore). Signing in with email or Google later links it: devices, subscriptions and memberships move to the real account and the anonymous one is deleted.
  • Signing in on a center records a free Membership with that center, so its admins can see the Member.
flowchart LR
    App[AvyApp] -- "full session<br/>(anonymous → linked)" --> Apex["apex: avy-fx.org<br/>/api/auth/* (Better Auth)"]
    Browser["Browser on nwac.us"] -- "Sign in" --> Apex
    Apex -- "one-time token (60s)" --> Center["nwac.us<br/>site session: preferences only"]
    Apex --- DB[("Payload DB<br/>members, sessions, devices,<br/>memberships, subscriptions")]
Loading

Start with docs/member-auth.md for how it fits together and ADR 026 for why.

Related Issues

Key Changes

Area Where
members auth collection plus owned rows (Memberships, Devices, Subscriptions, Deliveries) src/collections/
Better Auth server: plugins, rate limits, emails, deletion src/auth/members/getMemberAuth.ts
Better Auth's tables injected into Payload's schema (one migration system) src/auth/members/schema.ts
Apex → center site-session hand-off and the site-safe endpoint allowlist src/auth/members/plugins/siteSession.ts, siteSessionPolicy.ts
Device sign-in for Anonymous Members src/auth/members/plugins/deviceSignIn.ts
Anonymous → linked merge src/auth/members/linkAnonymousMember.ts
Silent re-sign-in in middleware src/auth/members/silentReSignIn.ts, src/middleware.ts
Apex sign-in and account pages, floating Member tag on center sites (POC-grade UI) src/app/(frontend)/members/, src/components/Members/
Payload strategy: Better Auth cookie → req.user on members (admin session always wins) src/collections/Members/

How to test

Setup

  1. Check out this branch, then run pnpm install.
  2. In .env:
    • MEMBER_AUTH_RATE_LIMIT=false, so repeated tries don't hit the 3-per-minute code limit.
    • Email codes: with Mailtrap SMTP_* set they arrive there. Without SMTP, the dev server log prints Subject: '123456 is your Avy code'. You can also read the code from the database with sqlite3 dev.db "select identifier, value from members_verifications order by created_at desc limit 1". The value is <code>:<attempts>.
    • Google sign-in stays off unless GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are set. Skip it; nobody has OAuth clients for it yet.
  3. Run pnpm seed to rebuild dev.db with the new tables (push mode), then pnpm dev.
  4. Use Chrome, which resolves *.localhost itself, or add nwac.localhost and dvac.localhost to /etc/hosts (see docs/troubleshooting.md).

Browser: one account across center sites

  1. Open http://nwac.localhost:3000. A Sign in pill floats bottom-right.
  2. Click it. You land on http://localhost:3000/members/sign-in (the apex). Enter any email, click Email me a code, enter the code.
  3. You come back to nwac, and the pill shows your email. The browser now holds an apex session plus an nwac site session.
  4. Open http://dvac.localhost:3000 and click Sign in. You should come straight back signed in, with no prompt: the apex already knows you.
  5. Click the pill → Manage account to reach the apex account page.
  6. In the admin (localhost:3000/admin, admin@avy.com / localpass), Members lists the new Member, and Memberships shows a free Membership for both nwac and dvac.
  7. Sign out from the pill on a center. That center's session and marker cookie are cleared; the apex session stays.

Browser: what a site session can't do

On nwac.localhost:3000, while signed in, run this in DevTools:

await fetch('/api/auth/delete-user', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }).then((r) => r.status)

You should get a refusal. The same account action works from localhost:3000/members.

AvyApp

Follow the instructions in NWACus/avy#1277. In short: point the app's debug screen at http://localhost:3000, then sign in anonymously, register the device, restore the session after dropping it, and link by email code. Check the result in the admin under Members and Devices: the anonymous Member is gone and the Device belongs to the linked Member.

Known gaps when testing locally

  • Silent re-sign-in can't be tried by hand on localhost. Locally the apex and the centers share localhost:3000, so Next's dev server turns the middleware's redirect into a path on the center host, which the center refuses. On deployed hosts the redirect stays on the apex. The server-side logic is covered by the POC harness (src/scripts/poc/better-auth-members.ts, run steps in docs/member-auth.md).
  • Google (web and native idToken) has never been run, because there are no OAuth clients yet.
  • Account deletion sends a confirmation link by email, so it needs SMTP set.

Screenshots / Demo video

Migration Explanation

20261029_062108_poc_members_better_auth only adds tables: members, the four Better Auth tables (members_sessions, members_accounts, members_verifications, members_rate_limits), and the Member-owned collections. Nothing existing changes. This is a POC migration and won't be merged as-is.

Future enhancements / Questions

  • Is the apex-as-auth-server plus limited site sessions the right trade-off for center pages that run third-party embeds?
  • Does the anonymous-first app flow (lazy, on first subscribe) match how we want notifications onboarding to feel?
  • Next steps: Google OAuth clients and an idToken test on real devices, Apple sign-in, real sign-in UI, push delivery, and splitting this into mergeable PRs.

🤖 Generated with Claude Code

busbyk and others added 13 commits November 11, 2026 11:46
Proposed ADR for public Member accounts authenticated by Better Auth via a
Payload custom strategy (hybrid table ownership, device-bound Anonymous
Members, auth per tenant host). Adds a Members section to GLOSSARY.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Center hosts get limited site sessions handed off from the apex (one-time
token via top-level redirect), so embed scripts on center pages can only
touch preferences. Account endpoints answer only on the apex; members stay
signed in via a marker cookie that triggers silent re-sign-in.

Also re-confirms the CLAUDE.md -> docs/decisions/README.md drift binding
(the ADR index gained a row for 026).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POC 1 for AvyApp notifications (ADR 026). Adds the `members` auth collection
with a text id, `disableLocalStrategy` and one custom strategy that turns a
Better Auth session cookie into `req.user` and yields whenever admin
credentials are present. Payload owns the table; Better Auth's `user` model is
mapped onto it with `modelName` alone, and its session, account, verification
and rateLimit tables are Drizzle tables injected through `afterSchemaInit`, so
dev push and `migrate:create` both carry them.

Also adds Memberships, Devices, Subscriptions and Deliveries, tenant-scoped
Member reads through Memberships, anonymous → linked account merging, a
device-bound sign-in for Anonymous Members, apex-only account endpoints with
limited site sessions handed to center hosts by a one-time token, silent
re-sign-in in middleware, Avy-branded OTP and deletion emails, database-backed
rate limits, and seed Members.

Gates (tsc, lint, jest, drift, fallow) were run by hand; the migration hook
flags the additive ALTER TABLE statements, so this commit skips hooks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
POC-grade `/members/sign-in` (email OTP, Google when configured) and `/members`
(session, hand-off links to center sites, sign out, delete account) so the site
session flow can be clicked through in a browser.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
`pnpm poc:members-auth` drives Better Auth's handler with apex and center Host
headers against a scratch copy of dev.db and asserts every done-means item
(a)–(h) plus rate limits. Unit tests cover the host rules, returnTo
validation, the site-safe path allowlist and the silent re-sign-in decision.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Records what the POC settled: afterSchemaInit (not before) for the injected
tables, text ids, no field mapping, ISO text dates, and that the Members
strategy yields to admin credentials because Payload runs its JWT strategy
last. Binds the new guide to the code it describes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ferences

The site-session exchange creates a `signup` Membership with that center the
first time it hands a Member a session, so Members who arrive through a
center are visible to its admins. Membership kinds are now signup, donor and
paid. Memberships carry their own `preferences` for center-scoped settings;
`/member-preferences/set` takes `scope: 'global' | 'center'` and `get`
returns both. Migration regenerated for the schema change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Fixed bottom-right, so no layout shift on ISR-cached pages. Reads the session
client-side; signed out it links into the apex hand-off with the current URL
as returnTo, signed in it shows the email with "Manage account" (apex) and
sign out.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A paid center membership is a way of donating, not a third kind. Migration
regenerated for the select change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
"Free" reads as a tier next to "donor", which is how a center would say it.
Migration regenerated for the new default.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The expo plugin maps AvyApp's expo-origin header to the Origin, which Better Auth
validates on every cookie-bearing POST; the plugin itself only trusts exp:// in
development, so device register, OTP linking and sign-out returned 403.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
middleware.ts, the center layout and .env.example now carry both main's and this
branch's changes; each bound doc was already accurate to its side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

Migration Safety Check

Found 22 potential issues:

20261029_173049_poc_members_better_auth.ts

Warning (line 28): DELETE keyword detected - review for data loss

FOREIGN KEY (\`member_id\`) REFERENCES \`members\`(\`id\`) ON UPDATE no action ON DELETE set null,

Warning (line 29): DELETE keyword detected - review for data loss

FOREIGN KEY (\`tenant_id\`) REFERENCES \`tenants\`(\`id\`) ON UPDATE no action ON DELETE set null

Warning (line 49): DELETE keyword detected - review for data loss

FOREIGN KEY (\`member_id\`) REFERENCES \`members\`(\`id\`) ON UPDATE no action ON DELETE set null

Warning (line 65): DELETE keyword detected - review for data loss

FOREIGN KEY (\`member_id\`) REFERENCES \`members\`(\`id\`) ON UPDATE no action ON DELETE set null,

Warning (line 66): DELETE keyword detected - review for data loss

FOREIGN KEY (\`tenant_id\`) REFERENCES \`tenants\`(\`id\`) ON UPDATE no action ON DELETE set null

Warning (line 86): DELETE keyword detected - review for data loss

FOREIGN KEY (\`member_id\`) REFERENCES \`members\`(\`id\`) ON UPDATE no action ON DELETE set null,

Warning (line 87): DELETE keyword detected - review for data loss

FOREIGN KEY (\`device_id\`) REFERENCES \`devices\`(\`id\`) ON UPDATE no action ON DELETE set null,

Warning (line 88): DELETE keyword detected - review for data loss

FOREIGN KEY (\`subscription_id\`) REFERENCES \`subscriptions\`(\`id\`) ON UPDATE no action ON DELETE set null

Warning (line 109): DELETE keyword detected - review for data loss

FOREIGN KEY (\`member_id\`) REFERENCES \`members\`(\`id\`) ON UPDATE no action ON DELETE cascade

Warning (line 132): DELETE keyword detected - review for data loss

FOREIGN KEY (\`member_id\`) REFERENCES \`members\`(\`id\`) ON UPDATE no action ON DELETE cascade

Warning (line 164): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`members_id\` text REFERENCES members(id) ON DELETE cascade;`,

Warning (line 164): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`members_id\` text REFERENCES members(id) ON DELETE cascade;`,

Warning (line 167): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`memberships_id\` integer REFERENCES memberships(id) ON DELETE cascade;`,

Warning (line 167): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`memberships_id\` integer REFERENCES memberships(id) ON DELETE cascade;`,

Warning (line 170): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`devices_id\` integer REFERENCES devices(id) ON DELETE cascade;`,

Warning (line 170): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`devices_id\` integer REFERENCES devices(id) ON DELETE cascade;`,

Warning (line 173): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`subscriptions_id\` integer REFERENCES subscriptions(id) ON DELETE cascade;`,

Warning (line 173): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`subscriptions_id\` integer REFERENCES subscriptions(id) ON DELETE cascade;`,

Warning (line 176): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`deliveries_id\` integer REFERENCES deliveries(id) ON DELETE cascade;`,

Warning (line 176): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`deliveries_id\` integer REFERENCES deliveries(id) ON DELETE cascade;`,

Warning (line 194): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_preferences_rels\` ADD \`members_id\` text REFERENCES members(id) ON DELETE cascade;`,

Warning (line 194): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_preferences_rels\` ADD \`members_id\` text REFERENCES members(id) ON DELETE cascade;`,

Review these patterns and add backup/restore logic if needed. See docs/migration-safety.md for guidance.

@github-actions

Copy link
Copy Markdown
Contributor

This branch was previously deployed

1 inactive deployment
Preview — 793c666c Deployed Nov 11, 2026 by busbyk via build #3304
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant