5 Commits

Author SHA1 Message Date
27afda74f1 feat(fase-13): admin UI + sidebar entry + isServerAdmin store + e2e SA-01..04
13.3 admin UI:
  - (admin) route group with own layout + red banner + sidebar (Collectives,
    Admins, Audit log, Server). +layout.ts is client-rendered (ssr=false),
    same rationale as the (app) group.
  - /admin/collectives — paginated list via admin_list_collectives, search
    by name, soft-delete / restore / hard-delete modals (hard-delete needs
    explicit checkbox; force toggle bypasses the 30-day wait server-side).
  - /admin/collectives/[id] — members list with kick action; recent actions
    for the collective filtered from admin_actions.
  - /admin/admins — list via server_admins join to users (disambiguated by
    FK name — there are TWO FKs to users so the embed needs the explicit
    server_admins_user_id_fkey); promote modal does an email lookup; revoke
    button is replaced by "you (cannot revoke yourself while sole admin)"
    when applicable.
  - /admin/audit — paginated feed (default 50), action filter.
  - /admin/server — server-layer default-section toggles backed by
    admin_set_default_section + the new admin_clear_default_section RPC
    (added because patching the JSONB to `true` is NOT equivalent to "no
    opinion" — `true` explicitly overrides a collective OFF).

13.4 sidebar/drawer entry:
  - $isServerAdmin store (writable; +$isServerAdminLoaded for the gate
    race) refreshed on every onAuthStateChange in root layout, cleared on
    sign-out. Cached so the sidebar tile is synchronous.
  - DesktopSidebar + MobileDrawer render the entry only when the store is
    true. Distinct red icon so it never blends with normal nav.

Stores wiring:
  - features.ts gains serverSectionDefaults writable + enabledSections
    derived now reads server > collective > user > default. Loader
    piggybacks on loadCurrentUserFeatures so the server layer is fetched
    once per sign-in.
  - serverAdmin.ts new module — refreshServerAdminFlag() + clearServerAdminFlag().
  - Tracks isServerAdminLoaded so the (admin) layout doesn't redirect away
    during the millisecond between SIGNED_IN and the RPC resolving (caught
    empirically — every hard-load to /admin/* bounced to / without it).

13.5 tests:
  - admin.test.ts (SA-01..SA-04) with new loginAsAdmin fixture. Ana is the
    seed admin (server_admins seeded via supabase/seed.sql).
  - SA-04 + SV-02 reset their server-layer JSONB via the new
    admin_clear_default_section RPC so the suites don't leak state into
    each other.

Migration 025 adds admin_clear_default_section(text) — same SECURITY DEFINER
+ audit pattern as the rest. pgTAP 017 updated (23 plans, AR-T13b + the
SECURITY DEFINER list now includes the clear RPC).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 05:30:56 +02:00
f5c8cb68be feat(fase-7): collective-flow E2E coverage + fix 3 latent bugs
12 new Playwright tests closing the UI coverage gap in the collective
lifecycle (onboarding → invitation → admin manage). Writing them surfaced
three product-code bugs that have silently been present since Fase 1;
fixed as part of this phase.

Tests:
- tests/e2e/onboarding.test.ts       O-01..O-03 (Eva auto-redirect, happy
                                     path create, empty-name submit-disabled)
- tests/e2e/invitation.test.ts       I-01..I-05 (token generation, accept
                                     logged-out + logged-in, expired, used)
- tests/e2e/manage-collective.test.ts MC-02..MC-05 (promote, demote, remove
                                     member, generate pending invite)
- tests/fixtures/db.ts               resetEva, seedExpiredInvitation,
                                     seedUsedInvitation, restoreSeedMembership,
                                     countMembership — all via raw SQL so they
                                     don't depend on SUPABASE_SERVICE_ROLE_KEY

Bugs found & fixed:
- supabase/migrations/012_create_collective_rpc.sql: atomic
  `create_collective(name, emoji)` SECURITY DEFINER RPC. Fase 1 onboarding
  used `.insert(...).select().single()` which triggers the SELECT policy on
  the fresh row — creator isn't a member yet, so the INSERT was rejected with
  "row-level security" even though the INSERT policy passed. onboarding now
  calls the RPC which inserts both the collective AND the creator-as-admin
  membership in one transaction, bypassing RLS. F-08 in rls-isolation.test.ts
  has been silently masking this bug (only the spoof branch was asserted).

- routes/+layout.svelte: post-login redirect now reads sessionStorage
  `pendingInvitationToken` and routes back to /invitation/<token> instead of
  defaulting to /onboarding or /lists. The invitation page already stashed
  the token before kicking off Keycloak, but nothing read it back.

- routes/(app)/collective/manage/+page.svelte: loadMembers now subscribes
  to currentCollective so it re-runs when the store resolves after cold
  navigation. onMount alone races with the auth listener's first emit and
  the member list stayed empty on direct URL hits.

- routes/invitation/[token]/+page.svelte: awaits authLoading before deciding
  whether to redirect to login. Previously raced with the auth listener and
  triggered a redundant Keycloak round-trip for freshly-authenticated users.

Stable selectors added (Playwright):
- Onboarding: onboarding-create-tab, onboarding-join-tab,
  collective-name-input, collective-submit
- Manage: member-row-<uid>, role-select-<uid>, remove-member-<uid>,
  generate-invite, invite-link
- Invitation: invitation-accept, invitation-error (+ data-error-key attr)

Scope dropped from the plan — UI does not exist, would be feature work:
- O-04: "+ new collective" affordance in the sidebar.
- MC-01: rename-collective input in /collective/manage.
Both flagged as follow-ups in plan/fase-7-collective-flow-tests.md.

Test totals: 34 pgTAP + 140 Vitest integration + 15 Vitest unit + 58
Playwright + 1 gated rate-limit. 3 skipped (2 Realtime presence, 1 gated).
2026-04-14 22:33:33 +02:00
a86b296ecd fix(e2e): pin Playwright baseURL to localhost regardless of PUBLIC_APP_URL
Root cause of the recurring "just test-all shows 27/16, playwright alone
shows 43/0" split:

  Justfile loads .env with dotenv-load, which sets PUBLIC_APP_URL to the
  LAN IP from the phone-preview config. playwright.config.ts was reading
  that env and using it as baseURL. The resulting LAN-IP OAuth round-trip
  (browser → GoTrue → Keycloak → browser) adds ~hundreds of ms of
  loopback routing per hop and pushes the $currentCollective hydration
  past Playwright's first synthetic keystroke, producing a silent early
  return in handleAdd (name typed but Enter never triggers a write).

  Running playwright directly skipped dotenv-load, baseURL fell back to
  localhost, and everything passed. Same code, same machine, different
  wrapper.

Fix
  apps/web/playwright.config.ts: baseURL hardcoded to 'http://localhost:5173'.
    The LAN IP stays in PUBLIC_APP_URL for on-device phone previews (step
    2/3 of the mobile-testing recipe in CLAUDE.md), but e2e always hits
    the loopback so the timing profile is deterministic.
  apps/web/tests/fixtures/login.ts: origin-check hardcoded to localhost
    to match.

Verification
  just test-all → exit 0, 228 tests green (34 pgTAP + 140 Vitest
    integration + 11 Vitest unit + 43 Playwright), 4 skipped (upstream
    Realtime presence + WebKit-only touch gestures).
  just test-e2e alone → 43 passed.
  pnpm exec playwright test alone → 43 passed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:48:10 +02:00
5a63e5fc4a feat(dev): expose full auth stack on LAN IP for on-device preview
The dev stack previously mixed two hostnames (`localhost` in some places,
`keycloak` in others). That only worked because the laptop's /etc/hosts
maps `keycloak` to 127.0.0.1. Phones, tablets, or a second laptop had no
such mapping, so the OAuth flow broke the moment you tried to log in from
any non-laptop device.

Switched the SPA, Kong, GoTrue, and Keycloak client to all agree on a
single external host — the laptop's LAN IP (192.168.1.167) — so the full
Keycloak → GoTrue → Supabase → SvelteKit round-trip works from any device
on the same Wi-Fi.

Changes
  .env (root, ungitignored): PUBLIC_SUPABASE_URL / PUBLIC_KEYCLOAK_URL /
    PUBLIC_APP_URL now use the LAN IP (updated locally; tracked via
    apps/web/.env.development below).
  apps/web/.env.development: mirror the LAN IP so `$env/static/public`
    resolves the same on laptop and phone.
  apps/web/vite.config.ts: `server.host: true` — bind Vite to 0.0.0.0.
  apps/web/playwright.config.ts: `baseURL: PUBLIC_APP_URL ?? localhost`
    so E2E uses the same origin the stack is configured with.
  apps/web/tests/fixtures/login.ts:
    - wait for the collective button in the sidebar to render before
      returning (LAN-IP latency surfaced a pre-existing race in
      `handleCreate` where Enter fired before `$currentCollective`
      hydrated, silently no-op'ing).
    - derive expected app origin from PUBLIC_APP_URL.
  apps/web/tests/e2e/items.test.ts: scope D-04 delete assertion to the
    `[role="listitem"]` locator — with undoQueue enabled the toast text
    "Deleted <name>" also matches `getByText(itemName)` and shadowed the
    original check.
  infra/docker-compose.dev.yml:
    - GOTRUE_EXTERNAL_KEYCLOAK_URL and REDIRECT_URI now read from
      PUBLIC_KEYCLOAK_URL / PUBLIC_SUPABASE_URL so they follow the same
      host as the rest of the stack.
    - NEW: GOTRUE_URI_ALLOW_LIST with `/auth/callback` on both the LAN
      IP and localhost. Without an explicit allow-list GoTrue rejected
      `redirect_to=.../auth/callback` and fell back to SITE_URL root,
      stranding `?code=` at `/` and re-triggering signIn → infinite loop.
  keycloak/realm-export.json: `colectivo-web` client gains LAN-IP
    redirectUris and webOrigins (alongside the existing localhost
    entries). Persisted + live-applied via admin API.
  .gitignore: add .claude/ (per-project scheduler runtime state).

Verification
  just test-all → 224 passed, 4 skipped:
    34 pgTAP
    140 Vitest integration + 2 skipped (Realtime presence, upstream bug)
    11 Vitest unit
    39 Playwright + 2 skipped (mobile-swipe touch, WebKit-only)
  Phone sanity check: open http://192.168.1.167:5173 on a LAN device,
  log in as a seed user, full RLS-respecting session.

Caveats
  LAN IP (192.168.1.167) is DHCP-assigned — if it rotates, rerun the
  Keycloak admin API update (realm-export.json needs a new entry) and
  update the three PUBLIC_* URLs. Consider a Tailscale magic-DNS name
  as a stable replacement for the prod-deploy sprint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 16:09:32 +02:00
f396897cb5 test: full test suite (Vitest + pgTAP + Playwright) + TDD plan restructure
Add a 4-layer test stack covering RLS, triggers, and UI flows for Fases 0–2a,
then restructure every plan file so future fases start with tests and end with
a verification gate.

Test suite
- packages/test-utils: Vitest integration tests signing HS256 JWTs via jose so
  each test acts as a specific seed user (createClientAs + createAdminClient)
- supabase/tests: pgTAP for accept_invitation(), item_frequency trigger, and
  promote-on-admin-leave; each file self-installs pgtap extension
- apps/web/tests: Playwright E2E with live Keycloak login per test (storageState
  caching doesn't rehydrate Supabase's session state reliably)
- just test-all chains the three suites; test-db forwards POSTGRES_PASSWORD
  as PGPASSWORD with ON_ERROR_STOP=1 so failures abort the chain

Supabase auth gotcha
- PostgREST queries inside onAuthStateChange deadlock on GoTrue's navigator.locks
  auth lock (getAccessToken → getSession → initializePromise waits on the same
  lock that's held during event dispatch). Fix is two defenses: a pass-through
  lock in $lib/supabase, and a setTimeout(0) defer in root +layout.svelte to
  push loadUserCollectives out of the callback's microtask chain. Either alone
  is insufficient; both together unblock the Playwright suite.

Env key rotation
- apps/web/.env.development had a stale demo anon key signed with a different
  secret than root .env; Vite inlined that into the browser bundle so Kong (which
  uses the root .env value) rejected every request with 401. Aligned the two
  files and added a memory entry to flag this for the next rotation.

Plan restructure (TDD)
- Every fase now opens with X.0 Tests primero and closes with X.Z Verificación
  final. Completed fases (0, 1, 2a) show the pattern retroactively with the
  tests that currently cover them; pending fases (2b, 3, 4) list the tests to
  write before implementation.

Docs
- CLAUDE.md status line reports 54 + 12 + 15 = 81 green tests, adds gotchas
  #11 (auth-lock deadlock) and #12 (no storageState caching)
- README.md adds a TDD methodology section and the test-all command
- .gitignore excludes Playwright's generated reports and auth state

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 01:40:16 +02:00