Files
kai d1bf5196dd
release / which version (push) Successful in 1s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 1m7s
release / tag and release (push) Successful in 2s
Own sign-in with passkeys, public entrance, market (26.11.2) (#3)
2026-11-06 19:32:34 +00:00

136 lines
5.1 KiB
TypeScript

import "server-only";
import type { PoolClient } from "pg";
import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
type AuthenticationResponseJSON,
type AuthenticatorTransportFuture,
type RegistrationResponseJSON,
} from "@simplewebauthn/server";
// Passkeys (WebAuthn). Die Herausforderung liegt in auth_challenges, gilt
// fünf Minuten und wird beim Prüfen verbraucht — ein Mitschnitt lässt sich
// nicht wiederholen. Der Passkey gehört zur Domain, unter der eingerichtet
// wurde (instance.origin, instance.rp_id).
const CHALLENGE_MINUTES = 5;
const RP_NAME = "Was gibt's?";
export type Instance = { origin: string; rpId: string };
type Purpose = "setup" | "invite" | "login" | "recovery";
export async function loadInstance(client: PoolClient): Promise<Instance | null> {
const { rows } = await client.query("select origin, rp_id from instance");
return rows[0] ? { origin: rows[0].origin, rpId: rows[0].rp_id } : null;
}
async function storeChallenge(client: PoolClient, challenge: string, purpose: Purpose, context: object): Promise<string> {
await client.query("delete from auth_challenges where expires_at < now()");
const { rows } = await client.query(
`insert into auth_challenges (challenge, purpose, context, expires_at)
values ($1, $2, $3, now() + make_interval(mins => $4)) returning id`,
[challenge, purpose, JSON.stringify(context), CHALLENGE_MINUTES],
);
return rows[0].id;
}
/** Holt und verbraucht eine Herausforderung. */
export async function takeChallenge<T>(
client: PoolClient,
id: unknown,
purpose: Purpose,
): Promise<{ challenge: string; context: T } | null> {
if (typeof id !== "string" || !/^[0-9a-f-]{36}$/.test(id)) return null;
const { rows } = await client.query(
"delete from auth_challenges where id = $1 and purpose = $2 and expires_at > now() returning challenge, context",
[id, purpose],
);
return rows[0] ? { challenge: rows[0].challenge, context: rows[0].context as T } : null;
}
export async function registrationOptions(
client: PoolClient,
instance: Instance,
user: { id: string; name: string },
purpose: Purpose,
context: object,
exclude: { id: string; transports: string[] }[] = [],
) {
const options = await generateRegistrationOptions({
rpName: RP_NAME,
rpID: instance.rpId,
userName: user.name,
userDisplayName: user.name,
userID: Buffer.from(user.id.replace(/-/g, ""), "hex"),
attestationType: "none",
// Der Passkey ist der einzige Faktor: Besitz allein genügt nicht, das Gerät
// muss die Person prüfen (Gesicht, Finger, Geräte-PIN).
authenticatorSelection: { residentKey: "required", userVerification: "required" },
excludeCredentials: exclude.map((c) => ({ id: c.id, transports: c.transports as AuthenticatorTransportFuture[] })),
});
const challengeId = await storeChallenge(client, options.challenge, purpose, context);
return { challengeId, options };
}
export async function verifyRegistration(instance: Instance, challenge: string, response: RegistrationResponseJSON) {
const result = await verifyRegistrationResponse({
response,
expectedChallenge: challenge,
expectedOrigin: instance.origin,
expectedRPID: instance.rpId,
requireUserVerification: true,
});
if (!result.verified || !result.registrationInfo) return null;
const { credential, credentialDeviceType, credentialBackedUp } = result.registrationInfo;
return {
id: credential.id,
publicKey: Buffer.from(credential.publicKey),
counter: credential.counter,
transports: (response.response.transports ?? []) as string[],
deviceType: credentialDeviceType,
backedUp: credentialBackedUp,
};
}
export async function authenticationOptions(client: PoolClient, instance: Instance) {
const options = await generateAuthenticationOptions({ rpID: instance.rpId, userVerification: "required" });
const challengeId = await storeChallenge(client, options.challenge, "login", {});
return { challengeId, options };
}
export async function verifyAuthentication(
instance: Instance,
challenge: string,
response: AuthenticationResponseJSON,
passkey: { id: string; publicKey: Buffer; counter: number; transports: string[] },
) {
const result = await verifyAuthenticationResponse({
response,
expectedChallenge: challenge,
expectedOrigin: instance.origin,
expectedRPID: instance.rpId,
credential: {
id: passkey.id,
publicKey: new Uint8Array(passkey.publicKey),
counter: passkey.counter,
transports: passkey.transports as AuthenticatorTransportFuture[],
},
requireUserVerification: true,
});
return result.verified ? result.authenticationInfo.newCounter : null;
}
/** Erkennt einen Passkey grob am Gerät, damit die Liste lesbar ist. */
export function deviceLabel(userAgent: string | null): string {
const ua = userAgent ?? "";
if (/iPhone/.test(ua)) return "iPhone";
if (/iPad/.test(ua)) return "iPad";
if (/Android/.test(ua)) return "Android";
if (/Macintosh/.test(ua)) return "Mac";
if (/Windows/.test(ua)) return "Windows";
if (/Linux/.test(ua)) return "Linux";
return "";
}