-
Notifications
You must be signed in to change notification settings - Fork 0
feat(account): super-admin read-only "view as" (customer impersonation) #262
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+1,417
−45
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
fd0969e
feat(admin): owner allowlist + isAdmin (config-in-code)
kilbot dfba0ef
feat(admin): findAdminCustomerByEmail + getAdminCustomerById
kilbot 3e6d6cf
refactor(auth): extract getSessionCustomer; getCustomer delegates
kilbot 2cf11cb
feat(account): stamp x-wcpos-account-request header for impersonation…
kilbot ff55272
feat(impersonation): getImpersonation resolver + assertViewOnly guard
kilbot 2f87aaf
feat(impersonation): getCustomer + order fetchers resolve the target
kilbot 9154955
feat(impersonation): block mutating account routes during inspection
kilbot fce463f
feat(impersonation): owner-only /account/admin entry + start action
kilbot c43d207
feat(impersonation): read-only banner + exit route
kilbot daebe42
fix(test): ViewOnlyError takes no constructor args
kilbot 0d6f7fd
test(impersonation): end-to-end lib-layer resolve + orders
kilbot 213d71e
fix(impersonation): strip spoofable scope header, session-safe OAuth …
kilbot 7e7472c
fix: address impersonation review feedback
a4a2f7d
fix: address impersonation audit review feedback
1c33300
fix(admin): set owner allowlist to paul@kilbot.com.au
kilbot ccf116e
fix(admin): Medusa v2 admin API keys require HTTP Basic auth, not Bearer
kilbot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import { describe, expect, it, vi, beforeEach } from 'vitest' | ||
|
|
||
| const { | ||
| getSessionCustomer, | ||
| findAdminCustomerByEmail, | ||
| startImpersonation, | ||
| redirect, | ||
| consume, | ||
| } = | ||
| vi.hoisted(() => ({ | ||
| getSessionCustomer: vi.fn(), | ||
| findAdminCustomerByEmail: vi.fn(), | ||
| startImpersonation: vi.fn(), | ||
| redirect: vi.fn(() => { | ||
| throw new Error('REDIRECT') | ||
| }), | ||
| consume: vi.fn(async () => ({ success: true, remaining: 9 })), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/medusa-auth', () => ({ getSessionCustomer })) | ||
| vi.mock('@/lib/admin', () => ({ | ||
| isAdmin: (e?: string | null) => e?.trim().toLowerCase() === 'paul@kilbot.com', | ||
| })) | ||
| vi.mock('@/lib/discord/medusa-admin', () => ({ findAdminCustomerByEmail })) | ||
| vi.mock('@/lib/impersonation', () => ({ startImpersonation })) | ||
| vi.mock('@/lib/rate-limit', () => ({ | ||
| createRateLimiter: () => ({ consume }), | ||
| clientIp: () => 'ip', | ||
| })) | ||
| vi.mock('@/lib/logger', () => ({ authLogger: { info: vi.fn(), warn: vi.fn() } })) | ||
| vi.mock('@/i18n/navigation', () => ({ redirect })) | ||
| vi.mock('next/headers', () => ({ headers: async () => ({ get: () => 'ip' }) })) | ||
|
|
||
| import { startImpersonationAction } from './actions' | ||
|
|
||
| beforeEach(() => { | ||
| getSessionCustomer.mockReset() | ||
| findAdminCustomerByEmail.mockReset() | ||
| startImpersonation.mockReset() | ||
| consume.mockReset() | ||
| consume.mockResolvedValue({ success: true, remaining: 9 }) | ||
| }) | ||
|
|
||
| describe('startImpersonationAction', () => { | ||
| it('rejects a non-admin session', async () => { | ||
| getSessionCustomer.mockResolvedValue({ email: 'nope@x.com' }) | ||
| const result = await startImpersonationAction({ email: 't@x.com', locale: 'en' }) | ||
| expect(result).toEqual({ error: 'forbidden' }) | ||
| expect(startImpersonation).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('rate limits trusted admin identity before looking up the target', async () => { | ||
| getSessionCustomer.mockResolvedValue({ email: 'Paul@Kilbot.com ' }) | ||
| consume.mockResolvedValueOnce({ success: false, remaining: 0 }) | ||
|
|
||
| const result = await startImpersonationAction({ email: 't@x.com', locale: 'en' }) | ||
|
|
||
| expect(result).toEqual({ error: 'rate_limited' }) | ||
| expect(consume).toHaveBeenCalledWith('paul@kilbot.com') | ||
| expect(findAdminCustomerByEmail).not.toHaveBeenCalled() | ||
| expect(startImpersonation).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('reports when the target email is not found', async () => { | ||
| getSessionCustomer.mockResolvedValue({ email: 'paul@kilbot.com' }) | ||
| findAdminCustomerByEmail.mockResolvedValue(null) | ||
| const result = await startImpersonationAction({ email: 'ghost@x.com', locale: 'en' }) | ||
| expect(result).toEqual({ error: 'not_found' }) | ||
| expect(startImpersonation).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('starts impersonation + redirects when admin targets a real customer', async () => { | ||
| getSessionCustomer.mockResolvedValue({ email: 'paul@kilbot.com' }) | ||
| findAdminCustomerByEmail.mockResolvedValue({ id: 'cus_t', email: 't@x.com' }) | ||
| await expect( | ||
| startImpersonationAction({ email: 't@x.com', locale: 'fr' }) | ||
| ).rejects.toThrow('REDIRECT') | ||
| expect(startImpersonation).toHaveBeenCalledWith('cus_t') | ||
| expect(redirect).toHaveBeenCalledWith({ href: '/account', locale: 'fr' }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| 'use server' | ||
|
|
||
| import { createHash } from 'node:crypto' | ||
| import { redirect } from '@/i18n/navigation' | ||
| import { getSessionCustomer } from '@/lib/medusa-auth' | ||
| import { isAdmin } from '@/lib/admin' | ||
| import { findAdminCustomerByEmail } from '@/lib/discord/medusa-admin' | ||
| import { startImpersonation } from '@/lib/impersonation' | ||
| import { createRateLimiter } from '@/lib/rate-limit' | ||
| import { authLogger } from '@/lib/logger' | ||
|
|
||
| const limiter = createRateLimiter({ | ||
| prefix: 'impersonate-lookup', | ||
| limit: 10, | ||
| window: '10 m', | ||
| }) | ||
|
|
||
| function redirectToAccount(locale: string): never { | ||
| redirect({ href: '/account', locale }) | ||
| throw new Error('Redirect failed') | ||
| } | ||
|
|
||
| function auditHash(value: string): string { | ||
| return createHash('sha256').update(value).digest('hex').slice(0, 12) | ||
| } | ||
|
|
||
| export type StartImpersonationResult = | ||
| | { error: 'forbidden' } | ||
| | { error: 'not_found' } | ||
| | { error: 'rate_limited' } | ||
|
|
||
| /** | ||
| * Owner-only. Verifies the REAL session is an admin, rate-limits by IP (email | ||
| * enumeration guard), looks up the target by email, then starts impersonation | ||
| * and redirects to /account. Returns an error shape on failure (redirect throws | ||
| * on success, so the happy path never returns). | ||
| */ | ||
| export async function startImpersonationAction(input: { | ||
| email: string | ||
| locale: string | ||
| }): Promise<StartImpersonationResult> { | ||
| const session = await getSessionCustomer() | ||
| if (!session?.email || !isAdmin(session.email)) { | ||
| authLogger.warn`Non-admin impersonation attempt by ${session?.email ?? 'anon'}` | ||
| return { error: 'forbidden' } | ||
| } | ||
| const adminEmail = session.email | ||
|
|
||
| const rateLimitKey = adminEmail.trim().toLowerCase() | ||
| const { success } = await limiter.consume(rateLimitKey) | ||
| if (!success) return { error: 'rate_limited' } | ||
|
|
||
| const email = input.email.trim().toLowerCase() | ||
| const target = await findAdminCustomerByEmail(email) | ||
| if (!target) { | ||
| authLogger.info`Impersonation lookup miss: admin=${adminEmail} target_hash=${auditHash(email)}` | ||
| return { error: 'not_found' } | ||
| } | ||
|
|
||
| authLogger.info`Impersonation START: admin=${adminEmail} target_id=${target.id}` | ||
| await startImpersonation(target.id) | ||
| redirectToAccount(input.locale) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { notFound } from 'next/navigation' | ||
| import { getSessionCustomer } from '@/lib/medusa-auth' | ||
| import { isAdmin } from '@/lib/admin' | ||
| import { startImpersonationAction } from './actions' | ||
|
|
||
| export const metadata = { robots: { index: false, follow: false } } | ||
|
|
||
| export default async function AdminInspectPage({ | ||
| params, | ||
| }: { | ||
| params: Promise<{ locale: string }> | ||
| }) { | ||
| const { locale } = await params | ||
| // Gate on the REAL session — never getCustomer (which could be a target). | ||
| const session = await getSessionCustomer() | ||
| if (!isAdmin(session?.email)) notFound() | ||
|
|
||
| async function submit(formData: FormData) { | ||
| 'use server' | ||
| const email = String(formData.get('email') ?? '') | ||
| await startImpersonationAction({ email, locale }) | ||
| // On success the action redirects; a returned error re-renders this page. | ||
| // (For inline error messaging, upgrade to useActionState in a follow-up.) | ||
| } | ||
|
|
||
| return ( | ||
| <div className="mx-auto max-w-md space-y-4"> | ||
| <h1 className="text-xl font-semibold">Inspect a customer (read-only)</h1> | ||
| <p className="text-sm text-muted-foreground"> | ||
| Enter a customer email to view their account exactly as they see it. You | ||
| cannot change their data while inspecting. | ||
| </p> | ||
| <form action={submit} className="flex gap-2"> | ||
| <input | ||
| name="email" | ||
| type="email" | ||
| required | ||
| placeholder="customer@example.com" | ||
| className="flex-1 rounded-md border px-3 py-2" | ||
| /> | ||
| <button | ||
| type="submit" | ||
| className="rounded-md bg-primary px-4 py-2 text-primary-foreground" | ||
| > | ||
| View as | ||
| </button> | ||
| </form> | ||
| </div> | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { NextResponse } from 'next/server' | ||
| import { stopImpersonation } from '@/lib/impersonation' | ||
| import { getSessionCustomer } from '@/lib/medusa-auth' | ||
| import { authLogger } from '@/lib/logger' | ||
| import { defaultLocale, locales } from '@/i18n/config' | ||
| import { getPathname } from '@/i18n/navigation' | ||
|
|
||
| function accountUrl(request: Request): URL { | ||
| const requestUrl = new URL(request.url) | ||
| const explicitLocale = requestUrl.searchParams.get('locale') | ||
| const referer = request.headers.get('referer') | ||
| let refererPathname = '' | ||
| try { | ||
| refererPathname = referer ? new URL(referer).pathname : '' | ||
| } catch { | ||
| refererPathname = '' | ||
| } | ||
| const refererLocale = refererPathname.split('/')[1] | ||
| const locale = locales.find( | ||
| (candidate) => candidate === explicitLocale || candidate === refererLocale | ||
| ) | ||
| return new URL(getPathname({ href: '/account', locale: locale ?? defaultLocale }), request.url) | ||
| } | ||
|
|
||
| async function exit(request: Request) { | ||
| const session = await getSessionCustomer() | ||
| await stopImpersonation() | ||
| authLogger.info`Impersonation STOP: admin_id=${session?.id ?? 'unknown'}` | ||
| return NextResponse.redirect(accountUrl(request), { status: 303 }) | ||
| } | ||
|
|
||
| export async function POST(request: Request) { | ||
| return exit(request) | ||
| } | ||
|
|
||
| // GET variant so a server-component render (which cannot delete cookies) can | ||
| // bounce a stale/deleted impersonation target here to clear the cookie and | ||
| // land the owner back on their own account. See AccountGate in | ||
| // src/app/[locale]/account/layout.tsx. | ||
| export async function GET(request: Request) { | ||
| return exit(request) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.