Skip to content

Dev - #10

Merged
devHanif-git merged 3 commits into
masterfrom
dev
Jun 16, 2026
Merged

Dev#10
devHanif-git merged 3 commits into
masterfrom
dev

Conversation

@devHanif-git

@devHanif-git devHanif-git commented Jun 16, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

Release Notes

  • New Features
    • Added “owner/device” correlation so orders are attributed and shown only for the current owner.
    • Implemented Google OAuth sign-in and added a callback redirect flow.
    • Added sign-out confirmation and auth-aware profile UI (guest vs signed-in).
    • Profile data is now persisted, including avatar upload.
  • Updates
    • Refreshed reward tier perk wording.
    • Profile “Recent Orders” messaging now adapts to authentication state.
  • Chores
    • Updated environment templates and ignore rules for local development.

… 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.
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Integrates Supabase Auth with Google OAuth to replace mocked localStorage sessions, adds a stable per-browser owner ID for order attribution, implements Supabase database schema with role-based RLS, updates profile and checkout flows for owner scoping, and adds authentication-aware UI with sign-out confirmation and avatar uploads.

Changes

Supabase Auth System and Owner ID Attribution

Layer / File(s) Summary
Owner ID: shared constants, client, and server modules
lib/auth/owner-id-shared.ts, lib/auth/owner-id.ts, lib/auth/owner-id-server.ts
Establishes owner ID infrastructure with cookie/storage key constants; client-side getOrCreateOwnerId and setOwnerId manage localStorage+cookie sync; server-side getOwnerIdFromCookie helper reads from Next.js cookies.
Order type, store filtering, and mock data updates
types/order.ts, lib/orders/store.ts, data/mock-order.ts
Extends Order type with ownerId field; adds listOrdersFor(ownerId) to filter orders; introduces SEED_OWNER_ID constant and tags four seeded mock orders; updates mockOrder() to include ownerId: "mock-test".
Checkout action and UI: ownerId validation and injection
app/(customer)/checkout/actions.ts, components/checkout-screen.tsx
PlaceOrderInput gains required ownerId; placeOrder validates and early-returns error if missing; CheckoutScreen calls getOrCreateOwnerId() and injects result into payload.
Supabase browser, server, and proxy clients
lib/supabase/client.ts, lib/supabase/server.ts, lib/supabase/proxy.ts, proxy.ts
Browser client factory with createClient() using @supabase/ssr; SSR server client with cookie wiring; updateSession() proxy validates/refreshes JWT per request; root proxy.ts exports handler with route matcher.
Supabase database migrations: profiles, roles, RLS, and avatars
supabase/migrations/20260616222010_auth_profiles.sql, .../20260616223000_avatars_storage.sql, .../20260616224500_profiles_welcomed_at.sql, .../20260616225500_profiles_guard_role.sql
Creates user_role enum, profiles table with auto-creation trigger on signup, current_user_role() security-definer, and RLS policies for role-based access control; configures public avatars bucket with 2MB limit and user-scoped access rules; adds welcomed_at column and role-escalation guard trigger.
Auth store: Supabase session hydration and welcome claim logic
store/auth.tsx
Replaces localStorage mocks with Supabase sessions; introduces userFromSession() mapping session data to AuthUser, and claimWelcome() atomically setting welcomed_at; ensures per-browser ownerId on hydration; listens to onAuthStateChange for live updates.
Profile store: Supabase-backed persistence with healing and async updates
store/profile.tsx
Migrates from localStorage to Supabase: fetches profiles row on auth hydration, heals missing rows via upsert, handles errors with identity fallbacks; updateProfile becomes async with full Supabase upsert().select().single() flow.
OAuth callback handler and auth screen Google sign-in wiring
app/(auth)/auth/callback/route.ts, components/auth-screen.tsx
Callback route exchanges OAuth code for Supabase session with same-site next redirect validation; AuthScreen wires Google button to signInWithOAuth() with computed redirect URL.
Profile server pages: async owner-scoped data fetching
app/(customer)/profile/page.tsx, app/(customer)/profile/orders/page.tsx
Both become async server components; derive ownerId from cookie and fetch orders via listOrdersFor(ownerId) instead of unscoped listOrders().
Profile UI: guest/member conditional rendering and sign-out modal
components/signout-confirm-modal.tsx, components/profile-screen.tsx
New modal with Escape-key/body-scroll side effects and ARIA attributes; ProfileScreen adds conditional guest/member hero (skeleton while hydrating), hides Beans/Account rows for guests, varies Recent Orders heading, routes sign-out through modal.
Profile edit screen: async avatar upload and Supabase persistence
components/profile-edit-screen.tsx, lib/supabase/avatar.ts
Profile edit becomes async authenticated flow with Supabase avatar upload to avatars bucket under user-scoped paths; adds preview state, saving/error flags, Loader2 spinner, and error message display; helper maps MIME types to file extensions with cache-buster URLs.
Session role lookup and access control
lib/auth/session.ts, app/(customer)/profile/settings/page.tsx
getSessionRole() now derives role from Supabase profiles table via security-definer; settings page removes dev role toggle and becomes synchronous.
Dependencies, environment config, and type definitions
package.json, .env.example, .dev.vars.example, .gitignore, wrangler.jsonc, types/database.ts
Adds Supabase packages; updates env examples with Supabase/Telegram placeholders; expands gitignore for credentials/Supabase CLI artifacts; adds site URL to wrangler vars; creates database schema types with recursive Json and generic Tables, TablesInsert, TablesUpdate helpers.
AuthUser type extension, Order type addition, and mock profile removal
types/auth.ts, data/profile.ts, data/rewards.ts
Extends AuthUser with optional avatarUrl and createdAt for OAuth metadata; removes mockProfile constant; updates reward tier perk text removing Beans-multiplier wording.
Hermes implementation plan for Google OAuth phases
.hermes/plans/2026-06-15_auth-google-oauth.md
Documents ten-phase OAuth implementation plan covering setup, client scaffolding, database schema, callback, OAuth wiring, role-based access, and verification as specification and checklist for this PR.

Sequence Diagram(s)

sequenceDiagram
  participant User as User (Browser)
  participant AuthScreen
  participant Supabase as Supabase Auth
  participant Callback as /auth/callback
  participant Browser as Browser (Post-Redirect)
  participant AuthProvider
  participant ProfileStore

  User->>AuthScreen: Click "Sign in with Google"
  AuthScreen->>Supabase: signInWithOAuth({ provider: "google", redirectTo: ... })
  Supabase->>User: Redirect to Google OAuth login
  User->>Supabase: Complete Google auth
  Supabase->>Callback: Redirect with code + next
  Callback->>Supabase: exchangeCodeForSession(code)
  Supabase-->>Callback: session object
  Callback->>Browser: Redirect to origin + next (cookies set)
  Browser->>AuthProvider: onAuthStateChange fires
  AuthProvider->>Supabase: auth.getUser()
  Supabase-->>AuthProvider: user object
  AuthProvider->>AuthProvider: userFromSession() → AuthUser
  AuthProvider->>AuthProvider: claimWelcome() → set welcomed_at
  AuthProvider-->>Browser: user + showWelcome signal
  Browser->>ProfileStore: Effect on user.id
  ProfileStore->>Supabase: Fetch profiles row (RLS enforced)
  Supabase-->>ProfileStore: profile data
  ProfileStore-->>Browser: Profile hydrated
Loading
sequenceDiagram
  participant CheckoutScreen
  participant getOrCreateOwnerId as lib/auth/owner-id.ts
  participant localStorage
  participant Cookie as HTTP Cookie
  participant placeOrder as placeOrder action
  participant ordersStore as lib/orders/store.ts

  CheckoutScreen->>getOrCreateOwnerId: getOrCreateOwnerId()
  getOrCreateOwnerId->>localStorage: read OWNER_ID_STORAGE_KEY
  alt id exists
    localStorage-->>getOrCreateOwnerId: existing id
  else id missing
    getOrCreateOwnerId->>getOrCreateOwnerId: crypto.randomUUID()
    getOrCreateOwnerId->>localStorage: persist new id
  end
  getOrCreateOwnerId->>Cookie: writeCookie(id, SameSite=Lax)
  getOrCreateOwnerId-->>CheckoutScreen: ownerId
  CheckoutScreen->>placeOrder: { ...input, ownerId }
  placeOrder->>placeOrder: validate ownerId non-empty
  placeOrder->>ordersStore: createOrder({ ..., ownerId })
  ordersStore-->>placeOrder: Order with ownerId
  placeOrder-->>CheckoutScreen: { ok: true, order }
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • devHanif-git/naise-coffee-platform#7: Both modify store/auth.tsx, sign-in/sign-out flow, and welcome-modal behavior; this PR upgrades from localStorage/cookie mocks to Supabase-backed OAuth and adds owner-ID persistence.
  • devHanif-git/naise-coffee-platform#4: Both modify app/(customer)/checkout/actions.ts; retrieved PR adds Telegram messaging while this PR adds ownerId validation and Supabase order attribution.

Poem

🐇 From localStorage dreams to Supabase reality,
A rabbit hops through OAuth with formality!
Each guest gets a cookie, each member a role,
RLS guards profiles, protecting the whole.
The profile page whispers what orders belong,
To guest or to member—the attribution so strong! 🍪✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The pull request title 'Dev' is vague and generic, providing no meaningful information about the actual changes made. Replace 'Dev' with a descriptive title that summarizes the main change, such as 'Add Supabase Auth with Google OAuth and owner-scoped orders' or 'Implement real authentication and profile persistence.'
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dev

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed: one or more packages not found in the registry.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
❌ Deployment failed
View logs
naise-coffee-platform 2188e67 Jun 16 2026, 07:18 PM

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
store/auth.tsx (1)

102-114: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Sync owner-id from persisted user before minting a new one.

On Line 113, getOrCreateOwnerId() always runs even when a persisted session exists. If AUTH_KEY is present but OWNER_ID_STORAGE_KEY was cleared, this mints a new ownerId and breaks server-side order scoping continuity for that signed-in user.

Suggested patch
   useEffect(() => {
+    let persistedUser: AuthUser | null = null;
     try {
       const raw = localStorage.getItem(AUTH_KEY);
       // eslint-disable-next-line react-hooks/set-state-in-effect -- one-time sync from localStorage
-      if (raw) setUser(JSON.parse(raw) as AuthUser);
+      if (raw) {
+        persistedUser = JSON.parse(raw) as AuthUser;
+        setUser(persistedUser);
+      }
       if (localStorage.getItem(WELCOME_KEY) === "1") setShowWelcome(true);
     } 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();
+    if (persistedUser?.id) setOwnerId(persistedUser.id);
+    else getOrCreateOwnerId();
     setHydrated(true);
   }, []);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@store/auth.tsx` around lines 102 - 114, The getOrCreateOwnerId() function is
called unconditionally in the useEffect hook, which means it will always mint a
new owner ID even when a persisted user session exists via AUTH_KEY. This breaks
order scoping continuity for signed-in users if OWNER_ID_STORAGE_KEY was
cleared. Fix this by checking whether a persisted user was successfully loaded
from localStorage before calling getOrCreateOwnerId(). If raw data from AUTH_KEY
exists and was successfully parsed into the user state, sync the owner-id from
that persisted user first. Only call getOrCreateOwnerId() when necessary, such
as when no persisted user exists or when the stored owner-id is missing, to
avoid minting a new ID and breaking the server-side order attribution.
🧹 Nitpick comments (1)
components/signout-confirm-modal.tsx (1)

28-73: ⚡ Quick win

Consider adding focus management for better accessibility.

The modal has good ARIA attributes but lacks focus trap and initial focus management. Screen reader and keyboard users can tab outside the visible dialog to elements behind the backdrop.

For a production-quality modal, consider:

  1. Auto-focusing the Cancel button (or dialog) on open
  2. Trapping focus within the dialog while open
  3. Returning focus to the trigger button on close

This can be achieved with a library like @radix-ui/react-dialog or a custom focus-trap hook.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/signout-confirm-modal.tsx` around lines 28 - 73, The modal
component lacks focus management for accessibility. Add auto-focus to the Cancel
button (or the dialog container) when the modal opens so keyboard users start in
the interactive area. Implement focus trapping to prevent keyboard navigation
from moving focus outside the dialog to elements behind the backdrop while the
modal is open. Additionally, restore focus back to the trigger button when
onClose is called. This can be achieved by adding a useEffect hook to manage
focus on mount/unmount, or by adopting a library like `@radix-ui/react-dialog`
which handles focus management automatically.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.hermes/plans/2026-06-15_auth-google-oauth.md:
- Around line 78-80: Replace the actual Supabase publishable key value in the
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY environment variable with a redacted
placeholder like `sb_publishable_<REDACTED>` to remove the exposed credential
from the committed plan file. Add a note or instruction adjacent to this
configuration explaining that users should retrieve the actual publishable key
from their Supabase dashboard and update the value locally, preventing the real
key from being stored in version history while maintaining clear documentation
on where to find it.

In `@app/`(customer)/checkout/actions.ts:
- Around line 43-47: The checkout action is accepting `input.ownerId` from the
client and using it directly to persist orders, which allows tampering to
attribute an order to a different owner. Instead of relying on the
client-supplied `ownerId` value, resolve the actual owner identity from the
server-side session or cookies, and use that server-resolved value when creating
or persisting the order. You may optionally validate that the client's claimed
`ownerId` matches the server-resolved ownership before proceeding, but always
use the server-resolved ownership as the source of truth for persistence.

In `@components/profile-screen.tsx`:
- Around line 108-114: Remove the redundant inline style={{ width: 88, height:
88 }} property from the span element in the profile screen component, as the
size-22 Tailwind class already provides this exact sizing (22 × 4px = 88px).
Delete the entire style prop to follow the coding guideline of using Tailwind
classes instead of hardcoded inline styles.

In `@lib/auth/owner-id.ts`:
- Around line 24-31: The writeCookie function sets a cookie without the Secure
flag, which poses a security risk on HTTPS deployments where plaintext
transmission could occur if an HTTP endpoint becomes reachable. Modify the
cookie string construction in writeCookie to conditionally include the Secure
flag by checking if window.location.protocol equals "https:", and append ";
Secure" to the cookie string only when that condition is true, keeping the
existing behavior for non-HTTPS environments like localhost development.

In `@store/auth.tsx`:
- Around line 19-23: Replace plaintext email/phone identifiers being stored in
the KNOWN_IDENTITIES_KEY with privacy-preserving alternatives. In the code
section around lines 57-67 where identities are being stored (likely in state
update or persistence logic), replace the raw email/phone values with either an
ownerId-based identifier or irreversibly hashed identifiers before adding them
to the KNOWN_IDENTITIES_KEY storage. Then update the corresponding retrieval and
comparison logic in the lines 71-93 section to work with the new non-PII format
instead of plaintext email/phone values.
- Around line 180-187: The signOut function in store/auth.tsx clears the
in-memory welcome state by calling setShowWelcome(false), but it does not remove
the persisted WELCOME_KEY from localStorage. This causes the welcome flag to
remain in localStorage even after sign-out, which can unexpectedly re-open the
welcome modal on subsequent page loads. Add a call to
localStorage.removeItem(WELCOME_KEY) in the signOut function alongside the
existing setShowWelcome(false) call to ensure both the in-memory state and the
persisted storage are cleared when the user signs out.
- Around line 65-67: The phone number normalization in the identity key
generation is incomplete, only removing whitespace but not other formatting
characters like hyphens and parentheses, causing different formats of the same
number to generate different keys. Enhance the normalization logic in the return
statement where input.method === "phone" to remove all non-digit characters
(while preserving the leading plus sign if present) to ensure phone numbers are
normalized consistently regardless of their formatting.

---

Outside diff comments:
In `@store/auth.tsx`:
- Around line 102-114: The getOrCreateOwnerId() function is called
unconditionally in the useEffect hook, which means it will always mint a new
owner ID even when a persisted user session exists via AUTH_KEY. This breaks
order scoping continuity for signed-in users if OWNER_ID_STORAGE_KEY was
cleared. Fix this by checking whether a persisted user was successfully loaded
from localStorage before calling getOrCreateOwnerId(). If raw data from AUTH_KEY
exists and was successfully parsed into the user state, sync the owner-id from
that persisted user first. Only call getOrCreateOwnerId() when necessary, such
as when no persisted user exists or when the stored owner-id is missing, to
avoid minting a new ID and breaking the server-side order attribution.

---

Nitpick comments:
In `@components/signout-confirm-modal.tsx`:
- Around line 28-73: The modal component lacks focus management for
accessibility. Add auto-focus to the Cancel button (or the dialog container)
when the modal opens so keyboard users start in the interactive area. Implement
focus trapping to prevent keyboard navigation from moving focus outside the
dialog to elements behind the backdrop while the modal is open. Additionally,
restore focus back to the trigger button when onClose is called. This can be
achieved by adding a useEffect hook to manage focus on mount/unmount, or by
adopting a library like `@radix-ui/react-dialog` which handles focus management
automatically.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c9f55154-9564-4d7b-8bb2-56493ef19673

📥 Commits

Reviewing files that changed from the base of the PR and between 8238fa7 and 2074352.

⛔ Files ignored due to path filters (1)
  • supabase/.temp/cli-latest is excluded by !**/.temp/**
📒 Files selected for processing (18)
  • .dev.vars.example
  • .gitignore
  • .hermes/plans/2026-06-15_auth-google-oauth.md
  • app/(customer)/checkout/actions.ts
  • app/(customer)/profile/orders/page.tsx
  • app/(customer)/profile/page.tsx
  • components/checkout-screen.tsx
  • components/profile-screen.tsx
  • components/signout-confirm-modal.tsx
  • data/mock-order.ts
  • data/rewards.ts
  • lib/auth/owner-id-server.ts
  • lib/auth/owner-id-shared.ts
  • lib/auth/owner-id.ts
  • lib/orders/store.ts
  • store/auth.tsx
  • types/order.ts
  • wrangler.jsonc

Comment on lines +43 to +47
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." };
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not persist untrusted input.ownerId as the ownership key.

Line 60 writes caller-controlled ownerId directly, so a tampered action payload can attribute an order to a different owner scope. Resolve ownership on the server (cookie) and optionally enforce equality with the client value before create.

Suggested patch
 import { createOrder } from "`@/lib/orders/store`";
 import { buildOrderMessage } from "`@/lib/orders/message`";
 import { sendTelegramMessage } from "`@/lib/telegram`";
+import { getOwnerIdFromCookie } from "`@/lib/auth/owner-id-server`";
 import type { OrderLine } from "`@/types/order`";
@@
 export async function placeOrder(
   input: PlaceOrderInput,
 ): Promise<PlaceOrderResult> {
@@
-  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 cookieOwnerId = await getOwnerIdFromCookie();
+  if (!cookieOwnerId) {
+    return { ok: false, error: "Missing session id. Refresh and try again." };
+  }
+  if (!input.ownerId?.trim() || input.ownerId !== cookieOwnerId) {
+    return { ok: false, error: "Session mismatch. Refresh and try again." };
+  }
@@
   const order = createOrder({
-    ownerId: input.ownerId,
+    ownerId: cookieOwnerId,
     paymentMethod: input.paymentMethod,

Also applies to: 60-60

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/`(customer)/checkout/actions.ts around lines 43 - 47, The checkout action
is accepting `input.ownerId` from the client and using it directly to persist
orders, which allows tampering to attribute an order to a different owner.
Instead of relying on the client-supplied `ownerId` value, resolve the actual
owner identity from the server-side session or cookies, and use that
server-resolved value when creating or persisting the order. You may optionally
validate that the client's claimed `ownerId` matches the server-resolved
ownership before proceeding, but always use the server-resolved ownership as the
source of truth for persistence.

Comment on lines +108 to +114
<span
aria-hidden
className="flex size-22 items-center justify-center rounded-full bg-neutral-100 text-neutral-400"
style={{ width: 88, height: 88 }}
>
<User className="size-10" strokeWidth={1.75} />
</span>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove redundant inline style; size-22 already resolves to 88px.

The inline style={{ width: 88, height: 88 }} duplicates what size-22 provides (22 × 4px = 88px in Tailwind). Per coding guidelines, static hardcoded values should use Tailwind classes, not inline styles.

Suggested fix
           <span
             aria-hidden
-            className="flex size-22 items-center justify-center rounded-full bg-neutral-100 text-neutral-400"
-            style={{ width: 88, height: 88 }}
+            className="flex size-22 items-center justify-center rounded-full bg-neutral-100 text-neutral-400"
           >
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/profile-screen.tsx` around lines 108 - 114, Remove the redundant
inline style={{ width: 88, height: 88 }} property from the span element in the
profile screen component, as the size-22 Tailwind class already provides this
exact sizing (22 × 4px = 88px). Delete the entire style prop to follow the
coding guideline of using Tailwind classes instead of hardcoded inline styles.

Source: Coding guidelines

Comment thread lib/auth/owner-id.ts
Comment on lines +24 to +31
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`;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add Secure for HTTPS cookie writes.

On Line 29-30, the owner-id cookie is written without Secure; on HTTPS deployments this allows accidental plaintext transmission if an HTTP endpoint is ever reachable. Add Secure when window.location.protocol === "https:".

Suggested patch
 function writeCookie(id: string): void {
+  const secure = window.location.protocol === "https:" ? "; secure" : "";
   // 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`;
+    `max-age=${OWNER_ID_COOKIE_MAX_AGE_SECONDS}; samesite=lax${secure}`;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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`;
}
function writeCookie(id: string): void {
const secure = window.location.protocol === "https:" ? "; secure" : "";
// 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${secure}`;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/auth/owner-id.ts` around lines 24 - 31, The writeCookie function sets a
cookie without the Secure flag, which poses a security risk on HTTPS deployments
where plaintext transmission could occur if an HTTP endpoint becomes reachable.
Modify the cookie string construction in writeCookie to conditionally include
the Secure flag by checking if window.location.protocol equals "https:", and
append "; Secure" to the cookie string only when that condition is true, keeping
the existing behavior for non-HTTPS environments like localhost development.

Comment thread store/auth.tsx Resolved
Comment thread store/auth.tsx Resolved
Comment thread store/auth.tsx Resolved
…LS 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/`(auth)/auth/callback/route.ts:
- Around line 14-23: In the callback route, when the error is returned from
exchangeCodeForSession, log the actual error details using an appropriate logger
before redirecting to the login page. Then in the AuthScreen component, read the
error query parameter from the URL (the error=auth value that gets passed) and
display it as a user-facing error message. Currently the error is silently
discarded and the error parameter is ignored, leaving users with no indication
of what went wrong during OAuth authentication.

In `@components/profile-edit-screen.tsx`:
- Line 3: The code creates blob URLs for photo previews without revoking
previous ones, causing memory leaks. You need to track the current blob URL
(using useRef to store it), revoke the previous blob URL whenever a new preview
is created (at line 36 where the new blob URL is generated), and add a useEffect
cleanup function that runs on component unmount to revoke any remaining blob
URL. Import useEffect from React if not already imported, create a ref to hold
the current blob URL, update it when creating new previews after revoking the
old one, and return a cleanup function from useEffect that calls
URL.revokeObjectURL on the tracked blob URL.

In `@lib/supabase/avatar.ts`:
- Around line 18-24: The avatar upload in the
supabase.storage.from("avatars").upload() call uses upsert: true with
extension-aware paths, which leaves orphaned previous avatar variants publicly
accessible when a user changes MIME types. Before uploading the new avatar file
at the computed path, delete any stale avatar files for that userId with
different extensions by querying the avatars bucket for all files matching the
userId prefix (excluding the new extension) and removing them. This ensures only
the current avatar variant remains publicly accessible after each upload.

In `@lib/supabase/client.ts`:
- Around line 8-9: Replace the non-null assertions (the `!` operator) on
process.env.NEXT_PUBLIC_SUPABASE_URL and
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY in the Supabase client
initialization with explicit validation guards that check if these environment
variables exist, and throw a descriptive error message immediately if they are
missing. Apply the same validation pattern to the corresponding environment
variable checks in server.ts and proxy.ts to ensure consistent fail-fast
behavior across all Supabase client instances.

In `@lib/supabase/proxy.ts`:
- Line 34: The `getClaims()` method call on line 34 returns an object with both
data and error properties, but the current code does not check the error result,
allowing invalid or expired tokens to pass through undetected. Modify the line
to destructure the result from `supabase.auth.getClaims()` into data and error
variables, then check if error exists and handle it appropriately (such as
throwing an error or returning early with an error response) to prevent silent
failures in the proxy hot path.

In `@store/auth.tsx`:
- Around line 196-209: The signOut function calls supabase.auth.signOut()
without error handling, meaning if this call throws (due to network errors or
other issues), the local state is still cleared via setUser(null) and
setShowWelcome(false), leaving the user believing they're signed out while a
valid session may persist server-side. Wrap the supabase.auth.signOut() call in
a try/catch block within the signOut function, and move the setUser(null) and
setShowWelcome(false) calls into the try block so they only execute after
successful sign-out. In the catch block, log the error and optionally display a
toast notification to inform the user that sign-out failed and allow them to
retry. The localStorage clearing can remain in its own separate try/catch as it
is already marked non-fatal.

In `@types/auth.ts`:
- Around line 27-29: Update the comment for the avatarUrl field in the auth.ts
types file to align with project guidelines. The current comment on line 28
misleadingly suggests rendering with plain <img> tags. Replace this guidance
with language that prefers the Next.js <Image> component and only permits plain
<img> as an exception when <Image> cannot be used, consistent with the project's
stated rule: "Use the Next.js <Image> component for all images; use plain <img>
only when <Image> cannot work".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a3a5e336-386e-4d4b-b1f1-1361fd477301

📥 Commits

Reviewing files that changed from the base of the PR and between 2074352 and 2188e67.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (25)
  • .dev.vars.example
  • .env.example
  • .gitignore
  • .hermes/plans/2026-06-15_auth-google-oauth.md
  • app/(auth)/auth/callback/route.ts
  • app/(customer)/profile/settings/page.tsx
  • components/auth-screen.tsx
  • components/profile-edit-screen.tsx
  • components/profile-screen.tsx
  • data/profile.ts
  • lib/auth/session.ts
  • lib/supabase/avatar.ts
  • lib/supabase/client.ts
  • lib/supabase/proxy.ts
  • lib/supabase/server.ts
  • package.json
  • proxy.ts
  • store/auth.tsx
  • store/profile.tsx
  • supabase/migrations/20260616222010_auth_profiles.sql
  • supabase/migrations/20260616223000_avatars_storage.sql
  • supabase/migrations/20260616224500_profiles_welcomed_at.sql
  • supabase/migrations/20260616225500_profiles_guard_role.sql
  • types/auth.ts
  • types/database.ts
💤 Files with no reviewable changes (1)
  • data/profile.ts
✅ Files skipped from review due to trivial changes (4)
  • supabase/migrations/20260616224500_profiles_welcomed_at.sql
  • proxy.ts
  • .dev.vars.example
  • .hermes/plans/2026-06-15_auth-google-oauth.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/profile-screen.tsx

Comment on lines +14 to +23
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`);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify /login route exists and check where auth screens are mounted
echo "=== Searching for login page route ==="
fd -t f 'page.tsx' --exec rg -l 'AuthScreen|login' {} \;

echo ""
echo "=== Checking app route structure for login ==="
fd -t f 'page.tsx' -p 'app.*login'

echo ""
echo "=== All page.tsx files in auth group ==="
fd -t f 'page.tsx' -p 'app/\(auth\)'

Repository: devHanif-git/naise-coffee-platform

Length of output: 451


Log OAuth exchange failures and handle the error parameter in the login UI.

The error from exchangeCodeForSession is silently discarded, and the error query parameter is sent to /login?error=auth but never read or displayed by AuthScreen. Users see no indication when OAuth fails. Add server-side logging and update AuthScreen to read and surface the error parameter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/`(auth)/auth/callback/route.ts around lines 14 - 23, In the callback
route, when the error is returned from exchangeCodeForSession, log the actual
error details using an appropriate logger before redirecting to the login page.
Then in the AuthScreen component, read the error query parameter from the URL
(the error=auth value that gets passed) and display it as a user-facing error
message. Currently the error is silently discarded and the error parameter is
ignored, leaving users with no indication of what went wrong during OAuth
authentication.

@@ -3,32 +3,65 @@
import { useRef, useState } from "react";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cat -n components/profile-edit-screen.tsx

Repository: devHanif-git/naise-coffee-platform

Length of output: 7275


🏁 Script executed:

# Verify that the suggested patch imports and cleanup logic are complete and correct
# by checking if there are any other blob URL creations or special handling

rg "createObjectURL|revokeObjectURL" components/profile-edit-screen.tsx

Repository: devHanif-git/naise-coffee-platform

Length of output: 124


Revoke object URLs to prevent blob-memory leaks

Line 36 creates a new blob URL on each photo pick without revoking the previous one. Add cleanup when replacing previews and on component unmount.

Suggested patch
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
@@
   const [previewUrl, setPreviewUrl] = useState(profile.avatarUrl);
+  const objectUrlRef = useRef<string | null>(null);
@@
   function onPickPhoto(e: React.ChangeEvent<HTMLInputElement>) {
@@
-    setPreviewUrl(URL.createObjectURL(file));
+    if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
+    const nextUrl = URL.createObjectURL(file);
+    objectUrlRef.current = nextUrl;
+    setPreviewUrl(nextUrl);
   }
+
+  useEffect(() => {
+    return () => {
+      if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
+    };
+  }, []);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
// ... other imports
export default function ProfileEditScreen({ profile }: Props) {
const [previewUrl, setPreviewUrl] = useState(profile.avatarUrl);
const objectUrlRef = useRef<string | null>(null);
// ... other state and logic
function onPickPhoto(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.currentTarget.files?.[0];
if (!file) return;
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
const nextUrl = URL.createObjectURL(file);
objectUrlRef.current = nextUrl;
setPreviewUrl(nextUrl);
}
useEffect(() => {
return () => {
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
};
}, []);
// ... rest of component
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/profile-edit-screen.tsx` at line 3, The code creates blob URLs for
photo previews without revoking previous ones, causing memory leaks. You need to
track the current blob URL (using useRef to store it), revoke the previous blob
URL whenever a new preview is created (at line 36 where the new blob URL is
generated), and add a useEffect cleanup function that runs on component unmount
to revoke any remaining blob URL. Import useEffect from React if not already
imported, create a ref to hold the current blob URL, update it when creating new
previews after revoking the old one, and return a cleanup function from
useEffect that calls URL.revokeObjectURL on the tracked blob URL.

Comment thread lib/supabase/avatar.ts
Comment on lines +18 to +24
const ext = extensionFor(file.type);
const path = `${userId}/avatar.${ext}`;

const { error: uploadError } = await supabase.storage
.from("avatars")
.upload(path, file, { upsert: true, contentType: file.type });
if (uploadError) throw uploadError;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, locate and examine the avatar.ts file
find . -name "avatar.ts" -type f

Repository: devHanif-git/naise-coffee-platform

Length of output: 103


🏁 Script executed:

# Check the current implementation of uploadAvatar
cd lib/supabase && cat -n avatar.ts

Repository: devHanif-git/naise-coffee-platform

Length of output: 1901


🏁 Script executed:

# Search for bucket policies and RLS rules related to avatars
rg -A 10 -B 5 "avatars" lib/supabase/ --type ts

Repository: devHanif-git/naise-coffee-platform

Length of output: 2244


🏁 Script executed:

# Search for extensionFor function definition
rg "extensionFor" lib/supabase/ --type ts -A 5

Repository: devHanif-git/naise-coffee-platform

Length of output: 733


🏁 Script executed:

# Check if there are any storage cleanup operations elsewhere
rg "storage.*remove\|deleteObject\|delete.*avatar" lib/supabase/ --type ts

Repository: devHanif-git/naise-coffee-platform

Length of output: 60


Prevent public orphan avatars when MIME type changes

The code uses extension-aware paths (avatar.png, avatar.jpg, avatar.webp) with upsert: true, which prevents multiple versions of the same extension but leaves previous variants behind when a user switches MIME types. A user uploading PNG then JPG leaves avatar.png publicly accessible in the bucket. Delete stale avatar variants before upload.

Suggested patch
 export async function uploadAvatar(
   file: File,
   userId: string,
 ): Promise<string> {
   const supabase = createClient();

   const ext = extensionFor(file.type);
   const path = `${userId}/avatar.${ext}`;
+  const legacyPaths = [
+    `${userId}/avatar.jpg`,
+    `${userId}/avatar.png`,
+    `${userId}/avatar.webp`,
+  ].filter((p) => p !== path);
+
+  const { error: removeError } = await supabase.storage.from("avatars").remove(legacyPaths);
+  if (removeError) throw removeError;

   const { error: uploadError } = await supabase.storage
     .from("avatars")
     .upload(path, file, { upsert: true, contentType: file.type });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/supabase/avatar.ts` around lines 18 - 24, The avatar upload in the
supabase.storage.from("avatars").upload() call uses upsert: true with
extension-aware paths, which leaves orphaned previous avatar variants publicly
accessible when a user changes MIME types. Before uploading the new avatar file
at the computed path, delete any stale avatar files for that userId with
different extensions by querying the avatars bucket for all files matching the
userId prefix (excluding the new extension) and removing them. This ensures only
the current avatar variant remains publicly accessible after each upload.

Comment thread lib/supabase/client.ts
Comment on lines +8 to +9
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail fast on missing Supabase env values.

Line 8 and Line 9 use non-null assertions, which turn config drift into runtime crashes with vague errors. Add explicit guards and throw a clear message early; the same guard pattern should be applied in lib/supabase/server.ts (Line 12-13) and lib/supabase/proxy.ts (Line 13-14).

Suggested patch
 export function createClient() {
+  const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
+  const publishableKey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY;
+  if (!url || !publishableKey) {
+    throw new Error(
+      "Missing NEXT_PUBLIC_SUPABASE_URL or NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY",
+    );
+  }
   return createBrowserClient<Database>(
-    process.env.NEXT_PUBLIC_SUPABASE_URL!,
-    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
+    url,
+    publishableKey,
   );
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
export function createClient() {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const publishableKey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY;
if (!url || !publishableKey) {
throw new Error(
"Missing NEXT_PUBLIC_SUPABASE_URL or NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY",
);
}
return createBrowserClient<Database>(
url,
publishableKey,
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/supabase/client.ts` around lines 8 - 9, Replace the non-null assertions
(the `!` operator) on process.env.NEXT_PUBLIC_SUPABASE_URL and
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY in the Supabase client
initialization with explicit validation guards that check if these environment
variables exist, and throw a descriptive error message immediately if they are
missing. Apply the same validation pattern to the corresponding environment
variable checks in server.ts and proxy.ts to ensure consistent fail-fast
behavior across all Supabase client instances.

Comment thread lib/supabase/proxy.ts
);

// Validates and refreshes the token. Do not remove.
await supabase.auth.getClaims();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

For @supabase/supabase-js v2.108.2, what are the exact failure semantics of auth.getClaims() (throws vs returns { error })?

💡 Result:

In @supabase/supabase-js v2.108.2, the auth.getClaims method is designed to return a result object in the form of { data, error } rather than throwing an exception [1][2]. As of the recent updates in May 2026 (specifically PR #2395, which is included in v2.108.2), the library ensures that all failure modes, including expired tokens, are handled and returned via the { error } field [3][4]. Previously, certain failure scenarios (like expired JWTs) would incorrectly throw a plain Error instead of adhering to this pattern [5][3]. The return structure for getClaims is a Promise that resolves to: - { data: { claims, header, signature }, error: null } on success [2] - { data: null, error: AuthError } on failure [2] You should handle failures by checking the error object, as the method is now intended to be non-throwing [2][3].

Citations:


Handle getClaims() error result in the proxy hot path.

Line 34 awaits getClaims() without checking the returned error object. In @supabase/supabase-js v2.108.2, this method returns { data, error } rather than throwing—failures are silently ignored instead of being handled. Invalid or expired tokens pass through undetected.

Suggested patch
-  // Validates and refreshes the token. Do not remove.
-  await supabase.auth.getClaims();
+  // Validates and refreshes the token. Do not remove.
+  const { error } = await supabase.auth.getClaims();
+  if (error) {
+    // Optionally log or handle transient auth infra failures
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await supabase.auth.getClaims();
// Validates and refreshes the token. Do not remove.
const { error } = await supabase.auth.getClaims();
if (error) {
// Optionally log or handle transient auth infra failures
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/supabase/proxy.ts` at line 34, The `getClaims()` method call on line 34
returns an object with both data and error properties, but the current code does
not check the error result, allowing invalid or expired tokens to pass through
undetected. Modify the line to destructure the result from
`supabase.auth.getClaims()` into data and error variables, then check if error
exists and handle it appropriately (such as throwing an error or returning early
with an error response) to prevent silent failures in the proxy hot path.

Comment thread store/auth.tsx
Comment on lines +196 to +209
const signOut = useCallback(async () => {
// Clear the real Supabase session (no-op if only the phone mock is active).
await supabase.auth.signOut();
setUser(null);
setShowWelcome(false);
}, []);

const dismissWelcome = useCallback(() => {
setShowWelcome(false);
try {
localStorage.removeItem(WELCOME_KEY);
localStorage.removeItem(PHONE_MOCK_KEY);
} catch {
// Non-fatal; the in-memory flag is already cleared.
// Non-fatal.
}
// 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 signing in again carries the full history over.
}, [supabase]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Unhandled error from supabase.auth.signOut() may silently fail.

If the Supabase sign-out call throws (network error, etc.), the local state is cleared anyway, leaving the user believing they're signed out while a valid session may persist server-side. Consider wrapping in try/catch and at minimum logging the error; optionally surface a toast so the user can retry.

🛡️ Proposed defensive handling
 const signOut = useCallback(async () => {
-  // Clear the real Supabase session (no-op if only the phone mock is active).
-  await supabase.auth.signOut();
+  try {
+    await supabase.auth.signOut();
+  } catch (err) {
+    // Log but continue — local state should still clear so the UI is consistent.
+    console.error("Sign-out failed", err);
+  }
   setUser(null);
   setShowWelcome(false);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@store/auth.tsx` around lines 196 - 209, The signOut function calls
supabase.auth.signOut() without error handling, meaning if this call throws (due
to network errors or other issues), the local state is still cleared via
setUser(null) and setShowWelcome(false), leaving the user believing they're
signed out while a valid session may persist server-side. Wrap the
supabase.auth.signOut() call in a try/catch block within the signOut function,
and move the setUser(null) and setShowWelcome(false) calls into the try block so
they only execute after successful sign-out. In the catch block, log the error
and optionally display a toast notification to inform the user that sign-out
failed and allow them to retry. The localStorage clearing can remain in its own
separate try/catch as it is already marked non-fatal.

Comment thread types/auth.ts
Comment on lines +27 to +29
// Profile photo URL from the identity provider (Google avatar). Absent for
// phone sign-in. Rendered directly via <img>, so no next/image config needed.
avatarUrl?: string;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix misleading avatar rendering guidance in the type comment.

Line 28 currently instructs rendering with <img>, which conflicts with the project rule and can spread incorrect usage guidance. Please update the comment to prefer Next.js <Image> and only allow <img> as an exception.

Suggested wording
-  // phone sign-in. Rendered directly via <img>, so no next/image config needed.
+  // phone sign-in. Prefer rendering via Next.js <Image>; use <img> only when
+  // <Image> cannot satisfy the use case.

As per coding guidelines, "Use the Next.js <Image> component for all images; use plain <img> only when <Image> cannot work".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Profile photo URL from the identity provider (Google avatar). Absent for
// phone sign-in. Rendered directly via <img>, so no next/image config needed.
avatarUrl?: string;
// Profile photo URL from the identity provider (Google avatar). Absent for
// phone sign-in. Prefer rendering via Next.js <Image>; use <img> only when
// <Image> cannot satisfy the use case.
avatarUrl?: string;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@types/auth.ts` around lines 27 - 29, Update the comment for the avatarUrl
field in the auth.ts types file to align with project guidelines. The current
comment on line 28 misleadingly suggests rendering with plain <img> tags.
Replace this guidance with language that prefers the Next.js <Image> component
and only permits plain <img> as an exception when <Image> cannot be used,
consistent with the project's stated rule: "Use the Next.js <Image> component
for all images; use plain <img> only when <Image> cannot work".

Source: Coding guidelines

@devHanif-git
devHanif-git merged commit df8235b into master Jun 16, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant