Files
crosscode-platform/apps/accounts/backend/src/lib/passwords.ts
T
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00

44 lines
1.7 KiB
TypeScript

/**
* Passwords: Argon2id with Events' parameters. bcrypt hashes (imported from Cross Events, whose
* older accounts still have them) verify too, and `needsRehash` tells the caller to store a new
* Argon2id hash after a successful sign-in, as Events does.
*/
import argon2 from '@node-rs/argon2';
import bcrypt from 'bcryptjs';
const OPTIONS = { algorithm: 2 as const /* Argon2id */, memoryCost: 19456, timeCost: 2, parallelism: 1 };
const PREFIX = `$argon2id$v=19$m=${OPTIONS.memoryCost},t=${OPTIONS.timeCost},p=${OPTIONS.parallelism}$`;
export const MIN_PASSWORD_LENGTH = 8;
export const MAX_PASSWORD_LENGTH = 200;
export function hashPassword(password: string): Promise<string> {
return argon2.hash(password, OPTIONS);
}
export async function verifyPassword(password: string, hash: string | null | undefined): Promise<boolean> {
if (!hash) return false;
try {
if (hash.startsWith('$argon2')) return await argon2.verify(hash, password);
if (/^\$2[aby]\$/.test(hash)) return await bcrypt.compare(password, hash);
} catch {
return false;
}
return false;
}
export const needsRehash = (hash: string) => !hash.startsWith(PREFIX);
/** A hash to compare against when there's no account, so a missing account takes as long. */
let dummy: Promise<string> | null = null;
export function dummyHash(): Promise<string> {
if (!dummy) dummy = hashPassword('no-such-account-placeholder');
return dummy;
}
export function passwordProblem(password: unknown): string | null {
if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`;
if (password.length > MAX_PASSWORD_LENGTH) return 'That password is too long.';
return null;
}