diff --git a/.changeset/verify-magic-link-confirm.md b/.changeset/verify-magic-link-confirm.md new file mode 100644 index 0000000..7593f3b --- /dev/null +++ b/.changeset/verify-magic-link-confirm.md @@ -0,0 +1,5 @@ +--- +"seamless-cli": patch +--- + +`seamless verify` holds the API and adapters to the magic link contract from seamless-auth-api v0.24. Opening a link answers `409 confirmation_required` with `sameDevice`, and only `POST /magic-link/verify/:token/confirm` with the `code` from the link's fragment signs in. New specs check that a confirm with no code or a wrong code is refused, that a wrong code spends the link, and that the adapter forwards the confirm body. The browser specs open the full delivered link and expect a 409 verify followed by a successful confirm. The Angular, Vue and Svelte reference apps are pinned to `@seamless-auth/angular` 0.6.0, `@seamless-auth/vue` 0.5.0 and `@seamless-auth/svelte` 0.5.0, which read the code and confirm on their own. diff --git a/verify/CONFORMANCE.md b/verify/CONFORMANCE.md index 3a66502..ba4cfd9 100644 --- a/verify/CONFORMANCE.md +++ b/verify/CONFORMANCE.md @@ -61,7 +61,7 @@ everyone. | `GET /api/permissions/all` | Pending `permission-guards`. All of `conformance:read`, `conformance:write` | | `GET /api/permissions/org` | Pending `permission-guards`. Organization scope, `conformance:org` | | `GET /api/permissions/org/:organizationId` | Pending `permission-guards`. Organization scope bound to the route, `conformance:org` | -| `GET /__captured/:recipient` | The most recent message the adapter delivered to `recipient` (an email address or phone number): `{ "token": "", "magicLinkUrl"?: "..." }`, or `null` | +| `GET /__captured/:recipient` | The most recent message the adapter delivered to `recipient` (an email address or phone number): `{ "token": "", "magicLinkUrl"?: "..." }`, or `null`. For a magic link, `magicLinkUrl` is the whole delivered link, fragment included | `/__captured` is a test hook, never part of a real deployment. The adapter must ask the API for external delivery (`x-seamless-auth-delivery-mode: external`) and hand each @@ -76,8 +76,23 @@ proxy" setting must not be used: it makes the client address caller-controlled. ## What the specs hold an adapter to -**Flows** (cookie transport): email OTP signup and sign-in, magic link (`204` while -pending, `200` once verified), OAuth against the mock provider, logout (`204`). +**Flows** (cookie transport): email OTP signup and sign-in, magic link (below), OAuth +against the mock provider, logout (`204`). + +**Magic link.** The delivered link is `?token=T#code=C`. The token is a lookup +handle in the query string, and the code is the proof, carried in the fragment so it +never reaches a server, a `Referer` or an access log. +- `GET /auth/magic-link/check` answers `204` until the link is confirmed, then `200` + with the session. +- `GET /auth/magic-link/verify/:token` never signs in, even on the device that asked. + It answers `409 { "error": "confirmation_required", "message", "sameDevice", + "requestedFrom" }`, forwarded verbatim. `sameDevice` is `true` for the browser that + requested the link, which then confirms without asking. +- `POST /auth/magic-link/verify/:token/confirm` with `{ "code": "C" }` consumes the link. + The adapter forwards the JSON body. A confirm without a code answers `400`, and a wrong + code answers `400` and spends the link, so the right code is refused after it. +- With `magic_link_redirect_uris` empty, a requested `redirectUri` must be exactly + `/verify-magiclink`. The harness's cookie-transport requests carry `x-seamless-auth-transport: cookie`, as the official client's unsafe requests do, so a body-less `POST` or `DELETE` passes the diff --git a/verify/angular-app/Dockerfile b/verify/angular-app/Dockerfile index e62d50a..6870597 100644 --- a/verify/angular-app/Dockerfile +++ b/verify/angular-app/Dockerfile @@ -1,12 +1,14 @@ # The verify harness builds this image with an `sdk` build context: verify/angular-vendor, # which holds local @seamless-auth/client and @seamless-auth/angular tarballs on a --local # run and nothing otherwise. Without them, the published @seamless-auth/angular is used. +# The version is pinned rather than `latest`: the CI build cache keys this layer on the +# command and its build args, so `latest` would keep serving the release it first resolved. FROM node:24-slim AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci COPY --from=sdk . /tmp/sdk/ -ARG SEAMLESS_ANGULAR_VERSION=latest +ARG SEAMLESS_ANGULAR_VERSION=0.6.0 RUN if ls /tmp/sdk/*.tgz >/dev/null 2>&1; then \ npm install --no-save /tmp/sdk/*.tgz; \ else \ diff --git a/verify/harness/adapter/magicLink.spec.ts b/verify/harness/adapter/magicLink.spec.ts index 611feee..e67d03d 100644 --- a/verify/harness/adapter/magicLink.spec.ts +++ b/verify/harness/adapter/magicLink.spec.ts @@ -1,8 +1,12 @@ import { expect, test } from '../lib/fixtures'; -import { loginViaMagicLink, registerAndVerifyEmail } from '../lib/adapterFlows'; +import { + loginViaMagicLink, + registerAndVerifyEmail, + requestMagicLinkViaAdapter, +} from '../lib/adapterFlows'; test.describe('magic link login (adapter, cookies)', () => { - test('register -> verify -> magic-link request/verify/poll -> session -> /users/me', async ({ + test('register -> verify -> magic-link request/verify/confirm/poll -> session -> /users/me', async ({ adapterActor, }) => { await registerAndVerifyEmail(adapterActor.ctx, adapterActor.email); @@ -11,4 +15,20 @@ test.describe('magic link login (adapter, cookies)', () => { const me = await adapterActor.ctx.get('/auth/users/me'); expect(me.status(), 'authenticated via magic-link session cookie').toBe(200); }); + + // The token alone, which is all a leaked query string carries, must not sign in + // through the adapter either: the API refuses the confirm and the adapter passes the + // refusal on. The flow above shows the adapter forwards the body when it has a code. + test('a confirm through the adapter without the code is refused', async ({ adapterActor }) => { + const { ctx, email } = adapterActor; + await registerAndVerifyEmail(ctx, email); + expect((await ctx.post('/auth/login', { data: { identifier: email } })).ok()).toBeTruthy(); + + const { token } = await requestMagicLinkViaAdapter(ctx, email); + expect((await ctx.get(`/auth/magic-link/verify/${token}`)).status()).toBe(409); + + const confirmed = await ctx.post(`/auth/magic-link/verify/${token}/confirm`, { data: {} }); + expect(confirmed.status(), 'confirm without the code is refused').toBe(400); + expect((await ctx.get('/auth/magic-link/check')).status(), 'no session').toBe(204); + }); }); diff --git a/verify/harness/api/magicLink.spec.ts b/verify/harness/api/magicLink.spec.ts index 064bcfd..dfc74f1 100644 --- a/verify/harness/api/magicLink.spec.ts +++ b/verify/harness/api/magicLink.spec.ts @@ -1,5 +1,6 @@ import { expect, test } from '../lib/fixtures'; import { + confirmMagicLink, login, pollMagicLink, registerAndVerifyEmail, @@ -7,28 +8,79 @@ import { verifyMagicLink, } from '../lib/flows'; +// The link is `?token=T#code=C`. Opening it (GET verify) never signs in: +// only a confirm that carries the code from the fragment consumes it. A query string +// leaks through a Referer, an analytics beacon or an access log, so the token on its +// own must never be enough. + test.describe('magic link (api)', () => { - test('request -> poll(waiting) -> verify -> poll issues a session', async ({ actor }) => { + test('request -> poll(waiting) -> verify(409) -> confirm with code -> poll issues a session', async ({ + actor, + }) => { await registerAndVerifyEmail(actor.ctx, actor.email); // user must exist + be verified const ephemeral = await login(actor.ctx, actor.email); - const { token } = await requestMagicLink(actor.ctx, ephemeral); + const { token, code } = await requestMagicLink(actor.ctx, ephemeral); - // Polling before the link is verified must return 204 (still waiting) — never 500. + // Polling before the link is verified must return 204 (still waiting), never 500. // This is the exact regression that created the otp-sanatization branch. const pending = await pollMagicLink(actor.ctx, ephemeral); expect(pending.status(), 'poll before verify is 204, not 500').toBe(204); - const verified = await verifyMagicLink(actor.ctx, token); - expect(verified.ok(), `verify -> ${verified.status()}`).toBeTruthy(); + const verified = await verifyMagicLink(actor.ctx, token, ephemeral); + expect(verified.status(), 'verify never signs in, even on the requesting device').toBe(409); + const held = await verified.json(); + expect(held.error).toBe('confirmation_required'); + expect(held.sameDevice, 'the requesting attempt is recognised').toBe(true); + expect(held.requestedFrom?.requestedAt, 'requestedFrom says when it was asked for').toBeTruthy(); + + // Opening the link does not consume it. + expect((await pollMagicLink(actor.ctx, ephemeral)).status(), 'still waiting after verify').toBe( + 204, + ); + + const confirmed = await confirmMagicLink(actor.ctx, token, { code }, ephemeral); + expect(confirmed.ok(), `confirm -> ${confirmed.status()} ${await confirmed.text()}`).toBeTruthy(); const completed = await pollMagicLink(actor.ctx, ephemeral); - expect(completed.status(), 'poll after verify issues a session').toBe(200); + expect(completed.status(), 'poll after confirm issues a session').toBe(200); const body = await completed.json(); expect(body.token, 'session access token').toBeTruthy(); expect(body.refreshToken, 'session refresh token').toBeTruthy(); }); + test('a link with its fragment stripped cannot sign in', async ({ actor }) => { + await registerAndVerifyEmail(actor.ctx, actor.email); + const ephemeral = await login(actor.ctx, actor.email); + const { token } = await requestMagicLink(actor.ctx, ephemeral); + + // Everything a leaked query string hands over: the token, and the attempt that + // asked for it when the attacker requested the link themselves. + expect((await verifyMagicLink(actor.ctx, token, ephemeral)).status()).toBe(409); + const confirmed = await confirmMagicLink(actor.ctx, token, {}, ephemeral); + expect(confirmed.status(), 'confirm without the code is refused').toBe(400); + + expect( + (await pollMagicLink(actor.ctx, ephemeral)).status(), + 'no session without the code', + ).toBe(204); + }); + + test('a wrong code is refused and spends the link', async ({ actor }) => { + await registerAndVerifyEmail(actor.ctx, actor.email); + const ephemeral = await login(actor.ctx, actor.email); + const { token, code } = await requestMagicLink(actor.ctx, ephemeral); + + const wrong = await confirmMagicLink(actor.ctx, token, { code: `${code}x` }, ephemeral); + expect(wrong.status(), 'a wrong code is refused').toBe(400); + + // Spent, so the right code can no longer be guessed toward. + const retry = await confirmMagicLink(actor.ctx, token, { code }, ephemeral); + expect(retry.status(), 'the right code after a wrong one is refused').toBe(400); + expect((await verifyMagicLink(actor.ctx, token, ephemeral)).status(), 'spent link').toBe(400); + expect((await pollMagicLink(actor.ctx, ephemeral)).status(), 'no session').toBe(204); + }); + test('an invalid magic-link token is rejected', async ({ actor }) => { const res = await verifyMagicLink(actor.ctx, 'not-a-real-token'); expect(res.status()).toBe(400); diff --git a/verify/harness/lib/adapterFlows.ts b/verify/harness/lib/adapterFlows.ts index b853c65..9adfe12 100644 --- a/verify/harness/lib/adapterFlows.ts +++ b/verify/harness/lib/adapterFlows.ts @@ -1,15 +1,44 @@ import { APIRequestContext, expect } from '@playwright/test'; +import { MagicLink, parseMagicLink } from './flows'; + // Cookie-based flows against the adapter (baseURL = adapter). The adapter strips // OTP/magic-link secrets from browser responses, so codes are read from the // harness adapter app's /__captured readout. -async function readCapturedCode(ctx: APIRequestContext, email: string): Promise { +async function readCaptured( + ctx: APIRequestContext, + email: string, +): Promise<{ token: string; magicLinkUrl?: string }> { const res = await ctx.get(`/__captured/${encodeURIComponent(email)}`); expect(res.ok(), `captured lookup -> ${res.status()}`).toBeTruthy(); const body = await res.json(); expect(body?.token, `a captured code for ${email}`).toBeTruthy(); - return String(body.token); + return { token: String(body.token), magicLinkUrl: body.magicLinkUrl }; +} + +async function readCapturedCode(ctx: APIRequestContext, email: string): Promise { + return (await readCaptured(ctx, email)).token; +} + +/** The magic link the adapter delivered to `email`, split into token and code. */ +export async function readCapturedMagicLink( + ctx: APIRequestContext, + email: string, +): Promise { + const { magicLinkUrl } = await readCaptured(ctx, email); + expect(magicLinkUrl, `a captured magic link for ${email}`).toBeTruthy(); + return parseMagicLink(magicLinkUrl!); +} + +/** Request a magic link for a started login and return the delivered link. */ +export async function requestMagicLinkViaAdapter( + ctx: APIRequestContext, + email: string, +): Promise { + const res = await ctx.post('/auth/magic-link'); + expect(res.ok(), `magic-link request -> ${res.status()}`).toBeTruthy(); + return readCapturedMagicLink(ctx, email); } export async function registerAndVerifyEmail(ctx: APIRequestContext, email: string): Promise { @@ -37,21 +66,29 @@ export async function loginViaEmailOtp(ctx: APIRequestContext, email: string): P } export async function loginViaMagicLink(ctx: APIRequestContext, email: string): Promise { - let res = await ctx.post('/auth/login', { data: { identifier: email } }); + const res = await ctx.post('/auth/login', { data: { identifier: email } }); expect(res.ok(), `login -> ${res.status()}`).toBeTruthy(); - res = await ctx.post('/auth/magic-link'); - expect(res.ok(), `magic-link request -> ${res.status()}`).toBeTruthy(); - const token = await readCapturedCode(ctx, email); + const { token, code } = await requestMagicLinkViaAdapter(ctx, email); // Polling before the link is verified must return 204 (still waiting). const pending = await ctx.get('/auth/magic-link/check'); expect(pending.status(), 'poll before verify is 204').toBe(204); - res = await ctx.get(`/auth/magic-link/verify/${token}`); - expect(res.ok(), `verify magic link -> ${res.status()}`).toBeTruthy(); + // Opening the link never signs in. The adapter forwards the 409 body verbatim, and + // the pre-auth cookie it forwards marks this as the requesting device. + const verified = await ctx.get(`/auth/magic-link/verify/${token}`); + expect(verified.status(), `verify magic link -> ${verified.status()}`).toBe(409); + const held = await verified.json(); + expect(held.error, 'verify holds the link for confirmation').toBe('confirmation_required'); + expect(held.sameDevice, 'the adapter forwards the requesting attempt').toBe(true); + + const confirmed = await ctx.post(`/auth/magic-link/verify/${token}/confirm`, { + data: { code }, + }); + expect(confirmed.ok(), `confirm magic link -> ${confirmed.status()}`).toBeTruthy(); - // Polling after verification issues the session (device binding must match). + // Polling after confirmation issues the session (device binding must match). const completed = await ctx.get('/auth/magic-link/check'); - expect(completed.status(), 'poll after verify issues a session').toBe(200); + expect(completed.status(), 'poll after confirm issues a session').toBe(200); } diff --git a/verify/harness/lib/flows.ts b/verify/harness/lib/flows.ts index 8ec9e6f..680e2d7 100644 --- a/verify/harness/lib/flows.ts +++ b/verify/harness/lib/flows.ts @@ -104,22 +104,59 @@ export async function login(ctx: APIRequestContext, identifier: string): Promise return body.token as string; } -/** Request a magic link; returns the raw token + URL via external delivery. */ +export interface MagicLink { + /** Lookup handle from the query string. On its own it signs nobody in. */ + token: string; + /** Proof from the fragment, which never reaches a server, a Referer or an access log. */ + code: string; + url: string; +} + +/** Split a delivered link, `?token=T#code=C`, into its token and code. */ +export function parseMagicLink(magicLinkUrl: string): MagicLink { + const url = new URL(magicLinkUrl); + const token = url.searchParams.get('token'); + const code = new URLSearchParams(url.hash.slice(1)).get('code'); + expect(token, `the link carries ?token= (${magicLinkUrl})`).toBeTruthy(); + expect(code, `the link carries #code= (${magicLinkUrl})`).toBeTruthy(); + expect(url.searchParams.has('code'), 'the code stays out of the query string').toBe(false); + return { token: token!, code: code!, url: magicLinkUrl }; +} + +/** Request a magic link; returns the delivered link via external delivery. */ export async function requestMagicLink( ctx: APIRequestContext, ephemeral: string, -): Promise<{ token: string; magicLinkUrl: string }> { +): Promise { const res = await ctx.get('/magic-link', { headers: { ...bearer(ephemeral), ...EXTERNAL_DELIVERY }, }); expect(res.ok(), `magic-link request -> ${res.status()} ${await res.text()}`).toBeTruthy(); const body = await res.json(); - expect(body?.delivery?.token, 'external delivery returns the magic-link token').toBeTruthy(); - return { token: body.delivery.token, magicLinkUrl: body.delivery.magicLinkUrl }; + expect(body?.delivery?.magicLinkUrl, 'external delivery returns the magic link').toBeTruthy(); + const link = parseMagicLink(body.delivery.magicLinkUrl); + expect(link.token, 'delivery.token is the token in the link').toBe(body.delivery.token); + return link; } -export function verifyMagicLink(ctx: APIRequestContext, rawToken: string) { - return ctx.get(`/magic-link/verify/${rawToken}`); +/** Open a link. It never signs in: it answers 409 confirmation_required. */ +export function verifyMagicLink(ctx: APIRequestContext, rawToken: string, ephemeral?: string) { + return ctx.get(`/magic-link/verify/${rawToken}`, { + headers: ephemeral ? bearer(ephemeral) : {}, + }); +} + +/** Confirm a link with the code from its fragment. This is what consumes it. */ +export function confirmMagicLink( + ctx: APIRequestContext, + rawToken: string, + body: { code?: string }, + ephemeral?: string, +) { + return ctx.post(`/magic-link/verify/${rawToken}/confirm`, { + headers: ephemeral ? bearer(ephemeral) : {}, + data: body, + }); } export function pollMagicLink(ctx: APIRequestContext, ephemeral: string) { diff --git a/verify/harness/lib/nextjsFlows.ts b/verify/harness/lib/nextjsFlows.ts index b7d4c53..1cb7325 100644 --- a/verify/harness/lib/nextjsFlows.ts +++ b/verify/harness/lib/nextjsFlows.ts @@ -12,15 +12,49 @@ import { expect, Page } from '@playwright/test'; const capturePath = (recipient: string) => `/api/verify-capture/${encodeURIComponent(recipient)}`; -async function readCapture(page: Page, recipient: string): Promise { +async function readCaptureBody( + page: Page, + recipient: string, +): Promise<{ token?: unknown; magicLinkUrl?: unknown } | null> { const { status, body } = await page.evaluate(async (path) => { const res = await fetch(path, { cache: 'no-store' }); return { status: res.status, body: res.ok ? await res.json() : null }; }, capturePath(recipient)); expect(status, `capture readout -> ${status} (is SEAMLESS_VERIFY_CAPTURE set?)`).toBe(200); + return body; +} + +async function readCapture(page: Page, recipient: string): Promise { + const body = await readCaptureBody(page, recipient); return body?.token ? String(body.token) : undefined; } +/** + * The magic link the starter captured for `recipient`, as a path on the app's origin + * (`/verify-magiclink?token=T#code=C`). Pass the token captured before the request as + * `previous` to wait for the new link. + */ +export async function readStarterMagicLink( + page: Page, + recipient: string, + previous?: string, +): Promise { + let link: string | undefined; + await expect + .poll( + async () => { + const body = await readCaptureBody(page, recipient); + if (!body?.magicLinkUrl || String(body.token) === previous) return false; + const url = new URL(String(body.magicLinkUrl)); + link = `${url.pathname}${url.search}${url.hash}`; + return true; + }, + { message: `a new magic link captured for ${recipient}`, timeout: 10_000 }, + ) + .toBe(true); + return link!; +} + /** The latest code the starter captured for `recipient`, or undefined if none yet. */ export function lastCapturedCode(page: Page, recipient: string): Promise { return readCapture(page, recipient); diff --git a/verify/harness/lib/reactFlows.ts b/verify/harness/lib/reactFlows.ts index e1c6884..10aaaa4 100644 --- a/verify/harness/lib/reactFlows.ts +++ b/verify/harness/lib/reactFlows.ts @@ -15,6 +15,37 @@ export function readCapturedCode(recipient: string, timeoutMs = 10_000): Promise ); } +/** + * The magic link the adapter delivered to `recipient`, polling until present, as a + * path the page's baseURL resolves (`/verify-magiclink?token=T#code=C`). The fragment + * is kept: it carries the code the confirm needs. + */ +export async function readCapturedMagicLink(recipient: string, timeoutMs = 10_000): Promise { + const ctx = await request.newContext(); + try { + const url = `${ADAPTER_URL}/__captured/${encodeURIComponent(recipient)}`; + const deadline = Date.now() + timeoutMs; + let last = 'never set'; + while (Date.now() < deadline) { + const res = await ctx.get(url); + if (res.ok()) { + const body = await res.json(); + if (body?.magicLinkUrl) { + const link = new URL(String(body.magicLinkUrl)); + return `${link.pathname}${link.search}${link.hash}`; + } + last = JSON.stringify(body); + } else { + last = `status ${res.status()}`; + } + await new Promise((r) => setTimeout(r, 300)); + } + throw new Error(`no captured magic link for ${recipient} within ${timeoutMs}ms (last: ${last})`); + } finally { + await ctx.dispose(); + } +} + /** * Poll a capture readout (`{ token }`, or null until something was sent) until it * holds a code. The adapter and the full-stack starters each serve one. A readout diff --git a/verify/harness/nextjs/magicLinkLogin.spec.ts b/verify/harness/nextjs/magicLinkLogin.spec.ts index 24da6f9..d6fe505 100644 --- a/verify/harness/nextjs/magicLinkLogin.spec.ts +++ b/verify/harness/nextjs/magicLinkLogin.spec.ts @@ -3,7 +3,7 @@ import { registerAndVerifyEmail } from '../lib/flows'; import { expectSignedIn, lastCapturedCode, - readStarterCode, + readStarterMagicLink, startSignIn, } from '../lib/nextjsFlows'; @@ -20,18 +20,22 @@ test.describe('magic link login (nextjs, browser)', { tag: '@login' }, () => { await page.getByRole('button', { name: 'Email me a sign-in link' }).click(); await expect(page.getByText(/We emailed a sign-in link/)).toBeVisible(); - const token = await readStarterCode(page, actor.email, previous); + const link = await readStarterMagicLink(page, actor.email, previous); const linkTab = await context.newPage(); - // The link is single use, and the dev pass runs under Strict Mode, which runs - // the verify effect twice. Every verify request the tab sends has to succeed. + // Opening the link (GET verify) never signs in: it answers 409 with + // `sameDevice: true` in the browser that asked, and the page confirms with the + // code from the fragment. The confirm spends the link, and the dev pass runs + // under Strict Mode, which runs the effect twice, so every confirm has to succeed. const verifyStatuses: number[] = []; + const confirmStatuses: number[] = []; linkTab.on('response', (res) => { - if (new URL(res.url()).pathname.startsWith('/auth/magic-link/verify/')) { - verifyStatuses.push(res.status()); - } + const { pathname } = new URL(res.url()); + if (!pathname.startsWith('/auth/magic-link/verify/')) return; + if (pathname.endsWith('/confirm')) confirmStatuses.push(res.status()); + else verifyStatuses.push(res.status()); }); - await linkTab.goto(`/verify-magiclink?token=${encodeURIComponent(token)}`); + await linkTab.goto(link); // The requesting tab collects the session from /magic-link/check. await expect(page.getByRole('heading', { name: 'Your session' })).toBeVisible({ @@ -44,10 +48,14 @@ test.describe('magic link login (nextjs, browser)', { tag: '@login' }, () => { timeout: 15_000, }); await expect(linkTab.getByText('This link did not work')).toHaveCount(0); - expect(verifyStatuses.length, 'the link was verified').toBeGreaterThan(0); + expect(confirmStatuses.length, 'the link was confirmed').toBeGreaterThan(0); expect( - verifyStatuses.filter((status) => status >= 400), - `every verify request for the link succeeded (got ${verifyStatuses.join(', ')})`, + verifyStatuses.filter((status) => status !== 409), + `every verify answered 409 confirmation_required (got ${verifyStatuses.join(', ')})`, + ).toEqual([]); + expect( + confirmStatuses.filter((status) => status >= 400), + `every confirm for the link succeeded (got ${confirmStatuses.join(', ')})`, ).toEqual([]); await linkTab.close(); }); diff --git a/verify/harness/react/magicLinkLogin.spec.ts b/verify/harness/react/magicLinkLogin.spec.ts index 35edcda..5ce5f30 100644 --- a/verify/harness/react/magicLinkLogin.spec.ts +++ b/verify/harness/react/magicLinkLogin.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from '../lib/fixtures'; import { registerAndVerifyEmail } from '../lib/flows'; -import { gotoSignIn, readCapturedCode } from '../lib/reactFlows'; +import { gotoSignIn, readCapturedMagicLink } from '../lib/reactFlows'; test.describe('magic link login (react, browser)', { tag: '@login' }, () => { test('request a magic link, open it in a second tab -> original tab authenticates', async ({ @@ -17,34 +17,45 @@ test.describe('magic link login (react, browser)', { tag: '@login' }, () => { await page.getByRole('button', { name: /Email Magic Link/ }).click(); await expect(page.getByRole('heading', { name: 'Check your email' })).toBeVisible(); - // "Click" the emailed link in a second tab; the original tab completes via - // BroadcastChannel + polling (same device binding — same browser/adapter). - const token = await readCapturedCode(actor.email); + // "Click" the emailed link, `/verify-magiclink?token=T#code=C`, in a second tab; + // the original tab completes via BroadcastChannel + polling. + const link = await readCapturedMagicLink(actor.email); const linkTab = await context.newPage(); - // The link is single use. Under Strict Mode (the react-dev project) an - // unguarded verify effect runs twice: the first request spends the link and - // the second is refused, and the screen reports that refusal. Every verify - // request the tab sends has to succeed. + // Opening the link (GET verify) never signs in: it answers 409 with + // `sameDevice: true` here, since the tab shares the requesting browser. The + // screen then confirms with the code from the fragment, without asking, and + // that confirm is what spends the link. Under Strict Mode (the react-dev + // project) an unguarded effect runs twice, and a second confirm finds the link + // spent and is refused, so every confirm the tab sends has to succeed. const verifyStatuses: number[] = []; + const confirmStatuses: number[] = []; linkTab.on('response', (res) => { - if (new URL(res.url()).pathname.startsWith('/auth/magic-link/verify/')) { - verifyStatuses.push(res.status()); - } + const { pathname } = new URL(res.url()); + if (!pathname.startsWith('/auth/magic-link/verify/')) return; + if (pathname.endsWith('/confirm')) confirmStatuses.push(res.status()); + else verifyStatuses.push(res.status()); }); - await linkTab.goto(`/verify-magiclink?token=${encodeURIComponent(token)}`); + await linkTab.goto(link); await expect(page.getByText('You are signed in')).toBeVisible({ timeout: 15_000 }); await expect - .poll(() => verifyStatuses.length, { message: 'the link was verified' }) + .poll(() => confirmStatuses.length, { message: 'the link was confirmed' }) .toBeGreaterThan(0); await linkTab.waitForLoadState('networkidle'); expect( - verifyStatuses.filter((status) => status >= 400), - `every verify request for the link succeeded (got ${verifyStatuses.join(', ')})`, + verifyStatuses.filter((status) => status !== 409), + `every verify answered 409 confirmation_required (got ${verifyStatuses.join(', ')})`, ).toEqual([]); + expect( + confirmStatuses.filter((status) => status >= 400), + `every confirm for the link succeeded (got ${confirmStatuses.join(', ')})`, + ).toEqual([]); + expect(new URL(linkTab.url()).hash, 'the screen strips the code from the address').not.toContain( + 'code=', + ); await expect(linkTab.getByText('Failed to verify token')).toHaveCount(0); await linkTab.close(); }); diff --git a/verify/svelte-app/Dockerfile b/verify/svelte-app/Dockerfile index aacb72c..f89cf55 100644 --- a/verify/svelte-app/Dockerfile +++ b/verify/svelte-app/Dockerfile @@ -1,12 +1,14 @@ # The verify harness builds this image with an `sdk` build context: verify/svelte-vendor, # which holds local @seamless-auth/client and @seamless-auth/svelte tarballs on a --local # run and nothing otherwise. Without them, the published @seamless-auth/svelte is used. +# The version is pinned rather than `latest`: the CI build cache keys this layer on the +# command and its build args, so `latest` would keep serving the release it first resolved. FROM node:24-slim AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci COPY --from=sdk . /tmp/sdk/ -ARG SEAMLESS_SVELTE_VERSION=latest +ARG SEAMLESS_SVELTE_VERSION=0.5.0 RUN if ls /tmp/sdk/*.tgz >/dev/null 2>&1; then \ npm install --no-save /tmp/sdk/*.tgz; \ else \ diff --git a/verify/vue-app/Dockerfile b/verify/vue-app/Dockerfile index 30ab114..03d63fd 100644 --- a/verify/vue-app/Dockerfile +++ b/verify/vue-app/Dockerfile @@ -1,12 +1,14 @@ # The verify harness builds this image with an `sdk` build context: verify/vue-vendor, # which holds local @seamless-auth/client and @seamless-auth/vue tarballs on a --local # run and nothing otherwise. Without them, the published @seamless-auth/vue is used. +# The version is pinned rather than `latest`: the CI build cache keys this layer on the +# command and its build args, so `latest` would keep serving the release it first resolved. FROM node:24-slim AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci COPY --from=sdk . /tmp/sdk/ -ARG SEAMLESS_VUE_VERSION=latest +ARG SEAMLESS_VUE_VERSION=0.5.0 RUN if ls /tmp/sdk/*.tgz >/dev/null 2>&1; then \ npm install --no-save /tmp/sdk/*.tgz; \ else \