Repository navigation
Dev - #10
Dev#10
Conversation
… 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.
📝 WalkthroughWalkthroughIntegrates 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. ChangesSupabase Auth System and Owner ID Attribution
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
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 }
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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
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. Comment |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ❌ Deployment failed View logs |
naise-coffee-platform | 2188e67 | Jun 16 2026, 07:18 PM |
There was a problem hiding this comment.
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 winSync owner-id from persisted user before minting a new one.
On Line 113,
getOrCreateOwnerId()always runs even when a persisted session exists. IfAUTH_KEYis present butOWNER_ID_STORAGE_KEYwas 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 winConsider 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:
- Auto-focusing the Cancel button (or dialog) on open
- Trapping focus within the dialog while open
- Returning focus to the trigger button on close
This can be achieved with a library like
@radix-ui/react-dialogor 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
⛔ Files ignored due to path filters (1)
supabase/.temp/cli-latestis excluded by!**/.temp/**
📒 Files selected for processing (18)
.dev.vars.example.gitignore.hermes/plans/2026-06-15_auth-google-oauth.mdapp/(customer)/checkout/actions.tsapp/(customer)/profile/orders/page.tsxapp/(customer)/profile/page.tsxcomponents/checkout-screen.tsxcomponents/profile-screen.tsxcomponents/signout-confirm-modal.tsxdata/mock-order.tsdata/rewards.tslib/auth/owner-id-server.tslib/auth/owner-id-shared.tslib/auth/owner-id.tslib/orders/store.tsstore/auth.tsxtypes/order.tswrangler.jsonc
| 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." }; | ||
| } |
There was a problem hiding this comment.
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.
| <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> |
There was a problem hiding this comment.
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
| 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`; | ||
| } |
There was a problem hiding this comment.
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.
| 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.
…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.
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (25)
.dev.vars.example.env.example.gitignore.hermes/plans/2026-06-15_auth-google-oauth.mdapp/(auth)/auth/callback/route.tsapp/(customer)/profile/settings/page.tsxcomponents/auth-screen.tsxcomponents/profile-edit-screen.tsxcomponents/profile-screen.tsxdata/profile.tslib/auth/session.tslib/supabase/avatar.tslib/supabase/client.tslib/supabase/proxy.tslib/supabase/server.tspackage.jsonproxy.tsstore/auth.tsxstore/profile.tsxsupabase/migrations/20260616222010_auth_profiles.sqlsupabase/migrations/20260616223000_avatars_storage.sqlsupabase/migrations/20260616224500_profiles_welcomed_at.sqlsupabase/migrations/20260616225500_profiles_guard_role.sqltypes/auth.tstypes/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
| 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`); | ||
| } |
There was a problem hiding this comment.
🧩 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"; | |||
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n components/profile-edit-screen.tsxRepository: 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.tsxRepository: 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.
| 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.
| 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; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and examine the avatar.ts file
find . -name "avatar.ts" -type fRepository: devHanif-git/naise-coffee-platform
Length of output: 103
🏁 Script executed:
# Check the current implementation of uploadAvatar
cd lib/supabase && cat -n avatar.tsRepository: 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 tsRepository: devHanif-git/naise-coffee-platform
Length of output: 2244
🏁 Script executed:
# Search for extensionFor function definition
rg "extensionFor" lib/supabase/ --type ts -A 5Repository: 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 tsRepository: 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.
| process.env.NEXT_PUBLIC_SUPABASE_URL!, | ||
| process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, |
There was a problem hiding this comment.
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.
| 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.
| ); | ||
|
|
||
| // Validates and refreshes the token. Do not remove. | ||
| await supabase.auth.getClaims(); |
There was a problem hiding this comment.
🧩 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:
- 1: https://supabase.com/docs/reference/javascript/auth-getclaims
- 2: https://supabase.github.io/auth-js/v2/classes/GoTrueClient.html
- 3: fix(auth): return AuthInvalidJwtError from getClaims for expired JWT supabase/supabase-js#2395
- 4: supabase/supabase-js@d942277
- 5: getClaims is raising a generic Error for expired token supabase/supabase-js#2394
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.
| 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.
| 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]); |
There was a problem hiding this comment.
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.
| // 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; |
There was a problem hiding this comment.
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.
| // 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
Summary by CodeRabbit
Release Notes