Commit Graph
247 Commits
Author SHA1 Message Date
Moheeb Zara 3703c2a76c docs: HANDOFF pass-54 — 046 deployed (run 26125372468), smoke clean 2026-05-19 14:08:56 -07:00
Moheeb Zara c00c82d796 docs: HANDOFF pass-54 — deferred RLS status-gate lifted (046), harness-proven, needs deploy 2026-05-19 14:04:55 -07:00
Moheeb Zara e954b08232 fix(rls): status-gate user_has_role_in_space + user_has_permission (046)
Lifts the deliberately-deferred SECURITY DEFINER status-gate. The
deferral's blocking reason ('no way to verify it breaks nothing') is
resolved by the integration harness, so the gap is now closed at the
RLS layer too (defense-in-depth beyond D2's app layer): an unverified/
inactive member can no longer exercise a role or permission via direct
PostgREST. Scoped to the two privilege entrypoints; get_user_space_ids
+ user_effective_roles deliberately untouched so unverified self-reads/
onboarding still work. Migration 046 + schema.sql mirror. New
integration test (5) proves both halves: gap closed AND
current/late/approval/unverified-reads all unbroken. 31 integration
tests green; default pnpm test 532/26 hermetic; build clean.
2026-05-19 14:04:31 -07:00
Moheeb Zara ee7f59f1f4 docs: fix ARCHITECTURE limitation #2 (Stripe IS integrated) + HANDOFF pass-53 (F4, 26 integration tests) 2026-05-19 13:26:46 -07:00
Moheeb Zara b56ef4e47c test(integration): Stripe webhook route handler end-to-end (F4)
Covers the biggest untested orchestration (where the Phase-3 P0s + the
deeper-audit D5 bug lived): real signature verify (good/bad/missing),
per-space vault secret+config resolution, stripe_webhook_events replay
idempotency, applySubscription -> member_billing upsert +
space_members status, and the D5 out-of-order monotonic guard proven
end-to-end (a stale event does NOT rewind current_period_end). Invokes
the actual POST handler against local Supabase with Stripe-signed
events (customer.subscription.updated -> no network, no payments enum).
26 integration tests green; default pnpm test 532/26 hermetic; build
clean. Non-runtime.
2026-05-19 13:26:00 -07:00
Moheeb Zara b0267bbfb6 docs: HANDOFF pass-53 state — harness pushed (run 26122719148) + F3 extension (21 integration tests) 2026-05-19 13:20:01 -07:00
Moheeb Zara 42f6509ba8 test(integration): billing + notification idempotency invariants (F3)
Extends the harness to the money/notification replay invariants
(previously only asserted by app code / manual audit):
- stripe_webhook_events PK -> a retried Stripe event id is rejected
  (replay protection).
- member_billing UNIQUE(space_id,member_id) -> the webhook's
  onConflict upsert never duplicates a member's billing row.
- notifications UNIQUE(space_id,dedupe_key) + ON CONFLICT DO NOTHING
  -> a replayed enqueue collapses to exactly one outbox row.
21 integration tests green on real Postgres; default pnpm test
unaffected (hermetic); build clean. Non-runtime.
2026-05-19 13:19:35 -07:00
Moheeb Zara 6403220c92 test(integration): DB-backed harness validating shipped SQL (045/042/044/043)
Root-cause fix for 'correctness depended on post-deploy manual audits'.
Separate psql-driven suite (pnpm test:integration, own vitest config,
integration/ outside __tests__ so the hermetic pnpm test gate is
untouched; self-skips without a DB). 18 tests run against real Postgres:
- 045 class_signup_tx/class_cancel_tx: RETURNS TABLE->array shape the
  actions destructure, capacity/waitlist/dedupe, and the per-session
  advisory lock under TWO concurrent connections (D11 proven, never
  over-enrolls).
- 042 equipment exclusion constraint (overlap 23P01; cancelled/adjacent
  ok). 044 self-change trigger (role + payment cols blocked; service
  bypass). 043 members_update WITH CHECK (cross-space move blocked).
Disproves the pass-52 flagged risk (signup rpc-shape). Non-runtime;
default pnpm test still 532/26 hermetic; build clean.
2026-05-19 13:01:16 -07:00
Moheeb Zara c2f5f2a726 docs: HANDOFF pass-52 — E1-E3 deployed (run 26088940576), smoke clean 2026-05-19 02:38:28 -07:00
Moheeb Zara 099a103ed5 docs: HANDOFF pass-52 — E1-E3 hardening + evidence-based SECURITY DEFINER deferral 2026-05-19 02:14:39 -07:00
Moheeb Zara 6b84b091e4 fix(stripe): generic webhook error responses, detail logged server-side (E3, P2)
The webhook returned raw signature-lib / Postgres error text to the
caller (signature verify is reachable unauthenticated). Now returns
generic 'Invalid signature' / 'Webhook processing error' / 'Webhook
handler error'; the real detail is console.error'd server-side so
debuggability is kept. Stripe only acts on the HTTP status. 532 tests.
2026-05-19 02:13:59 -07:00
Moheeb Zara 9351969c96 fix(forms): resolve duplicate const h redeclaration in submitForm
The E2 rate-limit block (f11f4b3) added a second `const h = await
headers()` in submitForm where one already existed near the insert,
breaking the build (redeclaration). Renamed the rate-limit one to
rlHdrs. Build green, 532 tests. (f11f4b3 was committed before its
build was verified — process miss; never deployed.)
2026-05-19 02:12:36 -07:00
Moheeb Zara f11f4b3771 fix(forms): rate-limit anonymous submitForm (E2, P2)
Anonymous, captcha-less submitForm was an unbounded DB-bloat vector.
Added a generous per-IP+form limit (20/min) — deliberately loose
because legitimate public signups at a hackerspace commonly share one
NAT/wifi IP, so a tight limit would false-block a room; this still
bounds automated flooding. Captcha (the real control) stays the
documented deferred follow-up. 532 tests.
2026-05-19 02:11:42 -07:00
Moheeb Zara c2ba9586fa fix(door): thread conn.auth_param into call + audit redaction (E1, completes D10)
D10 closed the client-facing leak; this completes the defense-in-depth
so a generic-adapter connection's custom auth-param value is also
scrubbed from the operator-readable door_access_log / callDoor reason
regardless of param name. auth_param added to ConnRow +
loadEnabledConnection + the test/selfEntry selects; threaded into every
callDoor (which already redacts reason/snippet by it) and auditDoor
gained an optional authParam. Native HeatSync (e=) was already covered;
this hardens custom generic adapters. 532 tests.
2026-05-19 02:10:20 -07:00
Moheeb Zara b90debbd37 docs: HANDOFF pass-51 — D11/D12 deployed (run 26086312156), smoke clean 2026-05-19 01:45:01 -07:00
Moheeb Zara d5a282b642 docs: HANDOFF pass-51 — D1-D10 verified (D6 regression fixed), D11/D12 deferred P1s cleared 2026-05-19 01:33:32 -07:00
Moheeb Zara 42fd3859a4 fix(door): defeat DNS-rebind by connecting to a validated resolved IP (D12)
Deferred deeper-audit P1. validateDoorTarget only string-checked the
host; a bare fetch did its own DNS resolution, so a hostname could
resolve to 127.0.0.1/169.254.169.254 between check and connect. The
executor now resolves once (dns.lookup all), rejects if ANY resolved
address is blocked (isBlockedDoorIp: loopback/unspecified/link-local/
metadata incl IPv4-mapped IPv6; RFC1918/LAN/ULA allowed since door
controllers live there), then connects to the validated IP literal so
fetch performs no second resolution (TOCTOU closed). Original Host kept
best-effort; redirect:'manual' retained. Dependency-free (no undici
seam). 33 door-logic tests; suite 532.
2026-05-19 01:33:01 -07:00
Moheeb Zara 705f03a299 fix(classes): atomic signup/cancel under per-session advisory lock (D11)
Deferred deeper-audit P1. signUpForClass (count->decide->insert) and
cancelMySignup (cancel->recount->promote) were non-atomic: concurrent
signups at the capacity boundary over-enrolled and concurrent cancels
double-promoted waitlisters (dynamic capacity can't be a DB constraint).
Migration 045 adds class_signup_tx/class_cancel_tx (SECURITY DEFINER,
pg_advisory_xact_lock per session) doing the decision+write atomically;
actions call the RPCs and keep all pre-checks. Removed the now-unused
effectiveCapacity/computeSignupStatus/pickPromotion imports +
isUniqueViolation (pure rules still live + tested in classes-logic).
528 tests; build clean.
2026-05-19 01:30:07 -07:00
Moheeb Zara 6105047ad7 fix(notifications): D6 regression — lone space must get full drain throughput
D6's pre-truncation capped every space's bucket at PER_SPACE=5 before
the round-robin, so a single-space deployment (the common single-
hackerspace case) drained only 5 emails/min instead of 20 — a 4x
slowdown introduced by the fairness fix. Fairness must bind only under
contention: per-space queues are now bounded solely by the CANDIDATES
fetch and the round-robin itself caps any one space's share when
multiple compete; a lone space drains the full BATCH again. Caught
verifying the D1-D10 batch.
2026-05-19 01:23:52 -07:00
Moheeb Zara 6568bc9c10 docs: HANDOFF pass-50 — D1-D10 deployed (run 26071186611), smoke clean 2026-05-18 18:49:39 -07:00
Moheeb Zara a7c3a08db9 docs: HANDOFF pass-50 — deeper audit + D1-D10 remediation 2026-05-18 18:45:43 -07:00
Moheeb Zara 66cb84bc57 fix(door): never return raw controller reason to the client (D10)
Every door action bubbled the executor's reason/e.message to the
client; redaction was password-literal + a fixed param-name regex, so a
generic-adapter connection with a custom auth param + verbose upstream
error could surface the secret client-side. Client returns are now a
generic 'controller call failed' message; the redacted detail still
goes to door_access_log for operators. redactDoorSecrets + callDoor
gained an optional authParam (scrub the connection's actual auth param
value regardless of name); threading conn.auth_param through the
door-call selects is a deferred defense-in-depth follow-up (client
leak is fully closed; native HeatSync e= is already regex-covered).
2026-05-18 18:44:54 -07:00
Moheeb Zara 785e8e0ef9 fix(rls): block member self-change of payment/dues columns (D9)
prevent_member_self_role_change covered role/status/space but not the
financial columns; RLS members_update lets a member UPDATE their own
row, so payment_status/dues_paid_until/last_paid_at/last_payment_at/
stripe_customer_id/payment_note/joined_at were self-settable via
PostgREST to forge a dues-good signal. Migration 044 adds them to the
blocked set; service-client (auth.uid() NULL) + privileged-on-another-
member writes still bypass (Stripe webhook unaffected). Schema + maps.
2026-05-18 18:41:35 -07:00
Moheeb Zara 26e54f1fcb fix(rls): members_update WITH CHECK mirrors USING (D8)
UPDATE policy was USING-only: a privileged caller could mutate a member
row into a space they don't administer (no post-image re-check).
Migration 043 adds the mirrored WITH CHECK. Self column escalation
(space_id/role/status) remains blocked by the trigger (D9). Schema +
DB maps updated.
2026-05-18 18:39:53 -07:00
Moheeb Zara 7b0948ddd6 fix(money): zero-decimal currency handling (D7)
Stripe sends zero-decimal currencies (JPY/KRW/VND/...) already in the
major unit; the unconditional /100 recorded a JPY dues charge 100x
understated in the ledger + receipt. minorToMajor is now currency-aware
(shared ZERO_DECIMAL_CURRENCIES/isZeroDecimalCurrency in
notifications-logic); formatMoney renders no fractional part for those.
Never fires for USD; closes silent ledger corruption for such tenants.
Tests added; suite 526+.
2026-05-18 18:38:25 -07:00
Moheeb Zara c9c0909ad7 fix(notifications): fair multi-tenant drain + re-entrancy-safe status writes (D6)
The dispatcher drained a single global FIFO (oldest 20), so one
tenant's billing burst starved every other space's email indefinitely.
Now round-robins an oldest-first candidate window across spaces with a
per-space cap (PER_SPACE=5, BATCH=20). Status writes are guarded with
.eq('status','pending') so an overlapping run can't flip a row another
run already advanced (no false 'failed' on an already-sent row).
2026-05-18 18:35:30 -07:00
Moheeb Zara d2b7aa6897 fix(stripe): never rewind billing period on out-of-order webhooks (D5)
Stripe doesn't guarantee event order. A late customer.subscription.
updated carrying an older period overwrote a newer current_period_end,
so graceExceeded flipped a paid member to 'late' and fired a false
'dues lapsed' email + access loss. applySubscription now reads the
stored period and keeps the later of stored vs incoming
(laterPeriodEnd, pure + tested); status still tracks latest sub.status
but grace is computed from the monotonic period.
2026-05-18 18:34:03 -07:00
Moheeb Zara 705a93291b fix(roles): pin assignCustomRole to the caller's space (D4)
assignCustomRole inserted {member_id, custom_role_id} with no space
check on either; the RLS WITH CHECK only validated member_id's space,
so an admin of space A could attach space B's custom role to an A
member. Now both the custom role and the target member are verified
in the caller's space before insert. (Blast radius was bounded by
downstream space re-filtering; this closes the scoping defect.)
2026-05-18 18:32:07 -07:00
Moheeb Zara 92170e44f4 fix(auth): validate /auth/callback next param against open-redirect (D3)
next was appended to origin unvalidated; next=//evil.com or /\evil.com
redirected off-site post-login. Now only a same-origin absolute path
(single leading slash, no //, no /\) is honored, else /dashboard.
2026-05-18 18:31:06 -07:00
Moheeb Zara 2239e7a92d fix(auth): unverified members cannot exercise roles; single-membership join (D2)
require_approval was silently void: redeeming an admin-role invite into
a require_approval space yielded role=admin,status=unverified and
requireMemberWithRole never checked status -> instant admin pre-approval.
- PRIVILEGE_STATUSES/isPrivilegeEligible (current|late only; excludes
  unverified/inactive). requireMemberWithRole now rejects non-privilege-
  eligible status with 'pending approval' before the role check; Member
  carries status (getAuthMember selects it). requireMember stays
  permissive so unverified members still see their own /me.
- joinSpace rejects a second active membership (single-space model;
  prevents the .single() self-DoS).
Deferred (HANDOFF): SECURITY DEFINER helpers user_has_role_in_space/
user_has_permission still ignore status (RLS defense-in-depth, own
careful pass). 524 tests; build clean.
2026-05-18 18:30:20 -07:00
Moheeb Zara a513ad0fab fix(equipment): DB-enforced reservation no-overlap (D1, P0)
reserveEquipment was check-then-insert with no DB guard: two concurrent
requests both passed the in-memory overlap check and double-booked a
machine. Migration 042 adds btree_gist + a GiST EXCLUDE constraint
(equipment_id =, tstzrange && ) WHERE status='reserved', making the DB
the arbiter; the action maps the 23P01 violation to the existing
friendly overlap message. App-side check kept as a fast pre-check.
Schema + DB maps updated.
2026-05-18 18:26:19 -07:00
Moheeb Zara 247e966446 docs: HANDOFF pass-49 — Phase 3 P0 fixes deployed (run 26068281306) 2026-05-18 17:21:48 -07:00
Moheeb Zara 997e2e1366 docs: HANDOFF pass-49 — Phase 3 post-deploy audit, 2 P0 fixed (deploy ASAP) 2026-05-18 17:01:47 -07:00
Moheeb Zara f2df287b35 fix(security): Phase 3 post-deploy audit — 2 P0 + P1 + P2 (R5)
Independent adversarial audit verdict was NOT SAFE; fixed:
- P0-1 /auth/confirm no longer trusts the query `type` (pinned to
  'email_change'); a public endpoint feeding an attacker-chosen OTP
  type into verifyOtp was an unintended auth entrypoint.
- P0-2 email sync uses the verifyOtp response user, not a follow-up
  getUser() that may not reflect the just-verified identity; /me now
  reconciles space_members.email against the authoritative auth email
  on load, so a missed sync self-heals (no permanent stale email).
- P1-1 requestEmailChange builds the confirm origin from
  NEXT_PUBLIC_APP_URL only, never request headers (forged Host could
  redirect the confirmation link / capture token_hash).
- P2-1 isSecretConfigField also catches password/token/private_key/
  *_token/*_password so non-conventionally-named credentials can't be
  stored in plaintext integrations.config.
521 tests; build clean.
2026-05-18 17:01:25 -07:00
Moheeb Zara c8842c3f75 docs: HANDOFF pass-48 — Phase 3 deployed (run 26066604148), smoke clean 2026-05-18 16:34:28 -07:00
Moheeb Zara 83ff54b17c docs: Phase 3 portal — API_REFERENCE, ARCHITECTURE, DEPLOYMENT (email-change config), HANDOFF pass-48 (P3f) 2026-05-18 15:55:20 -07:00
Moheeb Zara 5edd778cf6 feat(me): self-service email change, verified (P3e)
requestEmailChange -> supabase.auth.updateUser({email},{emailRedirectTo
/auth/confirm}); with Secure email change on (recommended) Supabase
double-confirms old+new. New /auth/confirm route verifyOtp(email_change)
then syncs the denormalized space_members.email to the authoritative
auth email ONLY post-verification (idempotent). proxy.ts whitelists
/auth/confirm (exact). Profile-tab UI shows current email + change
control. REQUIRES Supabase config (template -> /auth/confirm?token_hash=
{{ .TokenHash }}&type=email_change + redirect allowlist) — documented in
P3f. 521 tests; build clean (flow not exercisable without that config).
2026-05-18 15:53:39 -07:00
Moheeb Zara 2c847befeb feat(me): my-payments self-view in the Membership tab (P3d)
New getMyPayments: payments SELECT is treasurer-scoped (RLS), so the
self-view uses the validated service client strictly scoped to the
caller's space_id + member_id (same convention as getMyBilling /
getMyNotifications). Read-only list (amount, date, platform, status)
in the Membership tab. Docs updated. 521 tests; build clean.
2026-05-18 15:50:34 -07:00
Moheeb Zara 6189e2023d feat(me): self-serve cancel for class signups + reservations (P3c)
Activity tab: confirm-dialog Cancel on registered/waitlisted class
signups (cancelMySignup) and reserved equipment reservations
(cancelReservation) via the existing actions. Reusable CancelAction
(AlertDialog + toast + refresh). Buttons only shown on cancellable
states; the actions still enforce ownership/space scoping server-side.
521 tests; build clean (UI not browser-tested from here).
2026-05-18 15:48:24 -07:00
Moheeb Zara ef210c9fe5 feat(me): inline profile editing in the Profile tab (P3b)
Wires existing updateMyProfile + discloseAffiliations into an editable
form (name, handle, phone, bio, skills, interests, willing-to,
affiliations). Affiliations re-disclosed only when changed so the COI
timestamp is not reset on every save. Added bio to the updateMyProfile
param type (schema + column already supported it). 521 tests; build
clean (UI not browser-tested from here).
2026-05-18 15:46:15 -07:00
Moheeb Zara 5a7283266c refactor(me): tabbed member portal shell — Profile/Membership/Activity (P3a)
/me restructured into a 3-tab portal (Tabs primitive): Profile
(permissions), Membership (dues + certifications), Activity
(notifications, classes, reservations, cards, visits). Server page
keeps all data fetching; sections moved verbatim into a client portal
component. No behavior change; sets the frame for P3b-e. 521 tests.
2026-05-18 15:44:06 -07:00
Moheeb Zara 0e54a0c7cd docs: HANDOFF pass-47 — full-codebase audit + P1 remediation (R1-R4) 2026-05-18 13:15:00 -07:00
Moheeb Zara b8edd77ee0 fix(security): scope proxy public routes to exact paths (R4)
/auth -> /auth/callback and /api/cron -> /api/cron/notifications.
Both prefixes whitelisted more than the single route that needs
anonymity; a future /auth/* page or /api/cron/* job would have been
silently public. Verified those are the only routes under each.
2026-05-18 13:14:16 -07:00
Moheeb Zara 75686c04f0 refactor(paypal): extract + unit-test sync mapping; reuse auth helper (R3)
PayPal transaction filter + payments mapping + external-id dedupe were
inline and untested, and auth was a hand-rolled select instead of the
shared helper. Extracted to pure lib/paypal-logic.ts (also fixes a
latent throw on a missing/invalid PayPal date by falling back to now);
route now uses requireMemberWithRole. 7 tests; suite 521. Behavior
otherwise unchanged.
2026-05-18 13:13:16 -07:00
Moheeb Zara 0306157a60 refactor(stripe): extract + unit-test webhook decision logic (R2)
The webhook's money/status mapping (Basil field relocations, period
extraction, customer-id unwrap, status patch, invoice->payment row,
minor->major) lived inline in the route with zero test coverage - the
biggest untested critical path in the codebase. Extracted to a pure,
SDK-free lib/stripe/webhook-logic.ts (structural input types) and
refactored the route to only do signature verify + network + DB writes.
12 new tests cover the Basil edges and link/unlink + defaults. Behavior
unchanged; suite 514.
2026-05-18 13:11:09 -07:00
Moheeb Zara 504586fdcd fix(security): vault integration secrets instead of plaintext config (R1)
PayPal client_secret (and any secret-named integration field) was stored
plaintext in integrations.config, unlike Stripe/door which use the
AES-256-GCM vault. A DB read or backup leaked it in cleartext.

- lib/secrets/vault.ts: canonical generic storeSecret/readSecret +
  isSecretConfigField (the proven Stripe vault logic, generalized).
- saveIntegration: secret-named fields go to the vault, only a *_ref is
  kept in config; blank submit preserves the ref (write-only like
  Stripe); legacy plaintext auto-migrates into the vault on next save.
- paypal/sync reads client_secret from the vault, transitional fallback
  to legacy plaintext until the next save.
- Docs updated (API_REFERENCE, ARCHITECTURE 10.3). 502 tests.
2026-05-18 13:08:17 -07:00
Moheeb Zara 7844c262f8 docs: HANDOFF pass-46 — Phase 2 deployed (run 25990457904), smoke clean 2026-05-17 05:12:09 -07:00
Moheeb Zara f1bae44afd fix(notifications): P2 extreme-audit P1 fixes before deploy
Independent audit verdict was NOT SAFE; all findings fixed:
- dispatcher Idempotency-Key is now per-attempt (${id}:${attempts}),
  not row id alone, so a transient-failure response cached by Resend
  cannot permanently suppress every retry and silently lose an email.
- enqueueDues is fully try/catch wrapped so a notifications-table or
  render failure can never throw into / wedge the Stripe money path.
- dues_lapsed dedupe falls back to the subscription id when periodEnd
  is null (canceled/deleted subs), so future lapses no longer collapse
  to one key and get suppressed. New test; suite 499.
- documented the dispatcher's once/min concurrency assumption.
2026-05-17 05:06:02 -07:00
Moheeb Zara 7eb83676e7 feat(notifications): P2e member self-view on /me + docs
getMyNotifications (service-client self-view, mirrors getMyBilling) +
a read-only Notifications section on /me. Docs updated in the same
change: ARCHITECTURE (Phase 2 subsystem + limitation #5), API_REFERENCE
(notifications section, fixed the stale no-auth-middleware claim),
DATABASE_SCHEMA + DB_SCHEMA_MAP (migration 041 + table), DEPLOYMENT
(env vars + dispatcher crontab), HANDOFF pass-45.
2026-05-17 04:58:46 -07:00
Moheeb Zara 75097a601c feat(notifications): P2d dispatcher cron route
POST /api/cron/notifications drains <=20 pending rows/min, sends via the
transport with the row id as Resend Idempotency-Key (overlap-safe),
marks sent or increments attempts (retryable -> stay pending, permanent
or budget-exhausted -> failed). Constant-time CRON_SECRET bearer check;
503 when unset. ~4.5/s spacing under Resend's 5/s limit. proxy.ts
whitelists /api/cron (no session; own shared secret). CRON_SECRET added
to .env.example.
2026-05-17 04:54:11 -07:00