Repository navigation
feat(mosaic): wire up user profile passkeys #9983
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鈥檒l occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
ce44514
test(mosaic): model passkey contracts in fake FAPI
austincalvelage 96f7b35
feat(mosaic): wire passkey management to the current account
austincalvelage 1be46f1
test(mosaic): cover passkey lifecycle with connected features
austincalvelage 19fd269
chore(mosaic): keep one empty passkeys changeset
austincalvelage 96283a7
fix(mosaic): correct passkey lifecycle and validation
austincalvelage 7fbfb4b
test(mosaic): repair CI fixtures and cover removal focus cleanup
austincalvelage 16a4cb1
fix(mosaic): preserve removal targets during focus restoration
austincalvelage 98617d4
revert(mosaic): drop shared focus and environment changes
austincalvelage 270662d
fix(mosaic): preserve localized passkey feedback
austincalvelage 7af3c08
test(mosaic): record duplicate passkey message gap
austincalvelage 84954e3
refactor(mosaic): simplify passkeys composition and controller props
austincalvelage 8845990
fix(mosaic): preserve structured passkey action errors
austincalvelage 73064da
chore: keep one empty changeset
austincalvelage 190e5d0
refactor(mosaic): use pending action for passkey creation
austincalvelage f1fd73e
chore(mosaic): track passkey useNow follow-up
austincalvelage af42c2b
test(mosaic): align authentication composition with latest main
austincalvelage 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,2 @@ | ||
| --- | ||
| --- |
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
159 changes: 159 additions & 0 deletions
159
packages/mosaic/src/__tests__/feature/fake-fapi/passkeys.ts
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,159 @@ | ||
| import type { PasskeyJSON } from '@clerk/shared/types'; | ||
| import { http, HttpResponse } from 'msw'; | ||
|
|
||
| import type { FakeFapiState } from '../fake-fapi'; | ||
| import { fapiPasskey } from '../fapi'; | ||
| import { envelope, error, missing, requestUser, updateUser } from './shared'; | ||
|
|
||
| export interface FakePasskeysSeed { | ||
| name?: string; | ||
| authenticatorName?: string; | ||
| } | ||
|
|
||
| export function passkeyHandlers( | ||
| state: Pick<FakeFapiState, 'client' | 'environment'>, | ||
| fapiUrl: (path: string) => string, | ||
| seed: FakePasskeysSeed = {}, | ||
| ) { | ||
| const pendingPasskeys = new Map<string, { userId: string; passkey: PasskeyJSON; expiresAt: number }>(); | ||
| let nextPasskeyId = 1; | ||
|
|
||
| return [ | ||
| http.post(fapiUrl('/v1/me/passkeys'), ({ request }) => { | ||
| const user = requestUser(state, request); | ||
| if (!user) { | ||
| return missing(); | ||
| } | ||
| if (!state.environment.user_settings.attributes.passkey.enabled) { | ||
| return error('feature_not_enabled', 403); | ||
| } | ||
| if ( | ||
| state.environment.user_settings.enterprise_sso.enabled && | ||
| user.enterprise_accounts.some( | ||
| account => | ||
| account.enterprise_connection?.active && account.enterprise_connection.disable_additional_identifications, | ||
| ) | ||
| ) { | ||
| return error('enterprise_sso_additional_identifications_disabled', 422); | ||
| } | ||
| if (user.passkeys.length >= 10) { | ||
| return error('passkey_quota_exceeded', 403); | ||
| } | ||
| const now = Date.now(); | ||
| for (const [id, pending] of pendingPasskeys) { | ||
| if (pending.userId === user.id && pending.expiresAt <= now) { | ||
| pendingPasskeys.delete(id); | ||
| } | ||
| } | ||
| const expiresAt = now + 10 * 60_000; | ||
| const passkey = fapiPasskey({ | ||
| id: `passkey_${nextPasskeyId++}`, | ||
| name: seed.name ?? 'Chrome on macOS', | ||
| verification: { | ||
| id: 'verification_passkey', | ||
| object: 'verification', | ||
| status: 'unverified', | ||
| verified_at_client: '', | ||
| strategy: 'passkey', | ||
| attempts: 0, | ||
| expire_at: expiresAt, | ||
| error: { code: '', message: '' }, | ||
| nonce: JSON.stringify({ | ||
| challenge: 'Y2hhbGxlbmdl', | ||
| rp: { name: 'Acme', id: 'localhost' }, | ||
| user: { id: 'dXNlcg', name: 'user@example.com', displayName: 'Test user' }, | ||
| pubKeyCredParams: [{ type: 'public-key', alg: -7 }], | ||
| }), | ||
| }, | ||
| }); | ||
| pendingPasskeys.set(passkey.id, { userId: user.id, passkey, expiresAt }); | ||
| return envelope(passkey, state.client); | ||
| }), | ||
| http.post(fapiUrl('/v1/me/passkeys/:id/attempt_verification'), async ({ params, request }) => { | ||
| const pending = typeof params.id === 'string' ? pendingPasskeys.get(params.id) : undefined; | ||
| const user = requestUser(state, request); | ||
| if (!user || !pending) { | ||
| return missing(); | ||
| } | ||
| if (pending.userId !== user.id) { | ||
| return error('resource_forbidden', 403); | ||
| } | ||
| const { passkey } = pending; | ||
| const verification = passkey.verification; | ||
| if (!verification || pending.expiresAt <= Date.now()) { | ||
| return error('verification_expired', 400); | ||
| } | ||
| const body = new URLSearchParams(await request.text()); | ||
| if (body.get('strategy') !== 'passkey' || !body.get('public_key_credential')) { | ||
| return HttpResponse.json( | ||
| { errors: [{ code: 'form_param_missing', message: 'Passkey credential required.' }] }, | ||
| { status: 400 }, | ||
| ); | ||
| } | ||
| const verified = { | ||
| ...passkey, | ||
| name: seed.authenticatorName || passkey.name, | ||
| last_used_at: Date.now(), | ||
| verification: { | ||
| ...verification, | ||
| status: 'verified' as const, | ||
| attempts: verification.attempts + 1, | ||
| verified_at_client: state.client.id, | ||
| nonce: undefined, | ||
| error: undefined, | ||
| }, | ||
| }; | ||
| pendingPasskeys.delete(passkey.id); | ||
| updateUser(state, { ...user, passkeys: [...user.passkeys, verified] }); | ||
| return envelope(verified, state.client); | ||
| }), | ||
| http.post(fapiUrl('/v1/me/passkeys/:id'), async ({ params, request }) => { | ||
| const user = requestUser(state, request); | ||
| if (!user || typeof params.id !== 'string') { | ||
| return missing(); | ||
| } | ||
| const pending = pendingPasskeys.get(params.id); | ||
| const passkey = | ||
| user.passkeys.find(candidate => candidate.id === params.id) ?? | ||
| (pending?.userId === user.id ? pending.passkey : undefined); | ||
| if (!passkey) { | ||
| return missing(); | ||
| } | ||
| const method = new URL(request.url).searchParams.get('_method'); | ||
| if (method === 'DELETE') { | ||
| pendingPasskeys.delete(passkey.id); | ||
| updateUser(state, { ...user, passkeys: user.passkeys.filter(candidate => candidate.id !== passkey.id) }); | ||
| return envelope({ object: 'passkey', id: passkey.id, deleted: true }, state.client); | ||
| } | ||
| if (method === 'PATCH') { | ||
| const body = new URLSearchParams(await request.text()); | ||
| const name = body.get('name'); | ||
| if (name !== null && new TextEncoder().encode(name).length > 256) { | ||
| return HttpResponse.json( | ||
| { | ||
| errors: [ | ||
| { | ||
| code: 'form_param_max_length_exceeded', | ||
| message: 'Passkey name is too long.', | ||
| meta: { param_name: 'name' }, | ||
| }, | ||
| ], | ||
| }, | ||
| { status: 422 }, | ||
| ); | ||
| } | ||
| const renamed = { ...passkey, name: name ?? passkey.name }; | ||
| if (pending?.userId === user.id) { | ||
| pendingPasskeys.set(passkey.id, { ...pending, passkey: renamed }); | ||
| return envelope(renamed, state.client); | ||
| } | ||
| updateUser(state, { | ||
| ...user, | ||
| passkeys: user.passkeys.map(candidate => (candidate.id === passkey.id ? renamed : candidate)), | ||
| }); | ||
| return envelope(renamed, state.client); | ||
| } | ||
| return missing(); | ||
| }), | ||
| ]; | ||
| } | ||
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,32 @@ | ||
| import type { ClientJSON, SessionJSON, UserJSON } from '@clerk/shared/types'; | ||
| import { HttpResponse, type JsonBodyType } from 'msw'; | ||
|
|
||
| type ClientState = { client: ClientJSON }; | ||
|
|
||
| export function envelope(response: JsonBodyType, client: ClientJSON | null) { | ||
| return HttpResponse.json({ response, client }); | ||
| } | ||
|
|
||
| export function findSession(state: ClientState, id: unknown): SessionJSON | undefined { | ||
| return state.client.sessions.find(session => session.id === id); | ||
| } | ||
|
|
||
| export function error(code: string, status = 400) { | ||
| return HttpResponse.json({ errors: [{ code, message: code, long_message: code }] }, { status }); | ||
| } | ||
|
|
||
| export function requestUser(state: ClientState, request: Request): UserJSON | undefined { | ||
| const sessionId = new URL(request.url).searchParams.get('_clerk_session_id') ?? state.client.last_active_session_id; | ||
| return findSession(state, sessionId)?.user; | ||
| } | ||
|
|
||
| export function updateUser(state: ClientState, user: UserJSON): void { | ||
| state.client = { | ||
| ...state.client, | ||
| sessions: state.client.sessions.map(session => (session.user.id === user.id ? { ...session, user } : session)), | ||
| }; | ||
| } | ||
|
|
||
| export function missing() { | ||
| return HttpResponse.json({ errors: [{ code: 'resource_not_found', message: 'not found' }] }, { status: 404 }); | ||
| } |
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
89 changes: 89 additions & 0 deletions
89
packages/mosaic/src/features/user-profile/__tests__/passkeys-contract.feature.test.tsx
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,89 @@ | ||
| import { act, screen, waitFor } from '@testing-library/react'; | ||
| import userEvent from '@testing-library/user-event'; | ||
| import { afterEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { holdRequests, serveFapi } from '../../../__tests__/feature/fake-fapi'; | ||
| import { fapiClient, fapiEnvironment, fapiSession, fapiUser } from '../../../__tests__/feature/fapi'; | ||
| import { renderWithClerk } from '../../../__tests__/feature/render'; | ||
| import { UserProfilePasskeysSection } from '../user-profile-passkeys-section/user-profile-passkeys-section'; | ||
|
|
||
| function serveRegistration(passkeys = { name: 'Chrome on macOS', authenticatorName: '' }) { | ||
| const environment = fapiEnvironment(); | ||
| environment.user_settings.attributes.passkey.enabled = true; | ||
| vi.spyOn(navigator, 'webdriver', 'get').mockReturnValue(false); | ||
| vi.spyOn(navigator.credentials, 'create').mockResolvedValue({ | ||
| id: 'credential_1', | ||
| type: 'public-key', | ||
| rawId: new Uint8Array([1, 2, 3]).buffer, | ||
| authenticatorAttachment: 'platform', | ||
| response: { | ||
| clientDataJSON: new TextEncoder().encode('{}').buffer, | ||
| attestationObject: new Uint8Array([4, 5, 6]).buffer, | ||
| getTransports: () => ['internal'], | ||
| }, | ||
| }); | ||
| const seed = { | ||
| environment, | ||
| passkeys, | ||
| client: fapiClient([ | ||
| fapiSession({ id: 'sess_a', user: fapiUser({ id: 'user_a' }) }), | ||
| fapiSession({ id: 'sess_b', user: fapiUser({ id: 'user_b' }) }), | ||
| ]), | ||
| }; | ||
| return serveFapi(seed); | ||
| } | ||
|
|
||
| afterEach(() => vi.restoreAllMocks()); | ||
|
|
||
| describe('Registering passkeys against the backend contract', () => { | ||
| it('rejects another user verifying a pending registration without changing either account', async () => { | ||
| const fapi = serveRegistration(); | ||
| const { clerk } = await renderWithClerk(<UserProfilePasskeysSection />); | ||
| const alice = clerk.user; | ||
| if (!alice) { | ||
| throw new Error('Missing Alice'); | ||
| } | ||
| const creation = holdRequests('post', '/v1/me/passkeys'); | ||
| const outcome = alice.createPasskey().then( | ||
| result => result, | ||
| (error: unknown) => error, | ||
| ); | ||
| await waitFor(() => expect(creation.requests).toHaveLength(1)); | ||
| await act(() => clerk.setActive({ session: 'sess_b' })); | ||
| creation.release(); | ||
| expect(await outcome).toMatchObject({ status: 403, errors: [{ code: 'resource_forbidden' }] }); | ||
| expect(fapi.client.sessions.map(session => session.user.passkeys)).toEqual([[], []]); | ||
| expect(screen.queryByText('Chrome on macOS')).toBeNull(); | ||
| }); | ||
|
|
||
| it.each([ | ||
| { minutes: 2, expired: false }, | ||
| { minutes: 10, expired: true }, | ||
| ])('handles verification after $minutes minutes', async ({ minutes, expired }) => { | ||
| const fapi = serveRegistration(); | ||
| await renderWithClerk(<UserProfilePasskeysSection />); | ||
| const verification = holdRequests('post', '/v1/me/passkeys/passkey_1/attempt_verification'); | ||
| await userEvent.setup().click(screen.getByRole('button', { name: 'Add passkey' })); | ||
| await waitFor(() => expect(verification.requests).toHaveLength(1)); | ||
| vi.spyOn(Date, 'now').mockReturnValue(Date.now() + minutes * 60_000); | ||
| verification.release(); | ||
| if (expired) { | ||
| expect(await screen.findByRole('alert')).toBeVisible(); | ||
| expect(fapi.client.sessions[0]?.user.passkeys).toEqual([]); | ||
| } else { | ||
| expect(await screen.findByText('Chrome on macOS')).toBeVisible(); | ||
| expect(screen.queryByRole('alert')).toBeNull(); | ||
| } | ||
| }); | ||
|
|
||
| it.each([ | ||
| { name: 'Firefox on Windows', authenticatorName: '', expected: 'Firefox on Windows' }, | ||
| { name: 'Chrome on macOS', authenticatorName: 'iCloud Keychain', expected: 'iCloud Keychain' }, | ||
| ])('shows $expected after registration', async ({ name, authenticatorName, expected }) => { | ||
| const fapi = serveRegistration({ name, authenticatorName }); | ||
| await renderWithClerk(<UserProfilePasskeysSection />); | ||
| await userEvent.setup().click(screen.getByRole('button', { name: 'Add passkey' })); | ||
| expect(await screen.findByText(expected)).toBeVisible(); | ||
| expect(fapi.client.sessions[0]?.user.passkeys[0]?.name).toBe(expected); | ||
| }); | ||
| }); |
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.