Files
outline/plugins/passkeys/server/auth/passkeys.ts
T
Tom MoorandClaude Opus 5.5 5647621224 chore: Prune redundant comments and type suppressions (#14124)
* chore: Prune redundant comments and normalize lint directives

Removes comments that restate the following line and stale TODOs, drops
the passive event listener feature check now that all supported browsers
support it, and renames eslint directives to oxlint.

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

* fix: Evaluate restricted team domains at validation time

The restricted email provider list was captured when the model loaded, so
it could not follow the hosting environment and the tests that covered it
never reached the model.

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

* chore: Replace type suppressions with accurate types

Adds a Concrete helper type for registries of abstract classes, declares
missing Sequelize and refractor typings, uses public ProseMirror APIs, a
typed mock context helper in middleware tests, and a StaticLink component
for sidebar rows being edited.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-17 17:07:39 -04:00

374 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 validate from "@server/middlewares/validate";
import env from "@server/env";
import { AuthorizationError, ValidationError } from "@server/errors";
import type { APIContext } 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 } 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: APIContext) => 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 API context.
* @returns the expected origin (protocol://host:port).
*/
export const getExpectedOrigin = (ctx: APIContext): 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}`;
router.post(
"passkeys.generateRegistrationOptions",
auth({ type: AuthenticationType.APP }),
async (ctx: APIContext) => {
const { user } = ctx.state.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),
async (ctx: APIContext<T.PasskeysVerifyRegistrationReq>) => {
const { user } = ctx.state.auth;
const body = ctx.input.body;
authorize(user, "createUserPasskey", user.team);
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
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;
const ZERO_AAGUID = "00000000-0000-0000-0000-000000000000";
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 (aaguid && aaguid !== ZERO_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,
});
}
// Delete challenge from Redis
await Redis.defaultClient.del(getRegistrationChallengeKey(user.id));
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: APIContext) => {
ctx.redirect(getPasskeyLoginRedirect(ctx.query.client));
});
router.post(
"passkeys.generateAuthenticationOptions",
validate(T.PasskeysGenerateAuthenticationOptionsSchema),
async (ctx: APIContext<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: APIContext<T.PasskeysVerifyAuthenticationReq>) => {
const body = ctx.input.body;
const { challengeId, client = Client.Web } = body;
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
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 });
// Delete challenge from Redis
await Redis.defaultClient.del(getAuthenticationChallengeKey(challengeId));
// 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;