Files
outline/plugins/passkeys/server/auth/passkeys.ts
T
Tom MoorandClaude Opus 5.5 00b124d03c chore: Rename APIContext to Context and flatten its fields (#14684)
* chore: Rename APIContext to Context and flatten its fields

Auth and transaction now live directly on the context instead of in
ctx.state and a nested ctx.context, and model helpers read them directly.
APIContext remains as a deprecated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove deprecated APIContext alias

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* fix: Read auth from context in OAuth provider callbacks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Add withUser and withTransaction context helpers

Replaces manual createContext rebuilds that copy fields from an existing context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove arbitrary property access from Koa context types

AppContext and Context no longer inherit the any index signature from
Koa's DefaultContext, custom fields are declared explicitly, and importing
Koa's loose Context type is disallowed by lint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-23 23:17:06 -05:00

383 lines
12 KiB
TypeScript

import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
} from "@simplewebauthn/server";
import { isoBase64URL } from "@simplewebauthn/server/helpers";
import type { AuthenticatorTransportFuture } from "@simplewebauthn/server";
import Router from "@koa/router";
import { randomBytes } from "node:crypto";
import { toError } from "@shared/utils/error";
import { User, UserPasskey, Team } from "@server/models";
import auth from "@server/middlewares/authentication";
import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate";
import env from "@server/env";
import { AuthorizationError, ValidationError } from "@server/errors";
import type { Context } from "@server/types";
import { AuthenticationType } from "@server/types";
import Logger from "@server/logging/Logger";
import Redis from "@server/storage/redis";
import { signIn } from "@server/utils/authentication";
import { generatePasskeyName, PasskeyBrand } from "@shared/utils/passkeys";
import * as T from "./schema";
import { Client } from "@shared/types";
import { Minute } from "@shared/utils/time";
import { authorize } from "@server/policies";
const router = new Router();
const rpName = env.APP_NAME;
const CHALLENGE_EXPIRY_MS = Minute.ms * 5;
// Helper to get RP ID (domain) - for simplicity, we can use the hostname but strip port.
const getRpID = (ctx: Context) => ctx.request.hostname;
/**
* Helper to get the expected origin for WebAuthn.
* Properly handles non-standard ports by checking X-Forwarded-Port header.
*
* @param ctx - the context.
* @returns the expected origin (protocol://host:port).
*/
export const getExpectedOrigin = (ctx: Context): string => {
const protocol = ctx.protocol;
const hostname = ctx.request.hostname;
// When behind a proxy with app.proxy = true, Koa uses X-Forwarded-Host
// which typically doesn't include the port. We need to check X-Forwarded-Port.
const forwardedPort = ctx.request.get("X-Forwarded-Port");
// ctx.request.host includes port if present (e.g., "example.com:3000")
// ctx.request.hostname excludes port (e.g., "example.com")
const hostWithPort = ctx.request.host;
// Determine if we need to add a port to the origin
let origin = `${protocol}://${hostname}`;
// Check if X-Forwarded-Port exists (when behind a proxy)
if (forwardedPort) {
const port = parseInt(forwardedPort, 10);
// Only add port if it's not the default for the protocol
if (
(protocol === "https" && port !== 443) ||
(protocol === "http" && port !== 80)
) {
origin = `${protocol}://${hostname}:${port}`;
}
} else if (hostWithPort !== hostname) {
// hostWithPort includes port, use it directly
origin = `${protocol}://${hostWithPort}`;
}
return origin;
};
/**
* Generate Redis key for registration challenge.
*
* @param userId - the user ID.
* @returns the Redis key.
*/
const getRegistrationChallengeKey = (userId: string): string =>
`passkey:reg-challenge:${userId}`;
/**
* Generate Redis key for authentication challenge.
*
* @param challengeId - the challenge ID.
* @returns the Redis key.
*/
const getAuthenticationChallengeKey = (challengeId: string): string =>
`passkey:auth-challenge:${challengeId}`;
/**
* Returns true if a user may only register one passkey from the authenticator
* with the given AAGUID. The Chromium Touch ID authenticator, which is also used
* by the desktop app, reports the same AAGUID on every device, so it is excluded.
*
* @param aaguid - the authenticator AAGUID from the registration response.
* @returns true if a second passkey from the authenticator should be rejected.
*/
export const isUniqueAuthenticator = (aaguid: string | undefined): boolean =>
!!aaguid &&
aaguid !== "00000000-0000-0000-0000-000000000000" &&
aaguid !== PasskeyBrand.ChromiumBrowser;
router.post(
"passkeys.generateRegistrationOptions",
auth({ type: AuthenticationType.APP }),
async (ctx: Context) => {
const { user } = ctx.auth;
authorize(user, "createUserPasskey", user.team);
// Fetch existing passkeys to exclude them from registration
const existingPasskeys = await UserPasskey.findAll({
where: { userId: user.id },
});
const options = await generateRegistrationOptions({
rpName,
rpID: getRpID(ctx),
userID: isoBase64URL.toBuffer(user.id),
userName: user.email || user.name,
excludeCredentials: existingPasskeys.map((pk) => ({
id: pk.credentialId,
transports: pk.transports as AuthenticatorTransportFuture[],
})),
authenticatorSelection: {
residentKey: "preferred",
userVerification: "preferred",
},
});
// Save challenge to Redis with user ID as key
await Redis.defaultClient.set(
getRegistrationChallengeKey(user.id),
options.challenge,
"PX",
CHALLENGE_EXPIRY_MS
);
ctx.body = { data: options };
}
);
router.post(
"passkeys.verifyRegistration",
auth({ type: AuthenticationType.APP }),
validate(T.PasskeysVerifyRegistrationSchema),
transaction(),
async (ctx: Context<T.PasskeysVerifyRegistrationReq>) => {
const { user } = ctx.auth;
const body = ctx.input.body;
authorize(user, "createUserPasskey", user.team);
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getRegistrationChallengeKey(user.id)
);
if (!expectedChallenge) {
throw ValidationError(
"No registration challenge found or challenge expired"
);
}
let verification;
try {
verification = await verifyRegistrationResponse({
response: body,
expectedChallenge,
expectedOrigin: getExpectedOrigin(ctx),
expectedRPID: getRpID(ctx),
// Match the "preferred" policy in registration options; some
// authenticators legitimately skip user verification.
requireUserVerification: false,
});
} catch (error) {
const err = toError(error);
Logger.error("passkeys: Registration verification failed", err);
throw ValidationError(err.message);
}
const { verified, registrationInfo } = verification;
if (verified && registrationInfo) {
const { credential, aaguid } = registrationInfo;
// credential.id is already a Base64URL string
const credentialIdBase64 = credential.id;
const credentialPublicKey = credential.publicKey;
const counter = credential.counter;
// Capture user agent and generate friendly name
const userAgent = ctx.request.get("user-agent");
const transports = body.response.transports || [];
// Check if already exists by credential ID
const existing = await UserPasskey.findOne({
where: { credentialId: credentialIdBase64 },
});
if (existing) {
if (existing.userId !== user.id) {
throw ValidationError("Passkey already registered to another user");
}
await existing.updateWithCtx(ctx, {
credentialPublicKey: Buffer.from(credentialPublicKey),
counter,
userAgent,
aaguid,
});
} else {
// Check if user already has a passkey from the same authenticator
if (isUniqueAuthenticator(aaguid)) {
const duplicateDevice = await UserPasskey.findOne({
where: { userId: user.id, aaguid },
});
if (duplicateDevice) {
throw ValidationError("You already have a passkey on this device");
}
}
await UserPasskey.createWithCtx(ctx, {
userId: user.id,
credentialId: credentialIdBase64,
credentialPublicKey: Buffer.from(credentialPublicKey),
counter,
transports,
name: generatePasskeyName(aaguid, userAgent, transports),
userAgent,
aaguid,
});
}
ctx.body = { data: { verified: true } };
} else {
throw ValidationError("Verification failed");
}
}
);
/**
* Resolves the login screen redirect for the desktop passkey entrypoint,
* normalizing an untrusted client query parameter to a known value.
*
* @param client - the raw client value from the request query.
* @returns the relative path to redirect the browser to.
*/
export const getPasskeyLoginRedirect = (
client: string | string[] | undefined
): string => {
const normalized = client === Client.Desktop ? Client.Desktop : Client.Web;
return `/?method=passkey&client=${normalized}`;
};
/**
* Entry point for passkey login from the desktop app. The WebAuthn ceremony
* cannot run inside Electron's Chromium, so the desktop client opens this URL
* in the system browser. We forward to the login screen, which auto-starts the
* ceremony and returns the authenticated session via the outline:// deep link,
* mirroring the existing SSO desktop flow.
*/
router.get("passkey", (ctx: Context) => {
ctx.redirect(getPasskeyLoginRedirect(ctx.query.client));
});
router.post(
"passkeys.generateAuthenticationOptions",
validate(T.PasskeysGenerateAuthenticationOptionsSchema),
async (ctx: Context<T.PasskeysGenerateAuthenticationOptionsReq>) => {
const options = await generateAuthenticationOptions({
rpID: getRpID(ctx),
userVerification: "preferred",
});
// Generate a unique challenge ID for this authentication attempt
const challengeId = randomBytes(32).toString("hex");
await Redis.defaultClient.set(
getAuthenticationChallengeKey(challengeId),
options.challenge,
"PX",
CHALLENGE_EXPIRY_MS
);
ctx.body = { data: { ...options, challengeId } };
}
);
router.post(
"passkeys.verifyAuthentication",
validate(T.PasskeysVerifyAuthenticationSchema),
async (ctx: Context<T.PasskeysVerifyAuthenticationReq>) => {
const body = ctx.input.body;
const { challengeId, client = Client.Web } = body;
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getAuthenticationChallengeKey(challengeId)
);
if (!expectedChallenge) {
throw ValidationError(
"No authentication challenge found or challenge expired"
);
}
const credentialId = body.id;
const passkey = await UserPasskey.findOne({
where: { credentialId },
include: [
{
model: User,
as: "user",
include: [{ model: Team, as: "team", required: true }],
},
],
});
if (!passkey) {
throw ValidationError(
"Passkey not found. It may have been removed or registered on a different account."
);
}
const user = passkey.user;
const team = user.team;
if (!team.passkeysEnabled) {
throw AuthorizationError(
"Passkey authentication is not enabled for this team"
);
}
let verification;
try {
verification = await verifyAuthenticationResponse({
response: body,
expectedChallenge,
expectedOrigin: getExpectedOrigin(ctx),
expectedRPID: getRpID(ctx),
credential: {
id: passkey.credentialId,
publicKey: new Uint8Array(passkey.credentialPublicKey),
counter: passkey.counter,
transports: passkey.transports as AuthenticatorTransportFuture[],
},
// Match the "preferred" policy in authentication options; some
// authenticators legitimately skip user verification.
requireUserVerification: false,
});
} catch (err) {
Logger.error(
"passkeys: Authentication verification failed",
toError(err)
);
throw ValidationError("Passkey authentication failed. Please try again.");
}
const { verified, authenticationInfo } = verification;
if (verified && authenticationInfo) {
passkey.counter = authenticationInfo.newCounter;
passkey.lastActiveAt = new Date();
await passkey.save({ silent: true });
// Use the signIn utility which handles all sign-in logic
await signIn(ctx, "passkeys", {
user,
team,
isNewUser: false,
isNewTeam: false,
client,
});
} else {
throw ValidationError("Verification failed");
}
}
);
export default router;