diff --git a/.changeset/magic-link-fragment-code.md b/.changeset/magic-link-fragment-code.md new file mode 100644 index 00000000..59fac8dd --- /dev/null +++ b/.changeset/magic-link-fragment-code.md @@ -0,0 +1,14 @@ +--- +'seamless-auth-api': minor +--- + +Magic links now need a code from the link fragment to sign in, and a requested `redirectUri` must match exactly (#594). + +Breaking, in two places: + +- `redirectUri` on `POST /magic-link` is no longer accepted on its origin alone. With `magic_link_redirect_uris` empty, the only accepted value is the `/verify-magiclink` page on `frontend_url` or a configured origin, spelled exactly with no query. Any other path, such as a mobile landing page, has to be listed in `magic_link_redirect_uris`. +- The link is now `...?token=#code=`. `GET /magic-link/verify/:token` no longer consumes the link, even on the device that requested it: it always answers `409 confirmation_required`, with a new `sameDevice` boolean. `POST /magic-link/verify/:token/confirm` now requires a JSON body `{ "code": "" }` and answers `400` without it. A wrong code spends the link. Links mailed before the upgrade carry no code and can no longer be completed, so a user with one in flight requests another. + +Clients need to read `code` from the fragment, confirm with it, and confirm without asking when `sameDevice` is true. Release a client that does this before upgrading the API: it keeps working against older API versions, which ignore the body. A caller using external delivery that builds its own URL from `delivery.token` has to switch to `delivery.magicLinkUrl`, which carries the code. + +Run the database migrations: this adds `magic_link_tokens.code_hash`. diff --git a/docs/api-contract.md b/docs/api-contract.md index e3f72129..8f136997 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -77,23 +77,37 @@ protocol in [ecosystem.md](./ecosystem.md). link lands. Omit it and the link keeps the tenant-wide destination, `frontend_url` falling back to the first configured origin, which is what every existing caller gets. -A supplied value is validated against the configured `origins` the same way -`resolveOAuthRedirectUri` validates an OAuth redirect, and a value outside them answers `400`. -That is what lets one tenant serve a web client and a mobile client without them sharing a -single destination. The token is set as a `token` query parameter on the target, replacing one -of that name the caller had already put there. - -A destination that cannot be expressed as an origin, a custom scheme such as `myapp://auth` or a -universal link on a host that is not a WebAuthn origin, goes in the `magic_link_redirect_uris` -system config key instead. Entries there are matched exactly, which is what makes a custom -scheme safe to accept: there is no origin to compare, so only a literal an operator listed is -allowed. The key defaults to `[]`, and an empty list falls back to comparing against `origins`, -so a deployment that sets nothing behaves as described above. - -Setting it narrows rather than widens. Once the list is non-empty it is the whole allowlist, and -a destination on a configured origin that is not listed is refused. That is deliberate: a tenant -that needs a mobile scheme should not have to widen `origins`, which gates passkey ceremonies, to -get it. +A supplied value must match an entry of the `magic_link_redirect_uris` system config key +exactly. While that key is empty (the default), the only accepted values are the +`/verify-magiclink` page on `frontend_url` or on one of the configured `origins`, spelled +exactly, with no query of its own. Anything else answers `400`. Matching on origin alone used to +let a link land on any page of the site, including one that forwards its URL to a third party. + +A destination that is not that page, a custom scheme such as `myapp://auth`, a universal link on +a host that is not a WebAuthn origin, or a second path for a mobile client, goes in +`magic_link_redirect_uris`. Once the list is non-empty it is the whole allowlist, and the +default verify page is refused unless it is listed too. A tenant that needs a mobile scheme +should not have to widen `origins`, which gates passkey ceremonies, to get it. + +### Magic link token and code + +The link carries two values: `?token=` in the query and `#code=` in the fragment. Both replace +any of that name the target already had. The token finds the link; the code proves the person +reading the email is the one completing it. A fragment is never sent to a server and never +appears in a `Referer`, so a page that leaks its query string through a third-party request, an +analytics beacon or an access log hands out a token that cannot sign anyone in. + +- `GET /magic-link/verify/:token` describes the link and never consumes it. It always answers + `409 confirmation_required` with `requestedFrom` and `sameDevice`, which is true when the link + was opened by the attempt that requested it (the forwarded pre-auth bearer, or the IP and user + agent a trusted adapter forwards). A client may confirm without asking when it is true. +- `POST /magic-link/verify/:token/confirm` takes `{ "code": "" }` and + consumes the link. A request with no code answers `400` from validation; a wrong code answers + `400` and spends the link. The requesting device collects the session from + `GET /magic-link/check` as before. + +The landing page should read both values and drop them from the address bar +(`history.replaceState`) before it loads anything else. ### Native and mobile clients @@ -113,7 +127,7 @@ IP forwarding in the path while the app holds the tokens. What a deployment has - **Magic links.** A universal link on the web origin needs nothing extra. A custom scheme goes in `magic_link_redirect_uris` (exact match, see above). The app can also skip the link entirely and poll `GET /magic-link/check` with the ephemeral token until the session arrives, since - `/magic-link/verify/:token` completes the link from whichever device opened it. + `/magic-link/verify/:token/confirm` completes the link from whichever device opened it. - **OAuth.** A custom-scheme `redirectUri` is accepted when it is on the provider's `redirectUris` allowlist. Some providers refuse custom schemes on a web client type; a universal link on the web origin's `/oauth/callback` sidesteps that. diff --git a/docs/security-posture.md b/docs/security-posture.md index 5542681a..0a0928cf 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -95,7 +95,7 @@ A decoy responder that only reproduces the success path is not finished. Any `40 account can be made to answer is an oracle if a decoy answers `200` to the same request, and the ones that matter are the ones a caller can trigger on purpose: -- `/magic-link?redirectUri=` pointing somewhere the configured origins do not allow +- `/magic-link?redirectUri=` pointing somewhere the magic link allowlist does not allow answers `400 Redirect URI is not allowed`. A caller picks that value, so this is one deliberately bad request away. The decoy responder runs the same `resolveMagicLinkUrl` validation. diff --git a/openapi.json b/openapi.json index 6e277e0c..9f21713a 100644 --- a/openapi.json +++ b/openapi.json @@ -17190,128 +17190,12 @@ "/magic-link/verify/{token}": { "get": { "summary": "Verify magic link token", - "description": "Consumes the link when it is opened on the device that requested it, proven by the requesting attempt's ephemeral bearer token when the adapter forwards it, otherwise by the IP address and user agent a trusted adapter forwards. Opened anywhere else, answers 409 without consuming it; confirm with POST /magic-link/verify/{token}/confirm.", + "description": "Describes the link without consuming it, always answering 409 confirmation_required. `sameDevice` is true when it was opened by the attempt that requested it, proven by that attempt's ephemeral bearer token when the adapter forwards it, otherwise by the IP address and user agent a trusted adapter forwards. Consume it with POST /magic-link/verify/{token}/confirm and the code from the link fragment.", "tags": ["MagicLinks"], "parameters": [ { "schema": { "type": "string" }, "required": true, "name": "token", "in": "path" } ], "responses": { - "200": { - "description": "HTTP 200", - "content": { - "application/json": { - "example": { "message": "string", "token": "string", "delivery": null }, - "schema": { - "type": "object", - "properties": { - "message": { "type": "string" }, - "token": { "type": "string" }, - "delivery": { - "oneOf": [ - { - "type": "object", - "properties": { - "kind": { "type": "string", "enum": ["otp_email"] }, - "to": { "type": "string" }, - "token": { "type": "string" }, - "purpose": { "type": "string", "enum": ["account_recovery"] } - }, - "required": ["kind", "to", "token"] - }, - { - "type": "object", - "properties": { - "kind": { "type": "string", "enum": ["otp_sms"] }, - "to": { "type": "string" }, - "token": { "anyOf": [{ "type": "string" }, { "type": "number" }] }, - "purpose": { "type": "string", "enum": ["account_recovery"] } - }, - "required": ["kind", "to", "token"] - }, - { - "type": "object", - "properties": { - "kind": { "type": "string", "enum": ["magic_link_email"] }, - "to": { "type": "string" }, - "token": { "type": "string" }, - "magicLinkUrl": { "type": "string" } - }, - "required": ["kind", "to", "magicLinkUrl"] - }, - { - "type": "object", - "properties": { - "kind": { "type": "string", "enum": ["enrollment_invite_email"] }, - "to": { "type": "string" }, - "signInUrl": { "type": "string" } - }, - "required": ["kind", "to", "signInUrl"] - }, - { - "type": "object", - "properties": { - "kind": { "type": "string", "enum": ["account_notice_email"] }, - "notice": { - "type": "string", - "enum": [ - "account_recovery_opened", - "account_recovery_completed", - "recovery_code_used", - "identity_changed", - "application_notice" - ] - }, - "to": { "type": "string" }, - "subject": { "type": "string" }, - "text": { "type": "string" }, - "cancelUrl": { "type": "string" }, - "application": { - "type": "object", - "properties": { - "clientId": { "type": "string" }, - "name": { "type": "string" } - }, - "required": ["clientId", "name"] - } - }, - "required": ["kind", "notice", "to", "subject", "text"] - }, - { - "type": "object", - "properties": { - "kind": { "type": "string", "enum": ["account_notice_sms"] }, - "notice": { - "type": "string", - "enum": [ - "account_recovery_opened", - "account_recovery_completed", - "recovery_code_used", - "identity_changed", - "application_notice" - ] - }, - "to": { "type": "string" }, - "text": { "type": "string" }, - "cancelUrl": { "type": "string" }, - "application": { - "type": "object", - "properties": { - "clientId": { "type": "string" }, - "name": { "type": "string" } - }, - "required": ["clientId", "name"] - } - }, - "required": ["kind", "notice", "to", "text"] - } - ] - } - }, - "required": ["message"] - } - } - } - }, "400": { "description": "HTTP 400", "content": { @@ -17373,6 +17257,7 @@ "example": { "error": null, "message": "string", + "sameDevice": true, "requestedFrom": { "deviceClass": null, "requestedAt": "string" } }, "schema": { @@ -17380,6 +17265,7 @@ "properties": { "error": { "type": "string", "enum": ["confirmation_required"] }, "message": { "type": "string" }, + "sameDevice": { "type": "boolean" }, "requestedFrom": { "type": "object", "properties": { @@ -17401,7 +17287,7 @@ "required": ["deviceClass", "requestedAt"] } }, - "required": ["error", "message", "requestedFrom"] + "required": ["error", "message", "sameDevice", "requestedFrom"] } } } @@ -17437,12 +17323,23 @@ }, "/magic-link/verify/{token}/confirm": { "post": { - "summary": "Confirm a magic link opened on another device", - "description": "Consumes the link after the person who opened it has approved signing in the device that requested it.", + "summary": "Confirm a magic link", + "description": "Consumes the link, signing in the device that requested it. Takes the `code` the link carries in its fragment (`#code=`), which never appears in a query string or a Referer. A wrong code spends the link.", "tags": ["MagicLinks"], "parameters": [ { "schema": { "type": "string" }, "required": true, "name": "token", "in": "path" } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { "code": { "type": "string", "minLength": 1, "maxLength": 256 } }, + "required": ["code"] + } + } + } + }, "responses": { "200": { "description": "HTTP 200", diff --git a/src/controllers/decoyResponders.ts b/src/controllers/decoyResponders.ts index 270e2e41..49ec63cc 100644 --- a/src/controllers/decoyResponders.ts +++ b/src/controllers/decoyResponders.ts @@ -224,10 +224,8 @@ export const decoyRequestMagicLink = async (req: Request, res: Response) => { // of one deliberately bad request. The URL the first one builds goes nowhere, since // nothing is mailed; the call is made for its refusal. try { - await resolveMagicLinkUrl( - decoyCredentialIdFor(decoySubject(req)), - req.query.redirectUri as string | undefined, - ); + const decoyId = decoyCredentialIdFor(decoySubject(req)); + await resolveMagicLinkUrl(decoyId, decoyId, req.query.redirectUri as string | undefined); } catch (error) { if (error instanceof MagicLinkRedirectNotAllowedError) { return res.status(400).json({ error: 'Redirect URI is not allowed' }); diff --git a/src/controllers/magicLinks.ts b/src/controllers/magicLinks.ts index 358ceebf..45ce5406 100644 --- a/src/controllers/magicLinks.ts +++ b/src/controllers/magicLinks.ts @@ -13,7 +13,10 @@ import { classifyDeviceClass } from '../lib/deviceClass.js'; import { canReturnExternalDelivery } from '../lib/externalDelivery.js'; import { MagicLinkToken } from '../models/magicLinks.js'; import { User } from '../models/users.js'; -import { MagicLinkRequestQuerySchema } from '../schemas/magiclink.requests.js'; +import { + MagicLinkConfirmBodySchema, + MagicLinkRequestQuerySchema, +} from '../schemas/magiclink.requests.js'; import { claimUnverifiedAccount } from '../services/accountClaim.js'; import { AuthEventService } from '../services/authEventService.js'; import { rejectWeakFactorForBreakGlass } from '../services/breakGlassService.js'; @@ -105,11 +108,12 @@ export async function requestMagicLink(req: MagicLinkRequest, res: Response) { const rawToken = crypto.randomBytes(32).toString('base64url'); const tokenHash = hashSha256(rawToken); + const rawCode = crypto.randomBytes(32).toString('base64url'); let redirect_url: string; try { - redirect_url = await resolveMagicLinkUrl(rawToken, req.query.redirectUri); + redirect_url = await resolveMagicLinkUrl(rawToken, rawCode, req.query.redirectUri); } catch (error) { if (error instanceof MagicLinkRedirectNotAllowedError) { await logMagicLinkFailure(req, 'Redirect URI not allowed', user.id); @@ -147,7 +151,9 @@ export async function requestMagicLink(req: MagicLinkRequest, res: Response) { const magicLinkRecord = await MagicLinkToken.create({ user_id: user.id, token_hash: tokenHash, - redirect_url, + code_hash: hashSha256(rawCode), + // Without the fragment, so a read of this table yields no code to confirm with. + redirect_url: redirect_url.split('#')[0], ip_hash, user_agent_hash, attempt_id: authReq.attemptId, @@ -274,13 +280,15 @@ async function consumeLink( /** * Whether the request that opened the link comes from the device that asked for it. * - * The session goes to the requesting device, so a link opened anywhere else must not - * complete silently: anyone can request a link for someone else's address from their - * own machine. The pre-auth token, when the adapter forwards it, proves the attempt. - * Without it the IP and user agent are the only signal, which people behind one - * address with the same browser can share. They count only when a trusted adapter - * vouched for them: otherwise every request carries the adapter's own address, and - * every device would look like the one that asked. + * The pre-auth token, when the adapter forwards it, proves the attempt. Without it the + * IP and user agent are the only signal, which people behind one address with the same + * browser can share. They count only when a trusted adapter vouched for them: otherwise + * every request carries the adapter's own address, and every device would look like the + * one that asked. + * + * This only decides whether the client asks the person before confirming. It is not a + * reason to consume the link: the attempt belongs to whoever requested it, and anyone + * can request a link for someone else's address. */ async function openedOnRequestingDevice(req: RouteRequest, record: MagicLinkToken) { const auth = req.headers.authorization; @@ -306,6 +314,21 @@ async function openedOnRequestingDevice(req: RouteRequest, record: MagicLinkToke ); } +function codeMatches(code: string, codeHash: string) { + const presented = Buffer.from(hashSha256(code)); + const stored = Buffer.from(codeHash); + + return presented.length === stored.length && crypto.timingSafeEqual(presented, stored); +} + +/** + * Describes a link without consuming it. + * + * Consuming takes the code from the link's fragment, which only the confirm request + * carries. The token alone is in the query string, which is the part of a URL that leaks + * through a Referer, an analytics beacon or an access log, so it must not be enough to + * sign anyone in, even from the device that requested the link. + */ export async function verifyMagicLink(req: RouteRequest, res: Response) { logger.debug('Verifying magic link'); @@ -315,34 +338,55 @@ export async function verifyMagicLink(req: RouteRequest, res: Response) { return; } - if (!(await openedOnRequestingDevice(req, record))) { - await AuthEventService.log({ - userId: record.user_id, - type: 'magic_link_confirmation_required', - req, - }); + const sameDevice = await openedOnRequestingDevice(req, record); - return res.status(409).json({ - error: 'confirmation_required', - message: 'This link was requested from another device. Confirm to sign that device in.', - requestedFrom: { - deviceClass: record.requested_device_class ?? 'unknown', - requestedAt: new Date(record.created_at).toISOString(), - }, - }); - } + await AuthEventService.log({ + userId: record.user_id, + type: 'magic_link_confirmation_required', + req, + metadata: { sameDevice }, + }); - return consumeLink(req, res, record, 'same_device'); + return res.status(409).json({ + error: 'confirmation_required', + message: sameDevice + ? 'Confirm to finish signing in.' + : 'This link was requested from another device. Confirm to sign that device in.', + sameDevice, + requestedFrom: { + deviceClass: record.requested_device_class ?? 'unknown', + requestedAt: new Date(record.created_at).toISOString(), + }, + }); } -export async function confirmMagicLink(req: RouteRequest, res: Response) { +export async function confirmMagicLink( + req: Request, unknown, z.infer>, + res: Response, +) { const record = await findUsableLink(req, res); if (!record) { return; } - return consumeLink(req, res, record, 'confirmed'); + // A link from before codes existed was mailed without one, so nothing can prove it. + if (!record.code_hash || !codeMatches(req.body.code, record.code_hash)) { + logger.warn('Magic link code did not match'); + + // Someone holding the token without the code is what a leaked query string looks + // like, so the link is spent rather than left open to further guesses. + await MagicLinkToken.update( + { expires_at: new Date() }, + { where: { id: record.id, used_at: null } }, + ); + await logMagicLinkFailure(req, 'Invalid confirmation code', record.user_id); + return res.status(400).json({ error: 'Invalid verification token' }); + } + + const sameDevice = await openedOnRequestingDevice(req, record); + + return consumeLink(req, res, record, sameDevice ? 'same_device' : 'confirmed'); } export async function pollMagicLinkConfirmation(req: Request, res: Response) { diff --git a/src/generated/api.ts b/src/generated/api.ts index 715cdbb7..a312854e 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -15961,7 +15961,7 @@ export interface paths { }; /** * Verify magic link token - * @description Consumes the link when it is opened on the device that requested it, proven by the requesting attempt's ephemeral bearer token when the adapter forwards it, otherwise by the IP address and user agent a trusted adapter forwards. Opened anywhere else, answers 409 without consuming it; confirm with POST /magic-link/verify/{token}/confirm. + * @description Describes the link without consuming it, always answering 409 confirmation_required. `sameDevice` is true when it was opened by the attempt that requested it, proven by that attempt's ephemeral bearer token when the adapter forwards it, otherwise by the IP address and user agent a trusted adapter forwards. Consume it with POST /magic-link/verify/{token}/confirm and the code from the link fragment. */ get: { parameters: { @@ -15974,92 +15974,6 @@ export interface paths { }; requestBody?: never; responses: { - /** @description HTTP 200 */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - /** - * @example { - * "message": "string", - * "token": "string", - * "delivery": null - * } - */ - 'application/json': { - message: string; - token?: string; - delivery?: - | { - /** @enum {string} */ - kind: 'otp_email'; - to: string; - token: string; - /** @enum {string} */ - purpose?: 'account_recovery'; - } - | { - /** @enum {string} */ - kind: 'otp_sms'; - to: string; - token: string | number; - /** @enum {string} */ - purpose?: 'account_recovery'; - } - | { - /** @enum {string} */ - kind: 'magic_link_email'; - to: string; - token?: string; - magicLinkUrl: string; - } - | { - /** @enum {string} */ - kind: 'enrollment_invite_email'; - to: string; - signInUrl: string; - } - | { - /** @enum {string} */ - kind: 'account_notice_email'; - /** @enum {string} */ - notice: - | 'account_recovery_opened' - | 'account_recovery_completed' - | 'recovery_code_used' - | 'identity_changed' - | 'application_notice'; - to: string; - subject: string; - text: string; - cancelUrl?: string; - application?: { - clientId: string; - name: string; - }; - } - | { - /** @enum {string} */ - kind: 'account_notice_sms'; - /** @enum {string} */ - notice: - | 'account_recovery_opened' - | 'account_recovery_completed' - | 'recovery_code_used' - | 'identity_changed' - | 'application_notice'; - to: string; - text: string; - cancelUrl?: string; - application?: { - clientId: string; - name: string; - }; - }; - }; - }; - }; /** @description HTTP 400 */ 400: { headers: { @@ -16118,6 +16032,7 @@ export interface paths { * @example { * "error": null, * "message": "string", + * "sameDevice": true, * "requestedFrom": { * "deviceClass": null, * "requestedAt": "string" @@ -16128,6 +16043,7 @@ export interface paths { /** @enum {string} */ error: 'confirmation_required'; message: string; + sameDevice: boolean; requestedFrom: { /** @enum {string} */ deviceClass: @@ -16200,8 +16116,8 @@ export interface paths { get?: never; put?: never; /** - * Confirm a magic link opened on another device - * @description Consumes the link after the person who opened it has approved signing in the device that requested it. + * Confirm a magic link + * @description Consumes the link, signing in the device that requested it. Takes the `code` the link carries in its fragment (`#code=`), which never appears in a query string or a Referer. A wrong code spends the link. */ post: { parameters: { @@ -16212,7 +16128,13 @@ export interface paths { }; cookie?: never; }; - requestBody?: never; + requestBody?: { + content: { + 'application/json': { + code: string; + }; + }; + }; responses: { /** @description HTTP 200 */ 200: { diff --git a/src/migrations/20261120120000-add-magic-link-code.cjs b/src/migrations/20261120120000-add-magic-link-code.cjs new file mode 100644 index 00000000..caf68547 --- /dev/null +++ b/src/migrations/20261120120000-add-magic-link-code.cjs @@ -0,0 +1,27 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * The hash of the code a magic link carries in its fragment (#594). A link without one + * was issued before the code existed and can no longer be confirmed. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + ALTER TABLE public.magic_link_tokens ADD COLUMN IF NOT EXISTS code_hash TEXT; + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + ALTER TABLE public.magic_link_tokens DROP COLUMN IF EXISTS code_hash; + `); + }, +}; diff --git a/src/models/magicLinks.ts b/src/models/magicLinks.ts index 8df558ea..5070e696 100644 --- a/src/models/magicLinks.ts +++ b/src/models/magicLinks.ts @@ -20,6 +20,7 @@ export class MagicLinkToken extends Model< declare id: CreationOptional; declare user_id: string; declare token_hash: string; + declare code_hash: string | null; declare redirect_url: string | null; declare ip_hash: string | null; declare user_agent_hash: string | null; @@ -55,6 +56,10 @@ const initializeMagicTokenModel = (sequelize: Sequelize) => { allowNull: false, unique: true, }, + code_hash: { + type: DataTypes.TEXT, + allowNull: true, + }, redirect_url: { type: DataTypes.TEXT, allowNull: true, diff --git a/src/routes/magicLink.routes.ts b/src/routes/magicLink.routes.ts index 5e37ea78..37508513 100644 --- a/src/routes/magicLink.routes.ts +++ b/src/routes/magicLink.routes.ts @@ -15,6 +15,7 @@ import { createRouter } from '../lib/createRouter.js'; import { magicLinkEmailLimiter, magicLinkIpLimiter } from '../middleware/rateLimit.js'; import { ErrorSchema, InternalErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; import { + MagicLinkConfirmBodySchema, MagicLinkRequestQuerySchema, MagicLinkVerifyParamsSchema, } from '../schemas/magiclink.requests.js'; @@ -103,18 +104,17 @@ magicLinkRouter.get( adapter: {}, summary: 'Verify magic link token', description: - 'Consumes the link when it is opened on the device that requested it, proven by the ' + - "requesting attempt's ephemeral bearer token when the adapter forwards it, otherwise by " + - 'the IP address and user agent a trusted adapter forwards. Opened anywhere else, answers ' + - '409 without consuming it; ' + - 'confirm with POST /magic-link/verify/{token}/confirm.', + 'Describes the link without consuming it, always answering 409 confirmation_required. ' + + '`sameDevice` is true when it was opened by the attempt that requested it, proven by ' + + "that attempt's ephemeral bearer token when the adapter forwards it, otherwise by the " + + 'IP address and user agent a trusted adapter forwards. Consume it with ' + + 'POST /magic-link/verify/{token}/confirm and the code from the link fragment.', tags: ['MagicLinks'], schemas: { params: MagicLinkVerifyParamsSchema, response: { - 200: MessageSchema, 403: ErrorSchema, 400: ErrorSchema, 409: MagicLinkConfirmationRequiredSchema, @@ -129,14 +129,16 @@ magicLinkRouter.post( '/verify/:token/confirm', { adapter: {}, - summary: 'Confirm a magic link opened on another device', + summary: 'Confirm a magic link', description: - 'Consumes the link after the person who opened it has approved signing in the device ' + - 'that requested it.', + 'Consumes the link, signing in the device that requested it. Takes the `code` the link ' + + 'carries in its fragment (`#code=`), which never appears in a query string or a ' + + 'Referer. A wrong code spends the link.', tags: ['MagicLinks'], schemas: { params: MagicLinkVerifyParamsSchema, + body: MagicLinkConfirmBodySchema, response: { 200: MessageSchema, diff --git a/src/schemas/magiclink.requests.ts b/src/schemas/magiclink.requests.ts index d1eb2e1c..d43f93dc 100644 --- a/src/schemas/magiclink.requests.ts +++ b/src/schemas/magiclink.requests.ts @@ -15,9 +15,18 @@ export { MagicLinkVerifyParamsSchema } from '@seamless-auth/types'; */ export const MagicLinkRequestQuerySchema = z.object({ /** - * Where the link should land. Validated against the configured origins, so this cannot - * be used to point a link on the tenant's domain at somewhere else. Omit it to keep the - * tenant-wide destination. + * Where the link should land. Must match an entry of `magic_link_redirect_uris` exactly, + * or, when that is empty, the `/verify-magiclink` page on a configured origin. Omit it to + * keep the tenant-wide destination. */ redirectUri: z.url().optional(), }); + +/** + * The `code` is the value the link carries in its fragment (`#code=`). The query string + * holds only the token, so a URL that leaks through a Referer or a log is not enough to + * confirm the link. + */ +export const MagicLinkConfirmBodySchema = z.object({ + code: z.string().min(1).max(256), +}); diff --git a/src/schemas/magiclink.responses.ts b/src/schemas/magiclink.responses.ts index f6de2232..0429dfe2 100644 --- a/src/schemas/magiclink.responses.ts +++ b/src/schemas/magiclink.responses.ts @@ -22,12 +22,14 @@ export const MagicLinkPollResponseSchema = z.union([ ]); /** - * A link opened on a device other than the one that asked for it. The link is still - * unused; confirming it from this device signs the requesting device in. + * Every open of a link answers this, and the link stays unused until it is confirmed + * with the code from its fragment. `sameDevice` says whether it was opened by the + * attempt that requested it, so a client can confirm without asking when it was. */ export const MagicLinkConfirmationRequiredSchema = z.object({ error: z.literal('confirmation_required'), message: z.string(), + sameDevice: z.boolean(), requestedFrom: z.object({ deviceClass: z.enum(DEVICE_CLASSES), requestedAt: z.string(), diff --git a/src/services/magicLinkRedirect.ts b/src/services/magicLinkRedirect.ts index eb98e8e4..0f99bfb3 100644 --- a/src/services/magicLinkRedirect.ts +++ b/src/services/magicLinkRedirect.ts @@ -14,40 +14,57 @@ export class MagicLinkRedirectNotAllowedError extends Error { } } -const DEFAULT_VERIFY_PATH = '/verify-magiclink'; +export const DEFAULT_VERIFY_PATH = '/verify-magiclink'; + +function defaultLandingPages(origins: string[], frontendUrl?: string) { + return [...new Set([frontendUrl, ...origins])] + .filter((origin): origin is string => Boolean(origin)) + .map((origin) => `${origin.replace(/\/+$/, '')}${DEFAULT_VERIFY_PATH}`); +} /** * Builds the link a magic link email points at. * - * Without a requested target this stays on the tenant-wide value it always used, so an - * instance that asks for nothing sees no change. A caller that does ask is validated the - * same way OAuth validates its redirect URI, against the configured origins, which is - * what lets a tenant's web and mobile clients each receive a link that lands in the right - * place rather than sharing one destination. + * The token rides in the query and the code in the fragment. A fragment is never sent to + * a server, never appears in a Referer, and is left out of most analytics, so a landing + * page that leaks its query string leaks a lookup handle that cannot sign anyone in. + * + * Without a requested target this stays on the tenant-wide value it always used. A caller + * that does ask is held to `magic_link_redirect_uris` when set, and otherwise to the + * verify page on a configured origin. Matching on origin alone let a link land on any + * page of the tenant's site, including one that forwards its URL somewhere else. */ -export async function resolveMagicLinkUrl(token: string, requestedRedirectUri?: string) { +export async function resolveMagicLinkUrl( + token: string, + code: string, + requestedRedirectUri?: string, +) { const config = await getSystemConfig(); + const frontendUrl = config.frontend_url ?? config.origins[0]; + + let url: URL; if (!requestedRedirectUri) { - const frontendUrl = config.frontend_url ?? config.origins[0]; - return `${frontendUrl}${DEFAULT_VERIFY_PATH}?token=${token}`; - } + url = new URL(`${frontendUrl}${DEFAULT_VERIFY_PATH}`); + } else { + // Exact match in both cases. `magic_link_redirect_uris` exists for targets whose + // origin cannot be compared, such as `myapp://auth` or a universal link on a host + // that should not also be a WebAuthn origin. + const configured = config.magic_link_redirect_uris ?? []; + const allowed = + configured.length > 0 ? configured : defaultLandingPages(config.origins, config.frontend_url); + + if (!allowedRedirect(requestedRedirectUri, allowed, [])) { + throw new MagicLinkRedirectNotAllowedError(); + } - // `magic_link_redirect_uris` is matched exactly when set, because it exists for - // targets whose origin cannot be compared: a custom application scheme such as - // `myapp://auth`, or a universal link on a host that should not also be a WebAuthn - // origin. Empty by default, and an empty list falls back to comparing against - // `origins`, so a deployment that sets nothing is unaffected. - if ( - !allowedRedirect(requestedRedirectUri, config.magic_link_redirect_uris ?? [], config.origins) - ) { - throw new MagicLinkRedirectNotAllowedError(); + url = new URL(requestedRedirectUri); } - // Set rather than appended: a caller is free to carry its own query, and a second - // `token=` would leave which one wins up to whoever parses it. - const url = new URL(requestedRedirectUri); + // Set rather than appended: a second `token=` would leave which one wins up to whoever + // parses it. Any fragment the target carried is replaced for the same reason. url.searchParams.set('token', token); + url.hash = new URLSearchParams({ code }).toString(); return url.toString(); } diff --git a/tests/integration/magicLink/magicLink.spec.ts b/tests/integration/magicLink/magicLink.spec.ts index e6386436..1ff70081 100644 --- a/tests/integration/magicLink/magicLink.spec.ts +++ b/tests/integration/magicLink/magicLink.spec.ts @@ -24,17 +24,20 @@ import { import { AuthEventService } from '../../../src/services/authEventService.js'; import { verifyJwtWithKid } from '../../../src/services/sessionService.js'; import { sendMagicLinkEmail } from '../../../src/services/messagingService.js'; -import { hashDeviceFingerprint } from '../../../src/utils/utils.js'; +import { hashDeviceFingerprint, hashSha256 } from '../../../src/utils/utils.js'; import { LoginHook } from '../../../src/models/loginHooks.js'; import { buildLoginHook, startHookServer } from '../../factories/loginHookFactory.js'; let app: Application; +const CODE = 'fragment-code'; + function buildMagicLink(overrides: any = {}) { return { id: 'link-1', user_id: 'user-1', token_hash: 'hash', + code_hash: hashSha256(CODE), used_at: null, expires_at: new Date(Date.now() + 100000), ip_hash: 'ip', @@ -183,21 +186,52 @@ describe('GET /magic-link', () => { ); }); - it('sends the link to a requested target whose origin is configured', async () => { + it('sends the link to the verify page on a configured origin', async () => { (MagicLinkToken.update as any).mockResolvedValue([1]); (MagicLinkToken.create as any).mockResolvedValue({ id: 'link-1' }); const res = await request(app) .get('/magic-link') - .query({ redirectUri: 'http://localhost:5174/app/magic' }) + .query({ redirectUri: 'http://localhost:5174/verify-magiclink' }) .set('x-seamless-auth-delivery-mode', 'external') .set('x-seamless-service-token', await mintInternalServiceToken()); expect(res.status).toBe(200); - expect(res.body.delivery.magicLinkUrl).toContain('http://localhost:5174/app/magic?token='); + expect(res.body.delivery.magicLinkUrl).toContain( + 'http://localhost:5174/verify-magiclink?token=', + ); expect(res.body.delivery.magicLinkUrl).toContain(res.body.delivery.token); }); + it('refuses another path on a configured origin when no allowlist is set', async () => { + const res = await request(app) + .get('/magic-link') + .query({ redirectUri: 'http://localhost:5174/app/magic' }); + + expect(res.status).toBe(400); + expect(MagicLinkToken.create).not.toHaveBeenCalled(); + }); + + it('stores only hashes of the token and the fragment code it mails', async () => { + (MagicLinkToken.update as any).mockResolvedValue([1]); + (MagicLinkToken.create as any).mockResolvedValue({ id: 'link-1' }); + + const res = await request(app) + .post('/magic-link') + .set('x-seamless-auth-delivery-mode', 'external') + .set('x-seamless-service-token', await mintInternalServiceToken()); + + const url = new URL(res.body.delivery.magicLinkUrl); + const code = new URLSearchParams(url.hash.slice(1)).get('code'); + const created = (MagicLinkToken.create as any).mock.calls[0][0]; + + expect(code).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(url.searchParams.has('code')).toBe(false); + expect(created.code_hash).toBe(hashSha256(code!)); + expect(created.token_hash).toBe(hashSha256(res.body.delivery.token)); + expect(created.redirect_url).not.toContain('#'); + }); + it('refuses a requested target outside the configured origins', async () => { (MagicLinkToken.update as any).mockResolvedValue([1]); (MagicLinkToken.create as any).mockResolvedValue({ id: 'link-1' }); @@ -339,29 +373,26 @@ describe('GET /magic-link/verify/:token', () => { expect(res.status).toBe(400); }); - it('accepts a valid token opened by the requesting attempt', async () => { + // The token is all the query string carries, and a query string is what leaks. So a + // verify never consumes, not even for the attempt that asked: that attempt belongs to + // whoever requested the link, who need not be the person reading the email. + it('does not consume a link opened by the requesting attempt, and says so', async () => { (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); - (MagicLinkToken.update as any).mockResolvedValue([1]); (verifyJwtWithKid as any).mockResolvedValue({ jti: 'attempt-1' }); const res = await request(app) .get('/magic-link/verify/token') .set('Authorization', 'Bearer pre-auth'); - expect(res.status).toBe(200); - expect(verifyJwtWithKid).toHaveBeenCalledWith('pre-auth', 'ephemeral'); - expect(AuthEventService.log).toHaveBeenCalledWith( - expect.objectContaining({ - type: 'magic_link_success', - metadata: { reason: 'Magic link token consumed', confirmation: 'same_device' }, - }), + expect(res.status).toBe(409); + expect(res.body).toEqual( + expect.objectContaining({ error: 'confirmation_required', sameDevice: true }), ); + expect(verifyJwtWithKid).toHaveBeenCalledWith('pre-auth', 'ephemeral'); + expect(MagicLinkToken.update).not.toHaveBeenCalled(); }); it('asks for confirmation when opened on another device, without consuming the link', async () => { - // Anyone can request a link for someone else's address from their own machine, and - // the session goes to the requesting device. So a link opened anywhere else must - // not complete without the person who opened it approving. (MagicLinkToken.findOne as any).mockResolvedValue( buildMagicLink({ ip_hash: 'a-different-device', user_agent_hash: 'another-ua' }), ); @@ -372,15 +403,20 @@ describe('GET /magic-link/verify/:token', () => { expect(res.body).toEqual({ error: 'confirmation_required', message: expect.any(String), + sameDevice: false, requestedFrom: { deviceClass: 'macos', requestedAt: '2026-10-16T12:00:00.000Z' }, }); expect(MagicLinkToken.update).not.toHaveBeenCalled(); expect(AuthEventService.log).toHaveBeenCalledWith( - expect.objectContaining({ userId: 'user-1', type: 'magic_link_confirmation_required' }), + expect.objectContaining({ + userId: 'user-1', + type: 'magic_link_confirmation_required', + metadata: { sameDevice: false }, + }), ); }); - it('asks for confirmation when the bearer belongs to another attempt, even on a matching fingerprint', async () => { + it('reports another device when the bearer belongs to another attempt, even on a matching fingerprint', async () => { // hashDeviceFingerprint is mocked to the hashes buildMagicLink uses, so this link // matches the request's fingerprint. (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); @@ -393,14 +429,12 @@ describe('GET /magic-link/verify/:token', () => { ); expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ sameDevice: false })); expect(MagicLinkToken.update).not.toHaveBeenCalled(); }); it('falls back to the IP and user agent when no valid bearer is forwarded', async () => { - // hashDeviceFingerprint is mocked to the hashes buildMagicLink uses, so this link - // matches the request's fingerprint. (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); - (MagicLinkToken.update as any).mockResolvedValue([1]); (verifyJwtWithKid as any).mockResolvedValue(null); const res = directRes(); @@ -409,8 +443,9 @@ describe('GET /magic-link/verify/:token', () => { res, ); - expect(res.status).toHaveBeenCalledWith(200); - expect(MagicLinkToken.update).toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ sameDevice: true })); + expect(MagicLinkToken.update).not.toHaveBeenCalled(); }); it('treats a bearer that fails to verify like no bearer at all', async () => { @@ -426,12 +461,12 @@ describe('GET /magic-link/verify/:token', () => { ); expect(res.status).toHaveBeenCalledWith(409); - expect(MagicLinkToken.update).not.toHaveBeenCalled(); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ sameDevice: false })); }); // Behind an adapter that does not forward the client context, every request carries // the adapter's own address and user agent, so a matching fingerprint proves nothing. - it('asks for confirmation on a matching fingerprint no adapter vouched for', async () => { + it('reports another device on a matching fingerprint no adapter vouched for', async () => { (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); const res = directRes(); @@ -441,7 +476,7 @@ describe('GET /magic-link/verify/:token', () => { ); expect(res.status).toHaveBeenCalledWith(409); - expect(MagicLinkToken.update).not.toHaveBeenCalled(); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ sameDevice: false })); }); it('refuses a link created before attempt binding', async () => { @@ -476,35 +511,16 @@ describe('GET /magic-link/verify/:token', () => { expect(res.body.error).toBe('login_method_disabled'); expect(MagicLinkToken.findOne).not.toHaveBeenCalled(); }); - - it('returns 500 when the token cannot be atomically consumed', async () => { - (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); - (MagicLinkToken.update as any).mockResolvedValue([0]); - (verifyJwtWithKid as any).mockResolvedValue({ jti: 'attempt-1' }); - - const res = await request(app) - .get('/magic-link/verify/token') - .set('Authorization', 'Bearer pre-auth'); - - expect(res.status).toBe(500); - expect(res.body.error).toBe('Failed to use token'); - expect(AuthEventService.log).toHaveBeenCalledWith( - expect.objectContaining({ - type: 'magic_link_failed', - metadata: { reason: 'Failed to consume token' }, - }), - ); - }); }); describe('POST /magic-link/verify/:token/confirm', () => { - it('consumes a link opened on another device once the person approves', async () => { + it('consumes a link opened on another device once the person approves with its code', async () => { (MagicLinkToken.findOne as any).mockResolvedValue( buildMagicLink({ ip_hash: 'a-different-device', user_agent_hash: 'another-ua' }), ); (MagicLinkToken.update as any).mockResolvedValue([1]); - const res = await request(app).post('/magic-link/verify/token/confirm'); + const res = await request(app).post('/magic-link/verify/token/confirm').send({ code: CODE }); expect(res.status).toBe(200); expect(res.body).toEqual({ message: 'Success' }); @@ -520,10 +536,86 @@ describe('POST /magic-link/verify/:token/confirm', () => { ); }); + it('records a same-device confirmation as such', async () => { + (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); + (MagicLinkToken.update as any).mockResolvedValue([1]); + (verifyJwtWithKid as any).mockResolvedValue({ jti: 'attempt-1' }); + + const res = await request(app) + .post('/magic-link/verify/token/confirm') + .set('Authorization', 'Bearer pre-auth') + .send({ code: CODE }); + + expect(res.status).toBe(200); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'magic_link_success', + metadata: { reason: 'Magic link token consumed', confirmation: 'same_device' }, + }), + ); + }); + + // What a leaked query string hands an attacker: the token, and the requesting attempt + // when they asked for the link themselves. Neither is enough without the code. + it('refuses the requesting attempt that has the token but not the code', async () => { + (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); + (MagicLinkToken.update as any).mockResolvedValue([1]); + (verifyJwtWithKid as any).mockResolvedValue({ jti: 'attempt-1' }); + + const res = await request(app) + .post('/magic-link/verify/token/confirm') + .set('Authorization', 'Bearer pre-auth') + .send({ code: 'guessed' }); + + expect(res.status).toBe(400); + expect(MagicLinkToken.update).not.toHaveBeenCalledWith( + { used_at: expect.any(Date) }, + expect.anything(), + ); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'magic_link_failed', + metadata: { reason: 'Invalid confirmation code' }, + }), + ); + }); + + it('spends the link after a wrong code, so it cannot be guessed at', async () => { + (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); + (MagicLinkToken.update as any).mockResolvedValue([1]); + + await request(app).post('/magic-link/verify/token/confirm').send({ code: 'wrong' }); + + expect(MagicLinkToken.update).toHaveBeenCalledWith( + { expires_at: expect.any(Date) }, + { where: { id: 'link-1', used_at: null } }, + ); + }); + + it('refuses a confirm with no code before it reaches the link', async () => { + const res = await request(app).post('/magic-link/verify/token/confirm').send({}); + + expect(res.status).toBe(400); + expect(MagicLinkToken.findOne).not.toHaveBeenCalled(); + }); + + it('refuses a link mailed before codes existed', async () => { + (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink({ code_hash: null })); + (MagicLinkToken.update as any).mockResolvedValue([1]); + + const res = await request(app).post('/magic-link/verify/token/confirm').send({ code: CODE }); + + expect(res.status).toBe(400); + expect(MagicLinkToken.update).not.toHaveBeenCalledWith( + { used_at: expect.any(Date) }, + expect.anything(), + ); + }); + it('refuses a link that is already used', async () => { (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink({ used_at: new Date() })); - const res = await request(app).post('/magic-link/verify/token/confirm'); + const res = await request(app).post('/magic-link/verify/token/confirm').send({ code: CODE }); expect(res.status).toBe(400); expect(MagicLinkToken.update).not.toHaveBeenCalled(); @@ -534,7 +626,7 @@ describe('POST /magic-link/verify/:token/confirm', () => { buildMagicLink({ expires_at: new Date(Date.now() - 1000) }), ); - const res = await request(app).post('/magic-link/verify/token/confirm'); + const res = await request(app).post('/magic-link/verify/token/confirm').send({ code: CODE }); expect(res.status).toBe(400); }); @@ -542,10 +634,26 @@ describe('POST /magic-link/verify/:token/confirm', () => { it('rejects a missing token (direct invocation)', async () => { const res = directRes(); - await confirmMagicLink({ params: {} } as any, res); + await confirmMagicLink({ params: {}, body: { code: CODE } } as any, res); expect(res.status).toHaveBeenCalledWith(400); }); + + it('returns 500 when the link cannot be atomically consumed', async () => { + (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink()); + (MagicLinkToken.update as any).mockResolvedValue([0]); + + const res = await request(app).post('/magic-link/verify/token/confirm').send({ code: CODE }); + + expect(res.status).toBe(500); + expect(res.body.error).toBe('Failed to use token'); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'magic_link_failed', + metadata: { reason: 'Failed to consume token' }, + }), + ); + }); }); describe('GET /magic-link/check', () => { @@ -934,14 +1042,20 @@ describe('magic link full sign-in sequence (regression)', () => { const pendingPoll = await request(app).get('/magic-link/check'); expect(pendingPoll.status).toBe(204); - // 3) Verify the token (marks it used) + // 3) Open the link, then confirm it with the code from its fragment (marks it used) (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink({ used_at: null })); (MagicLinkToken.update as any).mockResolvedValue([1]); (verifyJwtWithKid as any).mockResolvedValue({ jti: 'attempt-1' }); const verifyRes = await request(app) .get('/magic-link/verify/token') .set('Authorization', 'Bearer pre-auth'); - expect(verifyRes.status).toBe(200); + expect(verifyRes.status).toBe(409); + expect(verifyRes.body.sameDevice).toBe(true); + const confirmRes = await request(app) + .post('/magic-link/verify/token/confirm') + .set('Authorization', 'Bearer pre-auth') + .send({ code: CODE }); + expect(confirmRes.status).toBe(200); // 4) Poll after verification -> session issued (MagicLinkToken.findOne as any).mockResolvedValue(buildMagicLink({ used_at: new Date() })); diff --git a/tests/unit/services/magicLinkRedirect.spec.ts b/tests/unit/services/magicLinkRedirect.spec.ts index 158b2ebc..62c5e4fd 100644 --- a/tests/unit/services/magicLinkRedirect.spec.ts +++ b/tests/unit/services/magicLinkRedirect.spec.ts @@ -20,9 +20,9 @@ beforeEach(() => { describe('resolveMagicLinkUrl', () => { describe('with no requested target', () => { - it('keeps the tenant-wide destination', async () => { - expect(await resolveMagicLinkUrl('tok')).toBe( - 'http://localhost:5174/verify-magiclink?token=tok', + it('keeps the tenant-wide destination, with the code in the fragment', async () => { + expect(await resolveMagicLinkUrl('tok', 'cod')).toBe( + 'http://localhost:5174/verify-magiclink?token=tok#code=cod', ); }); @@ -32,90 +32,144 @@ describe('resolveMagicLinkUrl', () => { frontend_url: 'http://localhost:5001', }); - expect(await resolveMagicLinkUrl('tok')).toBe( - 'http://localhost:5001/verify-magiclink?token=tok', + expect(await resolveMagicLinkUrl('tok', 'cod')).toBe( + 'http://localhost:5001/verify-magiclink?token=tok#code=cod', ); }); - }); - describe('with a requested target', () => { - it('honours one whose origin is configured', async () => { - const url = await resolveMagicLinkUrl('tok', 'http://localhost:5174/mobile/finish'); + it('never puts the code in the query string', async () => { + const url = new URL(await resolveMagicLinkUrl('tok', 'cod')); - expect(url).toBe('http://localhost:5174/mobile/finish?token=tok'); + expect(url.searchParams.has('code')).toBe(false); + expect(url.search).not.toContain('cod'); }); + }); - it('lets web and mobile clients reach different paths on one tenant', async () => { - const web = await resolveMagicLinkUrl('tok', 'http://localhost:5174/verify-magiclink'); - const mobile = await resolveMagicLinkUrl('tok', 'http://localhost:5174/app/magic'); - - expect(web).not.toBe(mobile); - expect(mobile).toContain('/app/magic'); + // With no allowlist, the only target is the verify page the SDKs and adapters land on. + // Matching on origin alone let a link land on any page of the site, including one that + // forwards its URL to a third party. + describe('with an empty magic_link_redirect_uris', () => { + it('honours the verify page on a configured origin', async () => { + expect( + await resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/verify-magiclink'), + ).toBe('http://localhost:5174/verify-magiclink?token=tok#code=cod'); }); - it('keeps a query the caller already put on the target', async () => { - const url = await resolveMagicLinkUrl('tok', 'http://localhost:5174/finish?platform=ios'); + it('honours the verify page on any configured origin and on frontend_url', async () => { + configure({ + origins: ['http://localhost:5174', 'https://app.example'], + frontend_url: 'https://www.example/', + }); - expect(url).toContain('platform=ios'); - expect(url).toContain('token=tok'); + await expect( + resolveMagicLinkUrl('tok', 'cod', 'https://app.example/verify-magiclink'), + ).resolves.toContain('https://app.example/verify-magiclink?token=tok'); + await expect( + resolveMagicLinkUrl('tok', 'cod', 'https://www.example/verify-magiclink'), + ).resolves.toContain('https://www.example/verify-magiclink?token=tok'); }); - // Otherwise a caller could decide which token the client reads. - it('replaces a token the caller supplied rather than appending a second', async () => { - const url = await resolveMagicLinkUrl('real', 'http://localhost:5174/finish?token=attacker'); + it('refuses another path on a configured origin', async () => { + await expect( + resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/mobile/finish'), + ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); + }); - expect(url).toBe('http://localhost:5174/finish?token=real'); + it('refuses the verify page carrying a query of its own', async () => { + await expect( + resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/verify-magiclink?next=/x'), + ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); + }); + + it('refuses a path that merely starts with the verify page', async () => { + await expect( + resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/verify-magiclink/../open'), + ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); }); it('refuses an origin that is not configured', async () => { - await expect(resolveMagicLinkUrl('tok', 'https://evil.example/steal')).rejects.toBeInstanceOf( - MagicLinkRedirectNotAllowedError, - ); + await expect( + resolveMagicLinkUrl('tok', 'cod', 'https://evil.example/verify-magiclink'), + ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); }); - // A near-miss host is the whole point of matching on origin rather than prefix. it('refuses a host that merely starts with a configured one', async () => { await expect( - resolveMagicLinkUrl('tok', 'http://localhost:5174.evil.example/steal'), + resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174.evil.example/verify-magiclink'), ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); }); it('refuses a different port on a configured host', async () => { - await expect(resolveMagicLinkUrl('tok', 'http://localhost:9999/x')).rejects.toBeInstanceOf( - MagicLinkRedirectNotAllowedError, - ); + await expect( + resolveMagicLinkUrl('tok', 'cod', 'http://localhost:9999/verify-magiclink'), + ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); }); it('refuses a value that is not a URL', async () => { - await expect(resolveMagicLinkUrl('tok', 'not-a-url')).rejects.toBeInstanceOf( + await expect(resolveMagicLinkUrl('tok', 'cod', 'not-a-url')).rejects.toBeInstanceOf( MagicLinkRedirectNotAllowedError, ); }); }); - // The key exists for targets whose origin cannot be compared, which is why the match - // is exact. An empty list is the default and has to keep behaving as it did. describe('with magic_link_redirect_uris configured', () => { it('allows a custom scheme that is listed exactly', async () => { configure({ magic_link_redirect_uris: ['myapp://auth'] }); - expect(await resolveMagicLinkUrl('tok', 'myapp://auth')).toBe('myapp://auth?token=tok'); + expect(await resolveMagicLinkUrl('tok', 'cod', 'myapp://auth')).toBe( + 'myapp://auth?token=tok#code=cod', + ); }); - it('refuses a target that is not on the list, even on a configured origin', async () => { - configure({ magic_link_redirect_uris: ['myapp://auth'] }); + it('lets web and mobile clients reach different listed targets', async () => { + configure({ + magic_link_redirect_uris: [ + 'http://localhost:5174/verify-magiclink', + 'http://localhost:5174/app/magic', + ], + }); - await expect( - resolveMagicLinkUrl('tok', 'http://localhost:5174/finish'), - ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); + const web = await resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/verify-magiclink'); + const mobile = await resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/app/magic'); + + expect(web).not.toBe(mobile); + expect(mobile).toContain('/app/magic'); + }); + + it('keeps a query a listed target carries', async () => { + configure({ magic_link_redirect_uris: ['http://localhost:5174/finish?platform=ios'] }); + + const url = await resolveMagicLinkUrl( + 'tok', + 'cod', + 'http://localhost:5174/finish?platform=ios', + ); + + expect(url).toContain('platform=ios'); + expect(url).toContain('token=tok'); }); - it('falls back to the configured origins when the list is empty', async () => { - configure({ magic_link_redirect_uris: [] }); + // Otherwise a caller could decide which token or code the client reads. + it('replaces a token and fragment the target supplied rather than adding a second', async () => { + configure({ + magic_link_redirect_uris: ['http://localhost:5174/finish?token=attacker#code=attacker'], + }); - expect(await resolveMagicLinkUrl('tok', 'http://localhost:5174/finish')).toBe( - 'http://localhost:5174/finish?token=tok', + const url = await resolveMagicLinkUrl( + 'real', + 'cod', + 'http://localhost:5174/finish?token=attacker#code=attacker', ); + + expect(url).toBe('http://localhost:5174/finish?token=real#code=cod'); + }); + + it('refuses a target that is not on the list, even the default verify page', async () => { + configure({ magic_link_redirect_uris: ['myapp://auth'] }); + + await expect( + resolveMagicLinkUrl('tok', 'cod', 'http://localhost:5174/verify-magiclink'), + ).rejects.toBeInstanceOf(MagicLinkRedirectNotAllowedError); }); }); });