Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/verify-magic-link-confirm.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 18 additions & 3 deletions verify/CONFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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": "<code or link token>", "magicLinkUrl"?: "..." }`, or `null` |
| `GET /__captured/:recipient` | The most recent message the adapter delivered to `recipient` (an email address or phone number): `{ "token": "<code or link 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
Expand All @@ -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 `<target>?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
`<frontend_url or origin>/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
Expand Down
4 changes: 3 additions & 1 deletion verify/angular-app/Dockerfile
Original file line number Diff line number Diff line change
@@ -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 \
Expand Down
24 changes: 22 additions & 2 deletions verify/harness/adapter/magicLink.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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);
});
});
64 changes: 58 additions & 6 deletions verify/harness/api/magicLink.spec.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,86 @@
import { expect, test } from '../lib/fixtures';
import {
confirmMagicLink,
login,
pollMagicLink,
registerAndVerifyEmail,
requestMagicLink,
verifyMagicLink,
} from '../lib/flows';

// The link is `<target>?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);
Expand Down
57 changes: 47 additions & 10 deletions verify/harness/lib/adapterFlows.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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<string> {
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<MagicLink> {
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<MagicLink> {
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<void> {
Expand Down Expand Up @@ -37,21 +66,29 @@ export async function loginViaEmailOtp(ctx: APIRequestContext, email: string): P
}

export async function loginViaMagicLink(ctx: APIRequestContext, email: string): Promise<void> {
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);
}
49 changes: 43 additions & 6 deletions verify/harness/lib/flows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<target>?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<MagicLink> {
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) {
Expand Down
36 changes: 35 additions & 1 deletion verify/harness/lib/nextjsFlows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | undefined> {
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<string | undefined> {
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<string> {
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<string | undefined> {
return readCapture(page, recipient);
Expand Down
Loading
Loading