From 7811d34b4dfdaffa87b8a3b929fa59242fab6516 Mon Sep 17 00:00:00 2001 From: devHanif Date: Tue, 16 Jun 2026 14:46:04 +0800 Subject: [PATCH 1/2] feat(auth): implement real Supabase Google OAuth, profiles table, and role-based access control - Replaced mocked localStorage authentication with Supabase Auth using Google OAuth. - Created a profiles table in Supabase to store user roles and metadata. - Implemented role-based access control for the /manage route. - Added server-side handling for owner-id to maintain order attribution across sessions. - Introduced a SignOutConfirmModal component for user sign-out confirmation. - Updated environment variable configurations for Supabase integration. - Removed legacy role toggles and ensured the application adheres to new role management. - Added necessary utility functions for managing owner-id in both client and server contexts. --- .dev.vars.example | 13 + .gitignore | 1 + .hermes/plans/2026-06-15_auth-google-oauth.md | 581 ++++++++++++++++++ app/(customer)/checkout/actions.ts | 10 + app/(customer)/profile/orders/page.tsx | 11 +- app/(customer)/profile/page.tsx | 12 +- components/checkout-screen.tsx | 5 + components/profile-screen.tsx | 207 ++++--- components/signout-confirm-modal.tsx | 74 +++ data/mock-order.ts | 1 + data/rewards.ts | 4 +- lib/auth/owner-id-server.ts | 13 + lib/auth/owner-id-shared.ts | 7 + lib/auth/owner-id.ts | 67 ++ lib/orders/store.ts | 27 + store/auth.tsx | 98 ++- supabase/.temp/cli-latest | 1 + types/order.ts | 5 + wrangler.jsonc | 5 + 19 files changed, 1045 insertions(+), 97 deletions(-) create mode 100644 .dev.vars.example create mode 100644 .hermes/plans/2026-06-15_auth-google-oauth.md create mode 100644 components/signout-confirm-modal.tsx create mode 100644 lib/auth/owner-id-server.ts create mode 100644 lib/auth/owner-id-shared.ts create mode 100644 lib/auth/owner-id.ts create mode 100644 supabase/.temp/cli-latest diff --git a/.dev.vars.example b/.dev.vars.example new file mode 100644 index 0000000..1d6f42b --- /dev/null +++ b/.dev.vars.example @@ -0,0 +1,13 @@ +# Local Workers preview vars, read by `opennextjs-cloudflare preview`. +# Copy to .dev.vars and fill in. .dev.vars is gitignored; this template is committed. + +NEXTJS_ENV=development + +# Public store URL for local preview +NEXT_PUBLIC_SITE_URL=http://localhost:3000 + +# Telegram order notifications — server-only secrets. +# TELEGRAM_BOT_TOKEN: from @BotFather (e.g. 123456789:ABCdef...). +# TELEGRAM_CHAT_ID: target group chat id (negative for groups, e.g. -1001234567890). +TELEGRAM_BOT_TOKEN= +TELEGRAM_CHAT_ID= diff --git a/.gitignore b/.gitignore index 0ff33d8..355eb22 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ /.open-next/ /.wrangler/ .dev.vars +!.dev.vars.example # production /build diff --git a/.hermes/plans/2026-06-15_auth-google-oauth.md b/.hermes/plans/2026-06-15_auth-google-oauth.md new file mode 100644 index 0000000..5d7d583 --- /dev/null +++ b/.hermes/plans/2026-06-15_auth-google-oauth.md @@ -0,0 +1,581 @@ +# Auth + Google OAuth (Supabase) Implementation Plan + +> **For Hermes:** Implement task-by-task. Each task is bite-sized. Verify after each. Commit per task. + +**Goal:** Replace the mocked localStorage auth with real Supabase Auth using Google OAuth (SSR cookie flow), create a `profiles` table with a `role` defaulting to `customer`, and gate the staff `/manage` surface on the real role — login and logout working end to end. + +**Architecture:** `@supabase/ssr` cookie-based sessions for the Next.js App Router. Three Supabase clients (browser, server, proxy). A `proxy.ts` (Next 16's renamed middleware) refreshes the session on every request. Google OAuth uses the PKCE redirect flow: app → Supabase `/auth/v1/callback` → our `/auth/callback` route handler exchanges the code for a session. A Postgres trigger auto-creates a `profiles` row on signup. RLS protects `profiles`; a `SECURITY DEFINER` helper avoids policy recursion. The existing `AuthProvider` public API is preserved so consuming components don't change — only its internals swap from localStorage to the Supabase session. + +**Tech Stack:** Next.js 16.2.9 (App Router, `proxy.ts`), TypeScript (strict), `@supabase/supabase-js`, `@supabase/ssr`, Supabase Postgres + RLS, deployed via `@opennextjs/cloudflare` (nodejs runtime). + +**Scope boundaries:** +- IN: Google OAuth sign-in/out, SSR session refresh, `profiles` table + trigger + RLS, real role gate for `/manage`, env wiring. +- OUT (later plans): WhatsApp/phone OTP (deferred until Meta WABA approved — phone UI stays mocked), moving orders/beans into Supabase, the guest `owner-id` → `auth.uid()` order migration (orders aren't in the DB yet, so there's nothing to migrate). + +**Key facts established from the codebase:** +- Project root: `C:\Users\devHanif\Documents\Projects_n_Programming\Random Projects\naisecoffee` +- Next 16 renamed `middleware` → `proxy` (nodejs only, no edge). Use `proxy.ts` at project root. +- `lib/supabase/` is empty (only `.gitkeep`). No `@supabase/*` deps yet. +- `store/auth.tsx` exposes `{ hydrated, user, isAuthenticated, showWelcome, signIn, signOut, dismissWelcome }`. Consumed by `components/profile-screen.tsx` and `components/auth-screen.tsx`. **Preserve this interface.** +- `lib/auth/session.ts` reads role from a `naise_role` cookie (placeholder). Replace with a `profiles.role` lookup. +- `app/(customer)/profile/settings/page.tsx` has a dev-only `naise_role` cookie toggle — REMOVE it (Task 8.3); the real gate uses `profiles.role`, and staff/admin roles are assigned in Supabase. +- Roles enum: `admin | manager | staff | customer` (`types/auth.ts`). `MANAGE_ROLES = [admin, manager, staff]`. +- `AuthProvider` is mounted in BOTH `app/(customer)/layout.tsx` and `app/(auth)/layout.tsx`. +- Supabase project ref: `hodukwhqjhjzyfxlsovp`. Publishable key uses the NEW naming: `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`. + +--- + +## Phase 0 — Supabase Dashboard + Google Cloud (USER does this, no code) + +### Task 0.1: Create Google OAuth credentials +**Owner:** devHanif (already has Client ID; **rotate the leaked secret first**). + +1. Google Cloud Console → APIs & Services → Credentials → reset the OAuth client secret (the old one was pasted in chat — treat as compromised). +2. OAuth client (Web application) config: + - **Authorized JavaScript origins:** `http://localhost:3000`, `https://naisecoffee.utemride.my`, `https://hodukwhqjhjzyfxlsovp.supabase.co` + - **Authorized redirect URIs:** `https://hodukwhqjhjzyfxlsovp.supabase.co/auth/v1/callback` +3. Copy Client ID + the NEW secret. + +### Task 0.2: Configure Supabase Auth +**Owner:** devHanif. + +1. Dashboard → Authentication → Providers → **Google** → enable, paste Client ID + Client Secret. Save. +2. Dashboard → Authentication → URL Configuration: + - **Site URL:** `http://localhost:3000` (swap to `https://naisecoffee.utemride.my` at launch) + - **Redirect URLs (allow-list):** add `http://localhost:3000/**` and `https://naisecoffee.utemride.my/**` +3. Confirm Data API exposes the `public` schema (default on). Note the publishable key from Settings → API Keys. + +**Verify:** Google appears as enabled under Providers; redirect allow-list contains both origins. + +--- + +## Phase 1 — Dependencies & environment + +### Task 1.1: Install Supabase packages (pinned) +**Files:** `package.json`, `package-lock.json` + +Run (ask before installing — AGENTS.md rule; these are the required, expected deps): +```bash +npm install @supabase/supabase-js@^2 @supabase/ssr@^0.5 +``` +After install, pin exact versions in `package.json` (replace `^` with the resolved exact versions from the lockfile) per the user's "pin exact versions" convention. Commit the lockfile. + +**Verify:** `npm ls @supabase/ssr @supabase/supabase-js` shows both resolved, no peer warnings that break the build. + +### Task 1.2: Add env vars (three places) +**Files:** `.env.example`, `.env.local`, `.dev.vars.example`, `.dev.vars` + +Append to `.env.example` (committed template — names only, no values): +```bash +# Supabase Auth — client-safe (exposed to the browser) +NEXT_PUBLIC_SUPABASE_URL= +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= +``` +> Decision (devHanif): LEAVE the existing legacy `NEXT_PUBLIC_SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_ROLE_KEY` lines in `.env.example` untouched. Just ADD the new `PUBLISHABLE_KEY` line alongside them. The code uses `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`; the legacy lines stay as harmless template placeholders for future server-side work. + +Add the real values to `.env.local` (gitignored): +```bash +NEXT_PUBLIC_SUPABASE_URL=https://hodukwhqjhjzyfxlsovp.supabase.co +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_MLdycDnv7gtNWLHoxa0SIQ_jO2BeKl4 +``` +Mirror both into `.dev.vars.example` (names) and `.dev.vars` (values) so the `opennextjs-cloudflare preview` Worker runtime sees them too. + +**Verify:** `grep PUBLISHABLE .env.local .dev.vars` shows the key in both; `.env.example`/`.dev.vars.example` carry the names only. + +--- + +## Phase 2 — Supabase clients + +### Task 2.1: Browser client +**Files:** Create `lib/supabase/client.ts` +```ts +import { createBrowserClient } from "@supabase/ssr"; + +// Browser-side Supabase client for Client Components (realtime, OAuth kickoff). +// Reads only the publishable key — safe to ship to the browser. +export function createClient() { + return createBrowserClient( + process.env.NEXT_PUBLIC_SUPABASE_URL!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, + ); +} +``` + +### Task 2.2: Server client +**Files:** Create `lib/supabase/server.ts` +```ts +import { createServerClient } from "@supabase/ssr"; +import { cookies } from "next/headers"; + +// Server-side client for Server Components, Server Actions, and Route Handlers. +// Uses the request cookie store. The setAll try/catch is required: Server +// Components cannot write cookies, so writes there are no-ops (the proxy +// refreshes the session instead). +export async function createClient() { + const cookieStore = await cookies(); + return createServerClient( + process.env.NEXT_PUBLIC_SUPABASE_URL!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, + { + cookies: { + getAll() { + return cookieStore.getAll(); + }, + setAll(cookiesToSet) { + try { + cookiesToSet.forEach(({ name, value, options }) => + cookieStore.set(name, value, options), + ); + } catch { + // Called from a Server Component — ignore; proxy handles refresh. + } + }, + }, + }, + ); +} +``` + +### Task 2.3: Proxy session-refresh helper +**Files:** Create `lib/supabase/proxy.ts` +```ts +import { createServerClient } from "@supabase/ssr"; +import { NextResponse, type NextRequest } from "next/server"; + +// Refreshes the Supabase session on every request and syncs cookies onto both +// the request (for Server Components downstream) and the response (for the +// browser). MUST call getClaims() — never getSession() — so the JWT signature +// is validated, not just decoded. +export async function updateSession(request: NextRequest) { + let supabaseResponse = NextResponse.next({ request }); + + const supabase = createServerClient( + process.env.NEXT_PUBLIC_SUPABASE_URL!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, + { + cookies: { + getAll() { + return request.cookies.getAll(); + }, + setAll(cookiesToSet) { + cookiesToSet.forEach(({ name, value }) => + request.cookies.set(name, value), + ); + supabaseResponse = NextResponse.next({ request }); + cookiesToSet.forEach(({ name, value, options }) => + supabaseResponse.cookies.set(name, value, options), + ); + }, + }, + }, + ); + + // Validates and refreshes the token. Do not remove. + await supabase.auth.getClaims(); + + return supabaseResponse; +} +``` + +**Verify (whole phase):** `npx tsc --noEmit` passes for these three files. + +--- + +## Phase 3 — Proxy (session refresh on every request) + +### Task 3.1: Create `proxy.ts` at project root +**Files:** Create `proxy.ts` (project root — Next 16 convention, replaces `middleware.ts`) +```ts +import { type NextRequest } from "next/server"; +import { updateSession } from "@/lib/supabase/proxy"; + +export async function proxy(request: NextRequest) { + return await updateSession(request); +} + +export const config = { + matcher: [ + // Run on everything except static assets and image files. + "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)", + ], +}; +``` +> Notes: Function MUST be named `proxy`. Runtime is nodejs (forced) — fine for `@opennextjs/cloudflare`. Do NOT create a `middleware.ts`. + +**Verify:** `npm run dev`, hit `http://localhost:3000/home`, confirm no proxy errors in the terminal and the page renders. + +--- + +## Phase 4 — Database: profiles table, trigger, RLS + +> Per the supabase skill: iterate with `execute_sql` (MCP) or the SQL editor, NOT `apply_migration`. Once green, capture the final SQL into a migration file under `supabase/migrations/`. Run advisors before committing. + +### Task 4.1: Create the role enum + profiles table +SQL: +```sql +-- Role set mirrors types/auth.ts. +create type public.user_role as enum ('admin', 'manager', 'staff', 'customer'); + +create table public.profiles ( + id uuid primary key references auth.users (id) on delete cascade, + role public.user_role not null default 'customer', + display_name text, + avatar_url text, + phone text, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +comment on table public.profiles is 'One row per auth user. Identity + role. Beans/orders live elsewhere.'; +``` + +### Task 4.2: updated_at trigger +```sql +create or replace function public.set_updated_at() +returns trigger +language plpgsql +set search_path = '' +as $$ +begin + new.updated_at = now(); + return new; +end; +$$; + +create trigger profiles_set_updated_at + before update on public.profiles + for each row execute function public.set_updated_at(); +``` + +### Task 4.3: Auto-create profile on signup +```sql +-- Runs as definer so it can insert into profiles regardless of RLS. Pulls +-- name/avatar from the Google identity payload. search_path pinned for safety. +create or replace function public.handle_new_user() +returns trigger +language plpgsql +security definer +set search_path = '' +as $$ +begin + insert into public.profiles (id, display_name, avatar_url) + values ( + new.id, + coalesce(new.raw_user_meta_data ->> 'full_name', new.raw_user_meta_data ->> 'name'), + new.raw_user_meta_data ->> 'avatar_url' + ) + on conflict (id) do nothing; + return new; +end; +$$; + +create trigger on_auth_user_created + after insert on auth.users + for each row execute function public.handle_new_user(); +``` + +### Task 4.4: Role helper (avoids RLS recursion) +```sql +-- SECURITY DEFINER so reading the caller's role does NOT re-trigger profiles +-- RLS (which would recurse). Kept minimal and only ever returns the CALLER's +-- own role. search_path pinned. Not a general-purpose lookup. +create or replace function public.current_user_role() +returns public.user_role +language sql +security definer +stable +set search_path = '' +as $$ + select role from public.profiles where id = (select auth.uid()); +$$; + +revoke execute on function public.current_user_role() from public; +grant execute on function public.current_user_role() to authenticated; +``` + +### Task 4.5: Enable RLS + policies +```sql +alter table public.profiles enable row level security; + +-- Read: a user reads their own row; staff/manager/admin read all. +create policy "profiles_select_own_or_staff" + on public.profiles for select + to authenticated + using ( + (select auth.uid()) = id + or public.current_user_role() in ('admin', 'manager', 'staff') + ); + +-- Insert: a user may insert only their own row (the trigger normally does this; +-- this policy covers any client-side upsert fallback). +create policy "profiles_insert_self" + on public.profiles for insert + to authenticated + with check ((select auth.uid()) = id); + +-- Update: a user updates only their own row. NOTE: this allows editing +-- display_name/avatar/phone but NOT role escalation — role changes are blocked +-- in app code (never write role from the client) and there is intentionally no +-- client-facing role-update policy. Admin role management is a future plan. +create policy "profiles_update_own" + on public.profiles for update + to authenticated + using ((select auth.uid()) = id) + with check ((select auth.uid()) = id); +``` +> Pitfall guarded: UPDATE needs both `USING` and `WITH CHECK`; SELECT policy is required for UPDATE to see the row; role lookup uses the definer function so the SELECT policy doesn't recurse. + +### Task 4.6: Backfill existing users (if any) +```sql +insert into public.profiles (id, display_name, avatar_url) +select id, + coalesce(raw_user_meta_data ->> 'full_name', raw_user_meta_data ->> 'name'), + raw_user_meta_data ->> 'avatar_url' +from auth.users +on conflict (id) do nothing; +``` + +### Task 4.7: Run advisors, then commit the migration +1. Run `supabase db advisors` (or MCP `get_advisors`) — fix any security/perf findings. +2. Create the migration file: `supabase migration new auth_profiles` then paste the finalized SQL (4.1–4.5) into `supabase/migrations/_auth_profiles.sql`. Keep 4.6 as a one-off (or include — it's idempotent). +3. `supabase migration list --local` to verify it's recorded. + +**Verify:** In the SQL editor, `select * from public.profiles;` works; a test signup (next phase) creates a row with `role='customer'`. + +--- + +## Phase 5 — OAuth callback route handler + +### Task 5.1: Create the code-exchange route +**Files:** Create `app/(auth)/auth/callback/route.ts` +```ts +import { NextResponse } from "next/server"; +import { createClient } from "@/lib/supabase/server"; + +// Supabase redirects here after Google. Exchange the PKCE code for a session +// (cookies are set by the server client), then send the user to `next`. +export async function GET(request: Request) { + const { searchParams, origin } = new URL(request.url); + const code = searchParams.get("code"); + const rawNext = searchParams.get("next") ?? "/home"; + // Only allow same-site relative redirects. + const next = + rawNext.startsWith("/") && !rawNext.startsWith("//") ? rawNext : "/home"; + + if (code) { + const supabase = await createClient(); + const { error } = await supabase.auth.exchangeCodeForSession(code); + if (!error) { + return NextResponse.redirect(`${origin}${next}`); + } + } + + return NextResponse.redirect(`${origin}/login?error=auth`); +} +``` +> Route lives in the `(auth)` group so it shares that segment but route handlers ignore layouts. Final URL is `/auth/callback`. + +**Verify:** `npx tsc --noEmit` passes. Full flow tested in Phase 7. + +--- + +## Phase 6 — Wire the Google button to real OAuth + +### Task 6.1: Replace the mock Google handler in AuthScreen +**Files:** Modify `components/auth-screen.tsx` + +- Import the browser client: `import { createClient } from "@/lib/supabase/client";` +- Replace `onGoogle` so it calls real OAuth instead of the `finish("google", …)` mock: +```ts +async function onGoogle() { + setPending("google"); + const supabase = createClient(); + const { error } = await supabase.auth.signInWithOAuth({ + provider: "google", + options: { + redirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(redirect)}`, + }, + }); + if (error) { + setPending(null); + // TODO: surface a toast; for now log. + console.error("Google sign-in failed", error); + } + // On success the browser navigates away to Google — no further work here. +} +``` +- Leave the phone/OTP branch (`onSendOtp`/`onVerifyOtp`) as the existing mock for now (WhatsApp/phone OTP is a later plan). Add a short comment noting it's still mocked. + +**Verify:** Clicking "Continue with Google" redirects to the Google consent screen. + +--- + +## Phase 7 — Swap AuthProvider internals to the real session + +> This is the highest-risk task. The public API of `useAuth()` must not change (ProfileScreen and AuthScreen depend on `hydrated`, `user`, `isAuthenticated`, `showWelcome`, `signOut`, `dismissWelcome`). Only the source of truth changes: localStorage mock → Supabase session. + +### Task 7.1: Rewrite `store/auth.tsx` to read the Supabase session +**Files:** Modify `store/auth.tsx` + +Behavior: +- On mount, create the browser client, call `supabase.auth.getClaims()` (or `getUser()`) to seed `user`, set `hydrated = true`. +- Subscribe with `supabase.auth.onAuthStateChange((event, session) => …)` to keep `user` live; unsubscribe on unmount. +- Map the Supabase user → existing `AuthUser` shape: + - `id` = `session.user.id` (real UUID — replaces the owner-id mock) + - `method` = `"google"` (from `session.user.app_metadata.provider`) + - `email` = `session.user.email` + - `name` = `user_metadata.full_name ?? user_metadata.name ?? email` +- `signOut` → `await supabase.auth.signOut()` then clear local state (keep `getOrCreateOwnerId` behavior for guests untouched — still mint an owner id so guest order attribution keeps working). +- `signIn` (the old mock) → **remove from the public type** OR keep as a no-op stub that throws "use OAuth". Cleanest: drop `signIn` from `AuthContextValue` and delete its only caller path in AuthScreen (already replaced in Task 6.1). Confirm no other callers: `search_files("signIn", path="...")` → only `auth-screen.tsx`. +- Welcome modal: preserve the one-time new-user celebration. Replace the localStorage `known-identities` heuristic with: show welcome when `onAuthStateChange` fires `SIGNED_IN` AND the user's `created_at` is within the last ~60s (brand-new account). Keep `WELCOME_KEY`/`dismissWelcome` as-is for the dismiss flow. +- Keep `getOrCreateOwnerId()` call on mount (guest attribution unchanged). + +> Because `AuthProvider` is mounted in two layouts, both the `(auth)` and `(customer)` trees get the live session. The Supabase client reads the same cookies the proxy refreshes, so the session is consistent across the redirect. + +**Verify:** `npx tsc --noEmit` passes; `useAuth()` consumers still compile. + +### Task 7.2: Confirm no stale mock imports +Run `search_files("naise-auth-known|naise-auth-welcome|setOwnerId", path=)` and reconcile: owner-id stays; the known-identities localStorage block is removed if no longer used. + +--- + +## Phase 8 — Sign-out (profile screen) + real role gate + +### Task 8.1: Verify sign-out works through the new provider +**Files:** `components/profile-screen.tsx` (likely no change) + +The screen already calls `signOut()` from `useAuth()` via `SignOutConfirmModal`. Since Task 7.1 makes `signOut` call `supabase.auth.signOut()`, this should work unchanged. Confirm by reading the file; only touch it if the `signOut` signature changed. + +**Verify:** Manual — sign in, open `/profile`, tap Sign Out, confirm modal → session cleared, UI flips to the guest state, and a refresh stays signed out. + +### Task 8.2: Replace the role gate with a profiles lookup +**Files:** Modify `lib/auth/session.ts` +```ts +import { createClient } from "@/lib/supabase/server"; +import { MANAGE_ROLES, type Role } from "@/types/auth"; + +// Reads the signed-in user's role from profiles (RLS-backed). Returns null for +// guests. Replaces the old naise_role cookie placeholder. +export async function getSessionRole(): Promise { + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return null; + + const { data, error } = await supabase + .from("profiles") + .select("role") + .eq("id", user.id) + .single(); + if (error || !data) return null; + return data.role as Role; +} + +export async function canManageOrders(): Promise { + const role = await getSessionRole(); + return role !== null && MANAGE_ROLES.includes(role); +} +``` +> Decision (devHanif): REMOVE the dev `naise_role` cookie toggle entirely. Staff/admin roles are assigned in Supabase (`profiles.role`), which is what grants `/manage` access. See Task 8.3. + +**Verify:** A `customer` hitting `/manage` is blocked; after `update … set role='staff'`, the same user can open it. + +### Task 8.3: Remove the dev `naise_role` toggle from settings +**Files:** Modify `app/(customer)/profile/settings/page.tsx` + +Delete the `toggleAdminRole` server action (lines ~16–34), the `cookies()` read of `naise_role` and the `isAdmin` constant in the page body, and the entire `process.env.NODE_ENV !== "production"` "Developer" section that renders the Grant/Remove Staff Access button. Drop the now-unused `cookies` import. The page should render only the Security section. + +To test staff access going forward, set the role directly in the DB: +```sql +update public.profiles set role = 'staff' where id = ''; +``` +(A proper admin role-management UI is a future plan.) + +**Verify:** `npx tsc --noEmit` and `npm run lint` pass; `/profile/settings` renders without the Developer section; `grep -r naise_role .` returns nothing. + +--- + +## Phase 9 — Generate DB types + +### Task 9.1: Supabase types for `profiles` +**Files:** Create `types/database.ts` +```bash +supabase gen types typescript --project-id hodukwhqjhjzyfxlsovp > types/database.ts +``` +Wire the server/browser clients to the generated `Database` generic if low-effort (`createServerClient(...)`). Keep it simple — only if it compiles cleanly. + +**Verify:** `npx tsc --noEmit` passes; `profiles.role` is typed as the enum. + +--- + +## Phase 10 — Full verification + +### Task 10.1: Type + lint +```bash +npx tsc --noEmit +npm run lint +``` +Expected: no errors. Fix any before proceeding (AGENTS.md: fix lint/type errors before finishing). + +### Task 10.2: Build +```bash +npm run build +``` +Expected: clean production build. + +### Task 10.3: Manual end-to-end (dev) +1. `npm run dev` +2. Visit `/login`, click **Continue with Google**, complete consent. +3. Land back on `/home` signed in. Check Supabase → Auth → Users (new user) and `select * from public.profiles` (new row, `role='customer'`, display_name/avatar populated). +4. Open `/profile` — avatar, name, member-since render from the session/profile. +5. Tap **Sign Out** → confirm → guest state; refresh stays signed out. +6. `/manage` blocked as customer. `update public.profiles set role='staff' where id='';`, re-sign-in, `/manage` opens. +7. Confirm phone/OTP button still shows the (mocked) flow without crashing. + +### Task 10.4: Cloudflare preview smoke test (optional but recommended) +```bash +npm run preview +``` +Confirm OAuth works under the Workers runtime (proxy is nodejs; ensure `.dev.vars` has the Supabase vars). Watch for cookie/domain issues. + +### Task 10.5: Commit +```bash +git add -A +git commit -m "feat(auth): real Supabase Google OAuth, profiles table + RLS, role gate" +``` +> Do NOT commit `.env.local` or `.dev.vars` (already gitignored). Confirm with `git status` before committing. + +--- + +## Files likely to change + +| Action | Path | +|---|---| +| Create | `lib/supabase/client.ts` | +| Create | `lib/supabase/server.ts` | +| Create | `lib/supabase/proxy.ts` | +| Create | `proxy.ts` (project root) | +| Create | `app/(auth)/auth/callback/route.ts` | +| Create | `supabase/migrations/_auth_profiles.sql` | +| Create | `types/database.ts` | +| Modify | `components/auth-screen.tsx` (real Google OAuth) | +| Modify | `store/auth.tsx` (Supabase session internals) | +| Modify | `lib/auth/session.ts` (profiles role lookup) | +| Modify | `.env.example`, `.env.local`, `.dev.vars.example`, `.dev.vars` | +| Modify | `package.json`, `package-lock.json` | +| Modify | `app/(customer)/profile/settings/page.tsx` (remove dev `naise_role` toggle — Task 8.3) | + +## Risks, tradeoffs, open questions + +1. **Two `AuthProvider` mounts.** Both layouts wrap children in their own `AuthProvider`. With localStorage that was fine; with Supabase each provider instance subscribes independently — acceptable (both read the same cookies), but confirm there's no double welcome-modal fire across the redirect boundary. +2. **`getClaims()` vs `getUser()`.** The proxy uses `getClaims()` (validates JWT signature). Server role lookups use `getUser()` (round-trips to Supabase, always fresh) — slightly slower but correct for authz. Acceptable for this app's traffic. +3. **Welcome-modal heuristic.** Switching from the localStorage known-identities list to a `created_at < 60s` check is simpler but time-based. Edge case: a brand-new user who dawdles on the consent screen >60s won't see the celebration. Low stakes; revisit if it matters. +4. **Cloudflare Workers + proxy.** Next 16 `proxy` is nodejs-runtime; `@opennextjs/cloudflare` supports it, but verify cookies set in the proxy survive the Worker response (Task 10.4). If issues appear, the OpenNext docs cover middleware/proxy adaptation. +5. **Role escalation.** No client-facing role-update policy exists, and app code never writes `role`. Admin role management (granting staff) is manual SQL for now — a deliberate deferral. +6. **Phone/OTP still mocked.** Per devHanif's decision the phone button STAYS, showing the existing localStorage mock until WhatsApp/WABA is approved. It must not crash now that `signIn` is removed from the provider — Task 7.1 must keep a minimal phone-mock path that satisfies the new provider interface (e.g. a local-only `mockPhoneSignIn` the AuthScreen calls, isolated from the real Supabase session). Add a clear "mocked — not wired to Supabase yet" comment in the phone branch. + +## Decisions confirmed (resolved before execution) +- **Q1 — RESOLVED:** Do NOT touch the existing legacy `NEXT_PUBLIC_SUPABASE_ANON_KEY` / `SUPABASE_SERVICE_ROLE_KEY` lines in `.env.example`. Just ADD the new `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` line. (Task 1.2) +- **Q2 — RESOLVED:** Keep the phone/OTP button, showing the mock flow, labeled clearly. (Task 7.1, risk #6) +- **Q3 — RESOLVED:** REMOVE the dev `naise_role` toggle from settings entirely. Staff/admin roles are assigned in Supabase (`profiles.role`). (Task 8.3) diff --git a/app/(customer)/checkout/actions.ts b/app/(customer)/checkout/actions.ts index 1296a38..1dafee2 100644 --- a/app/(customer)/checkout/actions.ts +++ b/app/(customer)/checkout/actions.ts @@ -22,6 +22,10 @@ export type PlaceOrderInput = { // Pre-discount and amount-due totals, in sen. subtotal: number; total: number; + // Stable per-browser id (`naise_owner_id`). Used so a guest's orders carry + // over to the account they later register — the new account adopts this + // same id. Validated to a non-empty string before persisting. + ownerId: string; }; export type PlaceOrderResult = @@ -36,6 +40,11 @@ export async function placeOrder( if (input.items.length === 0) { return { ok: false, error: "Your cart is empty." }; } + if (!input.ownerId) { + // The owner id should always be supplied by the client — guard so we + // never persist an order with no attribution (RLS will require it later). + return { ok: false, error: "Missing session id. Refresh and try again." }; + } const lines: OrderLine[] = input.items.map((item) => ({ name: item.name, @@ -48,6 +57,7 @@ export async function placeOrder( })); const order = createOrder({ + ownerId: input.ownerId, paymentMethod: input.paymentMethod, items: lines, subtotal: input.subtotal, diff --git a/app/(customer)/profile/orders/page.tsx b/app/(customer)/profile/orders/page.tsx index e196754..a76467e 100644 --- a/app/(customer)/profile/orders/page.tsx +++ b/app/(customer)/profile/orders/page.tsx @@ -1,7 +1,8 @@ import type { Metadata } from "next"; import Link from "next/link"; import { ChevronLeft } from "lucide-react"; -import { listOrders } from "@/lib/orders/store"; +import { listOrdersFor } from "@/lib/orders/store"; +import { getOwnerIdFromCookie } from "@/lib/auth/owner-id-server"; import { CustomerOrderCard } from "@/components/customer-order-card"; export const metadata: Metadata = { @@ -9,8 +10,12 @@ export const metadata: Metadata = { description: "Your full order history at Naise Coffee.", }; -export default function ProfileOrdersPage() { - const orders = listOrders(); +export default async function ProfileOrdersPage() { + // Scope to this browser's owner id so guests only see their own orders and + // members don't see another customer's history. Maps onto an RLS-scoped + // `select * from orders where user_id = auth.uid()` once Supabase lands. + const ownerId = await getOwnerIdFromCookie(); + const orders = listOrdersFor(ownerId); return (
diff --git a/app/(customer)/profile/page.tsx b/app/(customer)/profile/page.tsx index dcdc992..f63b86d 100644 --- a/app/(customer)/profile/page.tsx +++ b/app/(customer)/profile/page.tsx @@ -1,5 +1,6 @@ import type { Metadata } from "next"; -import { listOrders } from "@/lib/orders/store"; +import { listOrdersFor } from "@/lib/orders/store"; +import { getOwnerIdFromCookie } from "@/lib/auth/owner-id-server"; import { ProfileScreen } from "@/components/profile-screen"; export const metadata: Metadata = { @@ -8,11 +9,14 @@ export const metadata: Metadata = { }; // Cap the profile preview at the 3 most recent orders; the full history lives -// at /profile/orders. Reuses the shared mock order store until Supabase lands. +// at /profile/orders. Both signed-in members and guests see only their own +// orders — scoped by the per-browser owner id cookie until Supabase Auth + +// RLS take over. const RECENT_ORDERS_LIMIT = 3; -export default function ProfilePage() { - const recentOrders = listOrders().slice(0, RECENT_ORDERS_LIMIT); +export default async function ProfilePage() { + const ownerId = await getOwnerIdFromCookie(); + const recentOrders = listOrdersFor(ownerId).slice(0, RECENT_ORDERS_LIMIT); return ; } diff --git a/components/checkout-screen.tsx b/components/checkout-screen.tsx index 0f1ca30..4f8c3cd 100644 --- a/components/checkout-screen.tsx +++ b/components/checkout-screen.tsx @@ -34,6 +34,7 @@ import { paymentMethods, defaultPaymentMethodId } from "@/data/payment-methods"; import type { PaymentMethodId } from "@/types/payment"; import { GuestSignInModal } from "@/components/guest-signin-modal"; import { placeOrder as placeOrderAction } from "@/app/(customer)/checkout/actions"; +import { getOrCreateOwnerId } from "@/lib/auth/owner-id"; // Icons live in the UI layer so the data file stays pure content. Branded // wallets use a representative lucide glyph (no official logos shipped yet); @@ -166,6 +167,10 @@ export function CheckoutScreen() { notes, subtotal: totalOriginal, total: totalPrice, + // Per-browser stable id; minted on first call and reused thereafter. + // Same id is adopted by the auth store on sign-in, so guest orders + // automatically belong to the registered account afterwards. + ownerId: getOrCreateOwnerId(), }); if (!result.ok) { diff --git a/components/profile-screen.tsx b/components/profile-screen.tsx index d827d94..710ae26 100644 --- a/components/profile-screen.tsx +++ b/components/profile-screen.tsx @@ -1,5 +1,6 @@ "use client"; +import { useState } from "react"; import Link from "next/link"; import { ChevronLeft, @@ -9,6 +10,7 @@ import { Pencil, Settings, Star, + User, } from "lucide-react"; import type { Order } from "@/types/order"; import { getTierProgress } from "@/data/rewards"; @@ -17,6 +19,7 @@ import { useBeans } from "@/store/beans"; import { useProfile } from "@/store/profile"; import { ProfileAvatar } from "@/components/profile-avatar"; import { CustomerOrderCard } from "@/components/customer-order-card"; +import { SignOutConfirmModal } from "@/components/signout-confirm-modal"; // Member-since label, e.g. "Member since Sep 2025". Locale/timeZone pinned so // the edge server (UTC) and client render identical text (no hydration drift). @@ -48,10 +51,16 @@ const menuRows = [ // profile and Beans stores; `recentOrders` (already capped to 3) is passed in // from the server page so the list is server-rendered and crawlable. Mobile- // first within the app's max-w-md shell. +// +// Guests (signed-out browsers) see a stripped-down variant: silhouette +// avatar, "Guest" label, no Beans/tier card, no Edit Profile / Settings rows. +// Their recent orders are still shown — scoped server-side to the per-browser +// owner id, which carries over to the account they later register. export function ProfileScreen({ recentOrders }: { recentOrders: Order[] }) { const { profile } = useProfile(); const { balance } = useBeans(); const { isAuthenticated, signOut } = useAuth(); + const [signOutOpen, setSignOutOpen] = useState(false); const tier = getTierProgress(balance); @@ -74,85 +83,112 @@ export function ProfileScreen({ recentOrders }: { recentOrders: Order[] }) {
- {/* Identity hero — avatar, display name, member-since. */} -
- -

- {profile.displayName} -

-

- {memberSinceLabel(profile.memberSince)} -

-
- - {/* Beans + tier summary — taps through to the Rewards screen. */} - - - - -
-

- {balance.toLocaleString()} - - Beans - + {/* Identity hero. Members see avatar + display name + member-since; + guests see a silhouette + "Guest" + a sign-in nudge. */} + {isAuthenticated ? ( +

+ +

+ {profile.displayName} +

+

+ {memberSinceLabel(profile.memberSince)}

-

- {tier.current.name} tier +

+ ) : ( +
+ + + +

+ Guest +

+

+ Sign in to save your beans & order history

-
- - + + )} - {/* Account menu rows. */} -
- {menuRows.map((row) => { - const Icon = row.icon; - return ( - - - + {/* Beans + tier summary — members only. Hidden for guests since + they can't earn or redeem until they have an account. */} + {isAuthenticated && ( + + + + +
+

+ {balance.toLocaleString()} + + Beans - - {row.label} - - {row.description} +

+

+ {tier.current.name} tier +

+
+ + + )} + + {/* Account menu rows — members only. Edit Profile / Settings need an + account to act on; guests don't see them. */} + {isAuthenticated && ( +
+ {menuRows.map((row) => { + const Icon = row.icon; + return ( + + + - - - - ); - })} -
+ + {row.label} + + {row.description} + + + + + ); + })} +
+ )} - {/* Recent orders — capped at 3, see all opens the full history. */} + {/* Recent orders — capped at 3 for both members and guests. The + heading copy changes for guests so it's clear the orders are + tied to this device, not (yet) to an account. */}
- Recent Orders + {isAuthenticated ? "Recent Orders" : "Your orders on this device"} {recentOrders.length > 0 && ( - {/* Sign out for members; sign in for guests. Auth is mocked via the - localStorage-backed auth store until Supabase Auth lands. */} + {/* Sign out for members; sign in for guests. Per spec, the two + buttons just swap on toggle — no entry animation, no transition + between them — so dropping the `naise-rise` class here is + intentional. Auth is mocked via the localStorage-backed auth + store until Supabase Auth lands. */} {isAuthenticated ? (
+ + {signOutOpen && ( + { + setSignOutOpen(false); + signOut(); + }} + onClose={() => setSignOutOpen(false)} + /> + )}
); } diff --git a/components/signout-confirm-modal.tsx b/components/signout-confirm-modal.tsx new file mode 100644 index 0000000..5ef0aeb --- /dev/null +++ b/components/signout-confirm-modal.tsx @@ -0,0 +1,74 @@ +"use client"; + +import { useEffect } from "react"; +import { LogOut } from "lucide-react"; + +// Confirms before ending the session. Hand-rolled like the other modals: +// closes on backdrop click or Esc, locks body scroll while open. +export function SignOutConfirmModal({ + onConfirm, + onClose, +}: { + onConfirm: () => void; + onClose: () => void; +}) { + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + document.addEventListener("keydown", onKey); + const prevOverflow = document.body.style.overflow; + document.body.style.overflow = "hidden"; + return () => { + document.removeEventListener("keydown", onKey); + document.body.style.overflow = prevOverflow; + }; + }, [onClose]); + + return ( +
+
e.stopPropagation()} + className="relative flex w-full max-w-sm flex-col items-center overflow-hidden rounded-3xl bg-white px-6 pb-6 pt-8 text-center naise-pop" + > + + + + +

+ Sign out? +

+

+ You’ll need to sign in again to view your Beans, streak, and + order history. +

+ + + + +
+
+ ); +} diff --git a/data/mock-order.ts b/data/mock-order.ts index 4509136..579c6f5 100644 --- a/data/mock-order.ts +++ b/data/mock-order.ts @@ -38,6 +38,7 @@ export function mockOrder(): Order { return { token: "test", orderNumber: "NAISE-000000", + ownerId: "mock-test", status: "pending", paymentMethod: "DuitNow QR", proofOfPaymentUrl: "/brand/coffee_with_logo.png", diff --git a/data/rewards.ts b/data/rewards.ts index f161a0e..1745de0 100644 --- a/data/rewards.ts +++ b/data/rewards.ts @@ -13,13 +13,13 @@ export const rewardTiers: RewardTier[] = [ id: "bold", name: "Bold", threshold: 1000, - perk: "1.25× Beans and a free birthday drink.", + perk: "A free birthday drink and member-only offers.", }, { id: "naise-club", name: "Naise Club", threshold: 3000, - perk: "1.5× Beans, free upsizes, and early access to new drinks.", + perk: "Free upsizes and early access to new drinks.", }, ]; diff --git a/lib/auth/owner-id-server.ts b/lib/auth/owner-id-server.ts new file mode 100644 index 0000000..c4a157c --- /dev/null +++ b/lib/auth/owner-id-server.ts @@ -0,0 +1,13 @@ +// Server-side reader for the owner-id cookie. Used by Server Components +// (e.g. the profile page) to scope `listOrdersFor(...)` to this browser +// without shipping the order list to the client. Returns null when the +// cookie is missing — the page should render the empty state in that case. + +import { cookies } from "next/headers"; +import { OWNER_ID_COOKIE } from "@/lib/auth/owner-id-shared"; + +export async function getOwnerIdFromCookie(): Promise { + const store = await cookies(); + const value = store.get(OWNER_ID_COOKIE)?.value; + return value && value.length > 0 ? value : null; +} diff --git a/lib/auth/owner-id-shared.ts b/lib/auth/owner-id-shared.ts new file mode 100644 index 0000000..776095f --- /dev/null +++ b/lib/auth/owner-id-shared.ts @@ -0,0 +1,7 @@ +// Shared owner-id constants. No `"use client"` directive — safe to import +// from both client and server modules. Keeps the cookie name in one place. + +export const OWNER_ID_COOKIE = "naise_owner_id"; +export const OWNER_ID_STORAGE_KEY = "naise-owner-id"; +// 1 year — long enough that a returning guest's history doesn't disappear. +export const OWNER_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365; diff --git a/lib/auth/owner-id.ts b/lib/auth/owner-id.ts new file mode 100644 index 0000000..3535940 --- /dev/null +++ b/lib/auth/owner-id.ts @@ -0,0 +1,67 @@ +// Stable per-browser identifier used to attribute orders to *someone* — +// guest or member — before Supabase Auth lands. The same id is reused when a +// guest registers, so orders placed before sign-up automatically belong to +// the new account (no rewriting rows). On Supabase later this maps to +// `orders.user_id` once the row carries `auth.uid()`; the migration becomes a +// single UPDATE keyed on this id. +// +// The id lives in two places that are kept in sync: +// - localStorage (`naise-owner-id`) → read on the client +// - cookie (`naise_owner_id`) → read by Server Components +// Mirroring to a cookie lets the profile page render server-side (SSR + SEO) +// while still scoping orders to this browser. Cookie is non-HttpOnly on +// purpose: it's not a credential, just an opaque correlation id; the server +// doesn't trust it for authorization (mock today, RLS later). + +"use client"; + +import { + OWNER_ID_COOKIE, + OWNER_ID_COOKIE_MAX_AGE_SECONDS, + OWNER_ID_STORAGE_KEY, +} from "@/lib/auth/owner-id-shared"; + +function writeCookie(id: string): void { + // SameSite=Lax so the cookie is sent on top-level navigations (the SSR fetch + // for /profile etc.) but not on cross-site embeds. No Secure flag in dev so + // it works on http://localhost; production is served over https either way. + document.cookie = + `${OWNER_ID_COOKIE}=${encodeURIComponent(id)}; path=/; ` + + `max-age=${OWNER_ID_COOKIE_MAX_AGE_SECONDS}; samesite=lax`; +} + +// Returns the existing owner id, or mints + persists a new one. Safe to call +// on every client render — no-op once the id is set. +export function getOrCreateOwnerId(): string { + let id: string | null = null; + try { + id = localStorage.getItem(OWNER_ID_STORAGE_KEY); + } catch { + // localStorage unavailable (private mode, etc.); fall through to mint. + } + if (!id) { + id = crypto.randomUUID(); + try { + localStorage.setItem(OWNER_ID_STORAGE_KEY, id); + } catch { + // Non-fatal; cookie still gives the server something to scope by. + } + } + // Always refresh the cookie — bumps the expiry and recovers if it was + // cleared independently of localStorage. + writeCookie(id); + return id; +} + +// Replace the stored owner id. Used when a member signs in on a device that +// already has a different owner id (e.g. signing into their account on a +// shared browser): adopt the member's canonical id so future orders attach to +// it, not the guest record. +export function setOwnerId(id: string): void { + try { + localStorage.setItem(OWNER_ID_STORAGE_KEY, id); + } catch { + // Non-fatal. + } + writeCookie(id); +} diff --git a/lib/orders/store.ts b/lib/orders/store.ts index 622ee6a..6650dc8 100644 --- a/lib/orders/store.ts +++ b/lib/orders/store.ts @@ -18,6 +18,14 @@ const globalForOrders = globalThis as unknown as { __naiseOrderStore?: OrderStore; }; +// Seeds carry a fixed `SEED_OWNER_ID` so they only show up on the staff +// `/manage` board (which uses the unfiltered `listOrders`), not in any real +// customer's profile history (`listOrdersFor` matches on the visitor's owner +// id, which will never equal this constant). Declared above the store +// initializer because `seedStore()` runs at module evaluation time and +// references this constant — a `const` declared later would TDZ. +const SEED_OWNER_ID = "seed-store"; + const store: OrderStore = (globalForOrders.__naiseOrderStore ??= seedStore()); // The order's overall status is derived from its drinks: every drink done means @@ -64,6 +72,18 @@ export function listOrders(): Order[] { ); } +// Orders belonging to one customer (guest or member), newest first. Used by +// the customer profile/orders surfaces to scope the history to "this browser". +// Maps onto `select * from orders where user_id = auth.uid() order by +// created_at desc` under RLS once Supabase lands. A null/empty owner id +// matches no orders — the page should render the empty state. +export function listOrdersFor(ownerId: string | null | undefined): Order[] { + if (!ownerId) return []; + return [...store.orders.values()] + .filter((o) => o.ownerId === ownerId) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); +} + // Set one drink's fulfilment status, then re-derive the order's overall status // from all its drinks. Returns the updated order (or null if unknown). Replace // with a Supabase update + realtime broadcast later; the signature stays the @@ -108,6 +128,9 @@ export function cancelOrder(token: string): Order | null { // Seed a handful of mock orders so the manage screen has content before // Supabase. Timestamps are relative to process start. Remove once real orders // flow through createOrder against the database. +// +// Seeds use the module-level `SEED_OWNER_ID` (declared near the top so it's +// available when the global store is first initialized). function seedStore(): OrderStore { const orders = new Map(); const now = Date.now(); @@ -117,6 +140,7 @@ function seedStore(): OrderStore { { token: "seed-1023", orderNumber: "NAISE-001023", + ownerId: SEED_OWNER_ID, status: "pending", paymentMethod: "DuitNow QR", proofOfPaymentUrl: "/brand/coffee_with_logo.png", @@ -147,6 +171,7 @@ function seedStore(): OrderStore { { token: "seed-1022", orderNumber: "NAISE-001022", + ownerId: SEED_OWNER_ID, status: "preparing", paymentMethod: "Cash", createdAt: minutesAgo(5), @@ -167,6 +192,7 @@ function seedStore(): OrderStore { { token: "seed-1021", orderNumber: "NAISE-001021", + ownerId: SEED_OWNER_ID, status: "pending", paymentMethod: "DuitNow QR", proofOfPaymentUrl: "/brand/coffee_with_logo.png", @@ -197,6 +223,7 @@ function seedStore(): OrderStore { { token: "seed-1020", orderNumber: "NAISE-001020", + ownerId: SEED_OWNER_ID, status: "completed", paymentMethod: "Cash", createdAt: minutesAgo(24), diff --git a/store/auth.tsx b/store/auth.tsx index 6c85145..8c00caa 100644 --- a/store/auth.tsx +++ b/store/auth.tsx @@ -9,12 +9,17 @@ import { useState, } from "react"; import type { AuthMethod, AuthUser } from "@/types/auth"; +import { getOrCreateOwnerId, setOwnerId } from "@/lib/auth/owner-id"; const AUTH_KEY = "naise-auth"; // Set the moment a guest becomes a member; consumed once to show the welcome // modal, then cleared. Kept separate from the user record so signing out and // back in (an existing member) never re-triggers the new-user celebration. const WELCOME_KEY = "naise-auth-welcome"; +// Tracks identities (email/phone) that have signed in on this browser before. +// Lets us suppress the welcome modal when a returning member signs back in +// without needing a real backend lookup. JSON-encoded array of strings. +const KNOWN_IDENTITIES_KEY = "naise-auth-known"; type SignInInput = { method: AuthMethod; @@ -49,6 +54,43 @@ function defaultName(input: SignInInput): string { return "Naise Member"; } +// Stable per-identity key used to recognize a returning member. Phone +// numbers are normalised by stripping spaces; email is lowercased. The key +// includes the method so a Google account and a phone number that happen to +// share a string don't collide. +function identityKey(input: SignInInput): string | null { + if (input.method === "google" && input.email) { + return `google:${input.email.trim().toLowerCase()}`; + } + if (input.method === "phone" && input.phone) { + return `phone:${input.phone.replace(/\s+/g, "")}`; + } + return null; +} + +function readKnownIdentities(): Set { + try { + const raw = localStorage.getItem(KNOWN_IDENTITIES_KEY); + if (!raw) return new Set(); + const parsed: unknown = JSON.parse(raw); + if (!Array.isArray(parsed)) return new Set(); + return new Set(parsed.filter((v): v is string => typeof v === "string")); + } catch { + return new Set(); + } +} + +function writeKnownIdentities(known: Set): void { + try { + localStorage.setItem( + KNOWN_IDENTITIES_KEY, + JSON.stringify([...known]), + ); + } catch { + // Non-fatal; worst case we re-show the welcome modal next time. + } +} + export function AuthProvider({ children }: { children: React.ReactNode }) { // Start signed-out so the first client render matches the server HTML; the // persisted session loads in the effect below (same approach as the cart, @@ -66,6 +108,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { } catch { // Ignore malformed/unavailable storage; start as a guest. } + // Make sure every visitor has an owner id from first paint, so guest + // orders attribute correctly even before they ever sign in. + getOrCreateOwnerId(); setHydrated(true); }, []); @@ -82,28 +127,63 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { }, [user, hydrated]); const signIn = useCallback((input: SignInInput) => { + // Adopt the existing per-browser owner id as the user's id. This is the + // mechanism that carries guest orders into the new account: every order + // placed before sign-in already has this same ownerId, so the profile's + // `listOrdersFor(ownerId)` query keeps showing them. (In Supabase later, + // the user's auth.uid() takes over and we run a one-shot UPDATE keyed on + // this id to migrate the rows.) + const ownerId = getOrCreateOwnerId(); + + // Returning identity? Skip the welcome modal. New identity? Arm it and + // remember the identity for next time. A sign-in that doesn't carry an + // identity key (shouldn't happen with Google/phone, but defensive) is + // treated as new. + const key = identityKey(input); + const known = readKnownIdentities(); + const isReturning = key !== null && known.has(key); + const next: AuthUser = { - id: crypto.randomUUID(), + id: ownerId, method: input.method, email: input.email, phone: input.phone, name: defaultName(input), }; setUser(next); - // Arm the one-time welcome. In the mock there's no existing-account - // lookup, so every sign-in is treated as a new member; the flag itself - // guarantees it only ever fires once per browser. - setShowWelcome(true); - try { - localStorage.setItem(WELCOME_KEY, "1"); - } catch { - // Non-fatal; the in-memory flag still drives this session's modal. + // Keep the cookie/localStorage owner id pinned to the user's id so future + // server reads see the same value. + setOwnerId(ownerId); + + if (!isReturning) { + setShowWelcome(true); + try { + localStorage.setItem(WELCOME_KEY, "1"); + } catch { + // Non-fatal; the in-memory flag still drives this session's modal. + } + if (key !== null) { + known.add(key); + writeKnownIdentities(known); + } + } else { + // Returning member — make sure no stale welcome flag fires. + setShowWelcome(false); + try { + localStorage.removeItem(WELCOME_KEY); + } catch { + // Non-fatal. + } } }, []); const signOut = useCallback(() => { setUser(null); setShowWelcome(false); + // Intentionally keep the owner id intact. A signed-out browser is back to + // being a "guest" — orders placed in this state should still attach to + // the same id, so when the same person signs in again (or registers) + // their full history follows them. }, []); const dismissWelcome = useCallback(() => { diff --git a/supabase/.temp/cli-latest b/supabase/.temp/cli-latest new file mode 100644 index 0000000..95ea209 --- /dev/null +++ b/supabase/.temp/cli-latest @@ -0,0 +1 @@ +v2.106.0 \ No newline at end of file diff --git a/types/order.ts b/types/order.ts index 3a0a0d3..71645cc 100644 --- a/types/order.ts +++ b/types/order.ts @@ -30,6 +30,11 @@ export type Order = { token: string; // Human reference, e.g. NAISE-000001. orderNumber: string; + // The browser/account that placed this order. Stable id from + // `lib/auth/owner-id` — same value for a guest and the member they later + // become, so guest orders carry over to the new account on sign-up. Maps + // onto `orders.user_id` (auth.uid()) in Supabase later. + ownerId: string; status: OrderStatus; paymentMethod: string; items: OrderLine[]; diff --git a/wrangler.jsonc b/wrangler.jsonc index cb08f47..8e20048 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -6,4 +6,9 @@ "compatibility_date": "2025-03-01", "compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"], "assets": { "directory": ".open-next/assets", "binding": "ASSETS" }, + // Public, non-sensitive vars. Secrets (TELEGRAM_*) are set via `wrangler secret put` + // or the dashboard, never here — this file is committed to git. + "vars": { + "NEXT_PUBLIC_SITE_URL": "https://naisecoffee.utemride.my", + }, } From 2188e67c7529529457443b0e4a8a128ca43b402a Mon Sep 17 00:00:00 2001 From: devHanif Date: Wed, 17 Jun 2026 03:13:51 +0800 Subject: [PATCH 2/2] feat(auth): real Supabase Google OAuth, profiles + Storage avatars, RLS hardening Implements the full Supabase auth stack (the prior commit only landed scaffolding): browser/server/proxy clients, SSR session refresh via proxy.ts, Google OAuth callback route, and a real profiles.role gate replacing the naise_role cookie. Profile screen + edit are now backed by the profiles table (mock data removed); avatars upload to a public Storage bucket. Missing rows self-heal on load and edits persist via upsert. One-time welcome modal now uses an atomic profiles.welcomed_at claim (DB-enforced once-per-account) instead of localStorage, fixing the modal re-popping on tab refocus. Security: a BEFORE UPDATE trigger pins profiles.role for non-privileged writers, closing a client-side role-escalation hole. Redacted a key from the planning doc, hardened .gitignore (secrets + supabase/.temp), and untracked the CLI scratch file. Migrations: auth_profiles, avatars_storage, profiles_welcomed_at, profiles_guard_role. --- .dev.vars.example | 4 + .env.example | 3 + .gitignore | 12 + .hermes/plans/2026-06-15_auth-google-oauth.md | 3 +- app/(auth)/auth/callback/route.ts | 23 ++ app/(customer)/profile/settings/page.tsx | 70 +---- components/auth-screen.tsx | 23 +- components/profile-edit-screen.tsx | 67 ++++- components/profile-screen.tsx | 70 ++++- data/profile.ts | 10 - lib/auth/session.ts | 26 +- lib/supabase/avatar.ts | 44 +++ lib/supabase/client.ts | 11 + lib/supabase/proxy.ts | 37 +++ lib/supabase/server.ts | 31 ++ package-lock.json | 120 ++++++++ package.json | 2 + proxy.ts | 16 ++ store/auth.tsx | 265 ++++++++++-------- store/profile.tsx | 163 ++++++++--- supabase/.temp/cli-latest | 1 - .../20260616222010_auth_profiles.sql | 100 +++++++ .../20260616223000_avatars_storage.sql | 55 ++++ .../20260616224500_profiles_welcomed_at.sql | 9 + .../20260616225500_profiles_guard_role.sql | 34 +++ types/auth.ts | 8 +- types/database.ts | 192 +++++++++++++ 27 files changed, 1126 insertions(+), 273 deletions(-) create mode 100644 app/(auth)/auth/callback/route.ts delete mode 100644 data/profile.ts create mode 100644 lib/supabase/avatar.ts create mode 100644 lib/supabase/client.ts create mode 100644 lib/supabase/proxy.ts create mode 100644 lib/supabase/server.ts create mode 100644 proxy.ts delete mode 100644 supabase/.temp/cli-latest create mode 100644 supabase/migrations/20260616222010_auth_profiles.sql create mode 100644 supabase/migrations/20260616223000_avatars_storage.sql create mode 100644 supabase/migrations/20260616224500_profiles_welcomed_at.sql create mode 100644 supabase/migrations/20260616225500_profiles_guard_role.sql create mode 100644 types/database.ts diff --git a/.dev.vars.example b/.dev.vars.example index 1d6f42b..1856271 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -6,6 +6,10 @@ NEXTJS_ENV=development # Public store URL for local preview NEXT_PUBLIC_SITE_URL=http://localhost:3000 +# Supabase Auth — client-safe (publishable key is meant for the browser) +NEXT_PUBLIC_SUPABASE_URL= +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= + # Telegram order notifications — server-only secrets. # TELEGRAM_BOT_TOKEN: from @BotFather (e.g. 123456789:ABCdef...). # TELEGRAM_CHAT_ID: target group chat id (negative for groups, e.g. -1001234567890). diff --git a/.env.example b/.env.example index 5570d0c..2d27cba 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,8 @@ # Supabase — client-safe (exposed to the browser) NEXT_PUBLIC_SUPABASE_URL= +# New-style key (used by the app). Format: sb_publishable_... +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= +# Legacy key — kept as a placeholder for any future server-side tooling that still expects it. NEXT_PUBLIC_SUPABASE_ANON_KEY= # Supabase — server-only. NEVER import into client components. diff --git a/.gitignore b/.gitignore index 355eb22..0bd7bdf 100644 --- a/.gitignore +++ b/.gitignore @@ -28,7 +28,16 @@ # misc .DS_Store + +# secrets / credentials — never commit keys, certs, or service-account files *.pem +*.key +*.p12 +*.pfx +*.crt +*-key.json +service-account*.json +gha-creds-*.json # debug npm-debug.log* @@ -53,3 +62,6 @@ yarn-error.log* # typescript *.tsbuildinfo next-env.d.ts + +# supabase CLI scratch +/supabase/.temp/ diff --git a/.hermes/plans/2026-06-15_auth-google-oauth.md b/.hermes/plans/2026-06-15_auth-google-oauth.md index 5d7d583..6306151 100644 --- a/.hermes/plans/2026-06-15_auth-google-oauth.md +++ b/.hermes/plans/2026-06-15_auth-google-oauth.md @@ -76,8 +76,9 @@ NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= Add the real values to `.env.local` (gitignored): ```bash NEXT_PUBLIC_SUPABASE_URL=https://hodukwhqjhjzyfxlsovp.supabase.co -NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_MLdycDnv7gtNWLHoxa0SIQ_jO2BeKl4 +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= ``` +> Do NOT paste real key values into this plan (or any tracked file). Keys belong only in the gitignored `.env.local` / `.dev.vars`. Mirror both into `.dev.vars.example` (names) and `.dev.vars` (values) so the `opennextjs-cloudflare preview` Worker runtime sees them too. **Verify:** `grep PUBLISHABLE .env.local .dev.vars` shows the key in both; `.env.example`/`.dev.vars.example` carry the names only. diff --git a/app/(auth)/auth/callback/route.ts b/app/(auth)/auth/callback/route.ts new file mode 100644 index 0000000..a1c036b --- /dev/null +++ b/app/(auth)/auth/callback/route.ts @@ -0,0 +1,23 @@ +import { NextResponse } from "next/server"; +import { createClient } from "@/lib/supabase/server"; + +// Supabase redirects here after Google. Exchange the PKCE code for a session +// (cookies are set by the server client), then send the user to `next`. +export async function GET(request: Request) { + const { searchParams, origin } = new URL(request.url); + const code = searchParams.get("code"); + const rawNext = searchParams.get("next") ?? "/home"; + // Only allow same-site relative redirects. + const next = + rawNext.startsWith("/") && !rawNext.startsWith("//") ? rawNext : "/home"; + + if (code) { + const supabase = await createClient(); + const { error } = await supabase.auth.exchangeCodeForSession(code); + if (!error) { + return NextResponse.redirect(`${origin}${next}`); + } + } + + return NextResponse.redirect(`${origin}/login?error=auth`); +} diff --git a/app/(customer)/profile/settings/page.tsx b/app/(customer)/profile/settings/page.tsx index a11ed02..f4c7b66 100644 --- a/app/(customer)/profile/settings/page.tsx +++ b/app/(customer)/profile/settings/page.tsx @@ -1,39 +1,15 @@ import type { Metadata } from "next"; import Link from "next/link"; -import { cookies } from "next/headers"; -import { - ChevronLeft, - Lock, - Bell, - ShieldCheck, -} from "lucide-react"; +import { ChevronLeft, Lock, Bell, ShieldCheck } from "lucide-react"; export const metadata: Metadata = { title: "Settings", description: "Account and security settings for your Naise Coffee profile.", }; -// Dev-only role toggle: flips the `naise_role` cookie that the management gate -// (lib/auth/session.ts) reads, so the staff /manage surface can be exercised -// before Supabase Auth lands. Moved here from the profile screen — it's a -// security/role control, not a profile field. Server action (no client JS). -async function toggleAdminRole() { - "use server"; - - const cookieStore = await cookies(); - const isAdmin = cookieStore.get("naise_role")?.value === "admin"; - - if (isAdmin) { - cookieStore.delete("naise_role"); - } else { - cookieStore.set("naise_role", "admin", { - path: "/", - maxAge: 60 * 60 * 24 * 7, - }); - } -} - -// Security rows are placeholders until Supabase Auth lands. +// Security rows are placeholders until the related auth features land. Staff/ +// admin access to /manage is granted via `profiles.role` in Supabase (no dev +// toggle here anymore — set the role directly in the DB to test). const securityRows = [ { label: "Change Password", description: "Update your password", icon: Lock }, { @@ -48,10 +24,7 @@ const securityRows = [ }, ] as const; -export default async function ProfileSettingsPage() { - const cookieStore = await cookies(); - const isAdmin = cookieStore.get("naise_role")?.value === "admin"; - +export default function ProfileSettingsPage() { return (
@@ -70,10 +43,7 @@ export default async function ProfileSettingsPage() {
{/* Security — placeholder rows until auth lands. */} -
+

Security

@@ -102,34 +72,6 @@ export default async function ProfileSettingsPage() { })}
- - {/* Dev role control — flips the staff-access cookie for testing the - /manage surface. Visible only outside production. */} - {process.env.NODE_ENV !== "production" && ( -
-

- Developer -

-
-

- {isAdmin - ? "You currently have staff access — the Manage Orders surface is unlocked." - : "Grant staff access to open the Manage Orders surface."} -

-
- -
-
-
- )}
); diff --git a/components/auth-screen.tsx b/components/auth-screen.tsx index 88f5215..0024014 100644 --- a/components/auth-screen.tsx +++ b/components/auth-screen.tsx @@ -7,6 +7,7 @@ import { useRouter, useSearchParams } from "next/navigation"; import { ChevronLeft, Coffee, Flame, Loader2, Phone, Star } from "lucide-react"; import { images } from "@/constants/images"; import { useAuth } from "@/store/auth"; +import { createClient } from "@/lib/supabase/client"; // Google "G" mark — lucide ships no brand glyphs, so this is an inline SVG // (allowed image-rule exception). Kept here next to its only use. @@ -61,6 +62,9 @@ export function AuthScreen() { const [otp, setOtp] = useState(""); const [pending, setPending] = useState<"google" | "phone" | null>(null); + // MOCKED — phone/OTP is not yet wired to Supabase. It still uses the local + // auth-store mock (`signIn`) until WhatsApp/WABA is approved (a later plan). + // Google sign-in below is the real Supabase OAuth flow; this is not. function finish( method: "google" | "phone", extra: Parameters[0], @@ -73,12 +77,21 @@ export function AuthScreen() { }, 700); } - function onGoogle() { - finish("google", { - method: "google", - email: "member@gmail.com", - name: "Naise Member", + async function onGoogle() { + setPending("google"); + const supabase = createClient(); + const { error } = await supabase.auth.signInWithOAuth({ + provider: "google", + options: { + redirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(redirect)}`, + }, }); + if (error) { + setPending(null); + // TODO: surface a toast; for now log so failures aren't silent. + console.error("Google sign-in failed", error); + } + // On success the browser navigates away to Google — no further work here. } function onSendOtp(e: React.FormEvent) { diff --git a/components/profile-edit-screen.tsx b/components/profile-edit-screen.tsx index d593aaa..e5225ca 100644 --- a/components/profile-edit-screen.tsx +++ b/components/profile-edit-screen.tsx @@ -3,32 +3,65 @@ import { useRef, useState } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; -import { ChevronLeft, Camera } from "lucide-react"; +import { ChevronLeft, Camera, Loader2 } from "lucide-react"; +import { useAuth } from "@/store/auth"; import { useProfile } from "@/store/profile"; +import { uploadAvatar } from "@/lib/supabase/avatar"; import { ProfileAvatar } from "@/components/profile-avatar"; // Edit Profile — photo and display name only (security lives in Settings). -// Writes to the localStorage-backed profile store, then returns to /profile. +// Persists to the Supabase `profiles` row: the picked photo is uploaded to the +// `avatars` Storage bucket, then its public URL + the display name are written +// to the row via the profile store. Returns to /profile on success. export function ProfileEditScreen() { const router = useRouter(); + const { user } = useAuth(); const { profile, updateProfile } = useProfile(); const fileRef = useRef(null); const [displayName, setDisplayName] = useState(profile.displayName); - const [avatarUrl, setAvatarUrl] = useState(profile.avatarUrl); + // Preview shown in the avatar. Starts at the stored URL; swaps to a local + // object URL the moment a new file is picked (instant feedback before upload). + const [previewUrl, setPreviewUrl] = useState(profile.avatarUrl); + // The newly-picked file, held until save so we only upload on confirm. + const [pickedFile, setPickedFile] = useState(null); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); function onPickPhoto(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (!file) return; - const reader = new FileReader(); - reader.onload = () => setAvatarUrl(reader.result as string); - reader.readAsDataURL(file); + setError(null); + setPickedFile(file); + setPreviewUrl(URL.createObjectURL(file)); } - function onSave(e: React.FormEvent) { + async function onSave(e: React.FormEvent) { e.preventDefault(); - updateProfile({ displayName: displayName.trim() || profile.displayName, avatarUrl }); - router.push("/profile"); + if (saving) return; + if (!user) { + setError("You need to be signed in to edit your profile."); + return; + } + + setSaving(true); + setError(null); + try { + // Upload the new photo first (if one was picked) so we persist a real + // Storage URL, not the temporary local preview. + let avatarUrl = profile.avatarUrl; + if (pickedFile) { + avatarUrl = await uploadAvatar(pickedFile, user.id); + } + await updateProfile({ + displayName: displayName.trim() || profile.displayName, + avatarUrl, + }); + router.push("/profile"); + } catch { + setError("Couldn't save your changes. Please try again."); + setSaving(false); + } } return ( @@ -58,7 +91,7 @@ export function ProfileEditScreen() { > @@ -76,7 +109,7 @@ export function ProfileEditScreen() { @@ -101,11 +134,19 @@ export function ProfileEditScreen() { /> + {error && ( +

+ {error} +

+ )} + diff --git a/components/profile-screen.tsx b/components/profile-screen.tsx index 710ae26..755d537 100644 --- a/components/profile-screen.tsx +++ b/components/profile-screen.tsx @@ -57,13 +57,28 @@ const menuRows = [ // Their recent orders are still shown — scoped server-side to the per-browser // owner id, which carries over to the account they later register. export function ProfileScreen({ recentOrders }: { recentOrders: Order[] }) { - const { profile } = useProfile(); + const { profile, hydrated: profileHydrated } = useProfile(); const { balance } = useBeans(); - const { isAuthenticated, signOut } = useAuth(); + const { isAuthenticated, hydrated: authHydrated, signOut } = useAuth(); const [signOutOpen, setSignOutOpen] = useState(false); const tier = getTierProgress(balance); + // Identity shown in the hero comes straight from the profile store, which is + // now backed by the `profiles` row (display_name / avatar_url / created_at) + // and falls back to the session identity internally if the row is missing. + // So an edited display name/photo always wins, and there's no mock left. + const displayName = profile.displayName; + const avatarUrl = profile.avatarUrl; + const memberSince = profile.memberSince; + + // Both stores must settle before we know what to show. Until then we render a + // neutral skeleton hero rather than guessing — otherwise the screen flashes + // through three states on load (guest → fallback name → real profile) as auth + // resolves and then the profile row fetches. Gating on both flags collapses + // that into a single reveal. + const ready = authHydrated && profileHydrated; + return (
{/* Header — back returns to Home; title matches the other screens' @@ -84,23 +99,42 @@ export function ProfileScreen({ recentOrders }: { recentOrders: Order[] }) {
{/* Identity hero. Members see avatar + display name + member-since; - guests see a silhouette + "Guest" + a sign-in nudge. */} - {isAuthenticated ? ( + guests see a silhouette + "Guest" + a sign-in nudge. Until both the + auth and profile stores settle we show a neutral skeleton so the + screen reveals the resolved identity once, with no flash-through. */} + {!ready ? ( +
+ + + + Loading profile… +
+ ) : isAuthenticated ? (

- {profile.displayName} + {displayName}

- {memberSinceLabel(profile.memberSince)} + {memberSinceLabel(memberSince)}

) : ( @@ -122,8 +156,9 @@ export function ProfileScreen({ recentOrders }: { recentOrders: Order[] }) { )} {/* Beans + tier summary — members only. Hidden for guests since - they can't earn or redeem until they have an account. */} - {isAuthenticated && ( + they can't earn or redeem until they have an account. Gated on + `ready` so it doesn't pop in during the skeleton stage. */} + {ready && isAuthenticated && ( + ) : isAuthenticated ? (