From 767a27b1d07b839871c8bc32c701cf12cb0185be Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:18:20 +0000 Subject: [PATCH] Faster sign-in: stay signed in 90 days, optional password, passkeys on the web, device list - Member sessions slide to 90 days after last use (12 hours for 'not my device'); admins 30 days - Settings > Sign-in and security: password (argon2id, lockout), passkeys (WebAuthn), signed-in devices with sign out per device, all other devices, or everywhere - Gentle offer after a code sign-in; security notice email on every change - Passwords and passkeys in a separate credentials table, never in the member record Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvRBohp4Uwx8BacUZGx --- README.md | 18 + apps/api/package.json | 2 + apps/api/scripts/smoke.ts | 14 + apps/api/sql/control.sql | 5 + apps/api/sql/site.sql | 13 + apps/api/src/app.ts | 51 ++- apps/api/src/config.ts | 4 + apps/api/src/db.ts | 4 + apps/api/src/notify.ts | 16 +- apps/api/src/passkeys.ts | 68 +++ apps/api/src/passwords.ts | 16 + apps/api/src/pg-repo.ts | 37 +- apps/member/package.json | 1 + apps/member/src/app/(app)/me.tsx | 2 + apps/member/src/app/admin/index.tsx | 10 +- apps/member/src/app/faster-sign-in.tsx | 65 +++ apps/member/src/app/verify.tsx | 10 +- apps/member/src/lib/after-sign-in.ts | 28 ++ apps/member/src/lib/passkey.ts | 40 ++ apps/member/src/lib/session.tsx | 21 +- apps/member/src/lib/storage.ts | 8 + apps/member/src/ui/JoinForm.tsx | 76 +++- apps/member/src/ui/SecurityCard.tsx | 207 +++++++++ apps/member/src/ui/kit.tsx | 2 + package-lock.json | 557 +++++++++++++++++++++++++ packages/core/src/api.ts | 43 +- packages/core/src/http-client.ts | 17 +- packages/core/src/index.ts | 1 + packages/core/src/memory-platform.ts | 10 +- packages/core/src/memory-repo.ts | 15 +- packages/core/src/repo.ts | 61 ++- packages/core/src/services.ts | 317 +++++++++++++- packages/core/src/signin.ts | 126 ++++++ packages/core/src/types.ts | 2 + packages/core/test/signin.test.ts | 207 +++++++++ 35 files changed, 2007 insertions(+), 67 deletions(-) create mode 100644 apps/api/src/passkeys.ts create mode 100644 apps/api/src/passwords.ts create mode 100644 apps/member/src/app/faster-sign-in.tsx create mode 100644 apps/member/src/lib/after-sign-in.ts create mode 100644 apps/member/src/lib/passkey.ts create mode 100644 apps/member/src/ui/SecurityCard.tsx create mode 100644 packages/core/src/signin.ts create mode 100644 packages/core/test/signin.test.ts diff --git a/README.md b/README.md index 9de1c7b..0f2d2da 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,24 @@ Demo sign-ins: member `alex@example.com`; owner `owner@whatbox.test`; WhatBox pl `npm run build:preview` builds the clickable preview, which runs the same core code in the browser with no server. +## Signing in + +Members sign in with a 6-digit code by email or text, which always works. On top of that: + +- **Stay signed in.** A member's own device stays signed in for 90 days after it was last used (the + apps always; the web unless they untick "Keep me signed in", which ends it after 12 hours or when the + tab closes). Admins: 30 days after last use. Settings lists each device, with "sign out" per device, + "sign out all other devices" and "sign out everywhere". +- **Optional password**, hashed with argon2id. 5 wrong tries lock it for 15 minutes (doubling each + round, at most a day); an emailed code still works and clears the lock. +- **Passkeys** (Face ID, fingerprint, Windows Hello) on the web, verified with `@simplewebauthn/server`. + A site's passkeys belong to its own domain (afterh.com) and work on app.afterh.com. Local dev: set + `PASSKEY_RP_ID=localhost`. `PASSKEYS=off` hides them. The iPhone and Android apps don't offer them yet: + that needs the Apple Team ID and Android signing key published on each domain. +- Adding a password or passkey needs a sign-in or confirmation in the last 30 minutes. Every change + emails the member a security notice. Passwords and passkeys live in their own `credentials` table, + never in the member record. + ## Tests ``` diff --git a/apps/api/package.json b/apps/api/package.json index 1f84cdc..d0874b8 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -27,6 +27,8 @@ "@nestjs/common": "^11.2.12", "@nestjs/core": "^11.2.12", "@nestjs/platform-express": "^11.2.12", + "@node-rs/argon2": "^2.2.2", + "@simplewebauthn/server": "^14.1.0", "@whatbox/core": "^0.1.0", "all-the-cities": "3.1.0", "jose": "^6.2.18", diff --git a/apps/api/scripts/smoke.ts b/apps/api/scripts/smoke.ts index 1b8e437..b56794c 100644 --- a/apps/api/scripts/smoke.ts +++ b/apps/api/scripts/smoke.ts @@ -16,6 +16,20 @@ const base = process.env.API_URL ?? 'http://localhost:4000'; const me = await api.me(); assert.equal(me.member.displayName, 'Alex'); + // Faster sign-in: an optional password (argon2id), the device list, signing other devices out + await api.setPassword('smoke test kettle song'); + const pwApi = createHttpMemberApi(base, 'afterh', 'ios'); + await assert.rejects(pwApi.signInWithPassword(DEMO_MEMBER_EMAIL, 'not the password at all'), /don't match/); + pwApi.setToken((await pwApi.signInWithPassword(DEMO_MEMBER_EMAIL, 'smoke test kettle song')).token); + let sec = await api.security(); + assert.ok(sec.hasPassword && sec.devices.some((d) => d.device === 'iPhone or iPad app' && d.method === 'password')); + sec = await api.signOutOthers(); + assert.ok(sec.devices.every((d) => d.current)); + await assert.rejects(pwApi.me(), /sign in/i); + assert.equal((await api.removePassword()).hasPassword, false); + assert.equal(site.signIn?.passkeys, true); + assert.ok((await api.passkeyOptions()).ticket); + const res = await api.search({ withinMiles: 50, pageSize: 48 }); assert.ok(res.total > 5); const rosa = res.people.find((p) => p.displayName === 'Rosa')!; diff --git a/apps/api/sql/control.sql b/apps/api/sql/control.sql index a675d1c..bfa00ef 100644 --- a/apps/api/sql/control.sql +++ b/apps/api/sql/control.sql @@ -78,3 +78,8 @@ CREATE TABLE IF NOT EXISTS mail_log ( ); CREATE INDEX IF NOT EXISTS mail_log_at_idx ON mail_log (at); CREATE INDEX IF NOT EXISTS mail_log_msg_idx ON mail_log (message_id) WHERE message_id IS NOT NULL; + +-- Admins stay signed in while they use the admin at least once every 30 days. +ALTER TABLE admin_sessions ADD COLUMN IF NOT EXISTS created_at timestamptz; +ALTER TABLE admin_sessions ADD COLUMN IF NOT EXISTS last_used_at timestamptz; +CREATE INDEX IF NOT EXISTS admin_sessions_admin_idx ON admin_sessions (admin_id); diff --git a/apps/api/sql/site.sql b/apps/api/sql/site.sql index 4c85b6c..1363299 100644 --- a/apps/api/sql/site.sql +++ b/apps/api/sql/site.sql @@ -260,3 +260,16 @@ CREATE TABLE IF NOT EXISTS mail_sends ( ); CREATE INDEX IF NOT EXISTS mail_sends_due_idx ON mail_sends (campaign_id, next_at) WHERE status IN ('waiting', 'retry'); CREATE INDEX IF NOT EXISTS mail_sends_msg_idx ON mail_sends (message_id) WHERE message_id IS NOT NULL; + +-- Stay signed in: device name, how they signed in, last use (sliding 90-day expiry). Older rows have no doc. +ALTER TABLE sessions ADD COLUMN IF NOT EXISTS doc jsonb; +CREATE INDEX IF NOT EXISTS sessions_member_idx ON sessions (member_id); + +-- Optional passwords (argon2id hashes) and passkeys (public keys only). Never part of the member record. +CREATE TABLE IF NOT EXISTS credentials ( + id text PRIMARY KEY, -- pw_ or pk_ + member_id text NOT NULL REFERENCES members(id) ON DELETE CASCADE, + kind text NOT NULL, -- password | passkey + doc jsonb NOT NULL +); +CREATE INDEX IF NOT EXISTS credentials_member_idx ON credentials (member_id); diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index f553e79..4d75bd7 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -17,6 +17,13 @@ function bearer(auth?: string) { function clientPlatform(v?: string): ClientPlatform { return v === 'ios' || v === 'android' ? v : 'web'; } +/** Where a sign-in comes from, for the device list and "stay signed in". */ +function signInMeta(r: Request, b?: { remember?: unknown }) { + return { + ip: r.ip, userAgent: String(r.headers['user-agent'] ?? '').slice(0, 300), + platform: clientPlatform(r.headers['x-client-platform'] as string), remember: b?.remember !== false, + }; +} @Catch() export class ErrorFilter implements ExceptionFilter { @@ -55,10 +62,22 @@ export class PublicController extends SiteScoped { } @Post('auth/provider') async provider(@Req() r: Request, @Body() b: { provider: string; idToken: string }) { if (b.provider !== 'apple' && b.provider !== 'google') throw new RuleError('bad_provider', 'Unknown sign-in option.'); - return this.p.signInWithProvider(await this.site(r), b.provider, String(b.idToken ?? ''), { ip: r.ip }); + return this.p.signInWithProvider(await this.site(r), b.provider, String(b.idToken ?? ''), signInMeta(r)); + } + @Post('auth/verify') async verify(@Req() r: Request, @Body() b: { challengeId: string; code: string; remember?: boolean }) { + return this.p.verifyCode(await this.site(r), String(b.challengeId), String(b.code), signInMeta(r, b)); + } + @Post('auth/password') async password(@Req() r: Request, @Body() b: { email?: string; password?: string; remember?: boolean }) { + return this.p.signInWithPassword(await this.site(r), String(b.email ?? ''), String(b.password ?? '').slice(0, 200), signInMeta(r, b)); } - @Post('auth/verify') async verify(@Req() r: Request, @Body() b: { challengeId: string; code: string }) { - return this.p.verifyCode(await this.site(r), String(b.challengeId), String(b.code), { ip: r.ip }); + @Post('auth/passkey/options') async passkeyOptions(@Req() r: Request) { + return this.p.passkeySignInStart(await this.site(r), { ip: r.ip }); + } + @Post('auth/passkey') async passkey(@Req() r: Request, @Body() b: { ticket?: string; response?: unknown; remember?: boolean }) { + return this.p.signInWithPasskey(await this.site(r), String(b.ticket ?? ''), b.response, signInMeta(r, b)); + } + @Post('auth/sign-out-everywhere') async signOutEverywhere(@Req() r: Request) { + return this.p.signOutEverywhere(await this.ctx(r)); } // Lost access to the old email: the new address is confirmed with a code from auth/start first. @Post('auth/email-change') async emailChange(@Req() r: Request, @Body() b: { challengeId?: string; code?: string; oldEmail?: string; details?: string }) { @@ -104,6 +123,31 @@ export class GeoController extends SiteScoped { @Controller('v1/me') export class MeController extends SiteScoped { constructor(@Inject(PLATFORM) p: Platform) { super(p); } + // Settings > Sign-in and security + @Get('security') async security(@Req() r: Request) { return this.p.security(await this.ctx(r), bearer(r.headers.authorization)!); } + @Post('security/confirm/start') async confirmStart(@Req() r: Request) { return this.p.reauthStart(await this.ctx(r), { ip: r.ip }); } + @Post('security/confirm') async confirm(@Req() r: Request, @Body() b: { challengeId?: string; code?: string; password?: string }) { + return this.p.reauth(await this.ctx(r), bearer(r.headers.authorization)!, { + challengeId: b.challengeId ? String(b.challengeId) : undefined, code: b.code ? String(b.code) : undefined, password: b.password ? String(b.password).slice(0, 200) : undefined, + }, { ip: r.ip }); + } + @Put('security/password') async setPassword(@Req() r: Request, @Body() b: { password?: string }) { + return this.p.setPassword(await this.ctx(r), bearer(r.headers.authorization)!, String(b.password ?? '')); + } + @Delete('security/password') async removePassword(@Req() r: Request) { return this.p.removePassword(await this.ctx(r), bearer(r.headers.authorization)!); } + @Post('security/passkeys/options') async passkeyRegOptions(@Req() r: Request) { return this.p.passkeyRegisterStart(await this.ctx(r), bearer(r.headers.authorization)!); } + @Post('security/passkeys') async addPasskey(@Req() r: Request, @Body() b: { ticket?: string; response?: unknown; name?: string }) { + return this.p.passkeyRegisterFinish(await this.ctx(r), bearer(r.headers.authorization)!, String(b.ticket ?? ''), b.response, b.name ? String(b.name) : undefined); + } + @Delete('security/passkeys/:id') async removePasskey(@Req() r: Request, @Param('id') id: string) { + return this.p.removePasskey(await this.ctx(r), bearer(r.headers.authorization)!, id); + } + @Delete('security/devices/:id') async signOutDevice(@Req() r: Request, @Param('id') id: string) { + return this.p.signOutDevice(await this.ctx(r), bearer(r.headers.authorization)!, id); + } + @Post('security/devices/sign-out-others') async signOutOthers(@Req() r: Request) { + return this.p.signOutOthers(await this.ctx(r), bearer(r.headers.authorization)!); + } @Get() async me(@Req() r: Request) { return this.p.myProfile(await this.ctx(r)); } @Get('preview') async preview(@Req() r: Request) { return this.p.previewProfile(await this.ctx(r)); } @Patch() async update(@Req() r: Request, @Body() b: any) { return this.p.updateProfile(await this.ctx(r), b); } @@ -196,6 +240,7 @@ export class AdminController { private admin(auth?: string) { return this.p.adminFromToken(bearer(auth)); } @Post('auth/start') start(@Req() r: Request, @Body() b: { email: string }) { return this.p.adminStart(String(b.email ?? ''), { ip: r.ip }); } @Post('auth/verify') verify(@Body() b: { challengeId: string; code: string }) { return this.p.adminVerify(String(b.challengeId), String(b.code)); } + @Post('auth/sign-out') signOut(@Headers('authorization') a: string, @Body() b: { everywhere?: boolean }) { return this.p.adminSignOut(bearer(a), !!b?.everywhere); } @Get('me') async me(@Headers('authorization') a: string) { const ad = await this.admin(a); return { admin: { id: ad.id, email: ad.email, name: ad.name, role: ad.role }, sites: await this.p.adminSites(ad) }; diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index f1ad599..d9ddda3 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -20,6 +20,10 @@ export const config = { acsSmsFromJson: process.env.ACS_SMS_FROM_JSON ?? '', // {"*":"+18005550100"} push: process.env.PUSH ?? 'none', // none | expo expoAccessToken: process.env.EXPO_ACCESS_TOKEN === 'none' ? '' : process.env.EXPO_ACCESS_TOKEN ?? '', + // Passkeys (Face ID / fingerprint sign-in on the web). on | off. Each site's passkeys belong to its own domain. + passkeys: process.env.PASSKEYS !== 'off', + passkeyRpId: process.env.PASSKEY_RP_ID ?? '', // dev only: e.g. localhost + passkeyOrigins: (process.env.PASSKEY_ORIGINS ?? (process.env.NODE_ENV === 'production' ? '' : 'http://localhost:8081,http://localhost:19006')).split(',').filter(Boolean), oauthClientsJson: process.env.OAUTH_CLIENTS_JSON ?? '', // per-site Apple / Google client IDs // Photos: local (dev disk), azure (Blob, container per site) or inline (prototype data URIs only) photoStore: (process.env.PHOTO_STORE ?? 'local') as 'local' | 'azure' | 'inline', diff --git a/apps/api/src/db.ts b/apps/api/src/db.ts index 10aa796..e47dea9 100644 --- a/apps/api/src/db.ts +++ b/apps/api/src/db.ts @@ -10,6 +10,8 @@ import { createIdTokenVerifier } from './idp'; import { createPaymentGateways } from './payments'; import { PgSiteProvisioner } from './provision'; import { createIpIntel } from './ipintel'; +import { createPasskeys } from './passkeys'; +import { Argon2Hasher } from './passwords'; export { pool, closePools } from './db-pool'; @@ -57,6 +59,8 @@ export function createPlatform(opts: { ipIntel?: boolean } = {}) { mailLimits: { hourly: config.mailHourlyLimit, reserve: config.mailCodeReserve, perMinute: config.mailPerMinute }, photos, idTokens: createIdTokenVerifier(), + passwords: new Argon2Hasher(), + passkeys: createPasskeys(), events, exposeDevCodes: config.exposeDevCodes, rateLimitScale: config.rateLimitScale, diff --git a/apps/api/src/notify.ts b/apps/api/src/notify.ts index ae8533b..bc004e4 100644 --- a/apps/api/src/notify.ts +++ b/apps/api/src/notify.ts @@ -3,7 +3,7 @@ // arriving on a shared phone or inbox gives nothing away (sensitive sites especially). import { EmailClient } from '@azure/communication-email'; import { SmsClient } from '@azure/communication-sms'; -import { type MailSender, type Notifier, safetyNoticeContent, type Site } from '@whatbox/core'; +import { type MailSender, type Notifier, safetyNoticeContent, type SecurityChange, securityNoticeContent, type Site } from '@whatbox/core'; import { config } from './config'; export function codeText(site: Site, code: string) { @@ -18,6 +18,9 @@ export const consoleNotifier: Notifier = { async sendSafetyNotice({ site, email, displayName }) { console.log(`[notify] ${site.slug} safety notice to ${email.replace(/^(.).*@/, '$1•••@')} about "${displayName}"`); }, + async sendSecurityNotice({ site, email, change }) { + console.log(`[notify] ${site.slug} security notice to ${email.replace(/^(.).*@/, '$1•••@')}: ${change}`); + }, async sendAdminCode({ email, code }) { console.log(`[notify] admin ${email.replace(/^(.).*@/, '$1•••@')} code=${config.exposeDevCodes ? code : '(hidden)'}`); }, @@ -104,6 +107,17 @@ export class AcsNotifier implements Notifier, MailSender { }); } + async sendSecurityNotice({ site, email, change }: { site: Site; email: string; change: SecurityChange }) { + const from = this.siteSender(site); + if (!from) throw new Error(`No email sender configured for ${site.id}`); + const c = securityNoticeContent(site, change); + await this.sendEmail(`${site.slug} security notice ${mask(email)}`, from, { + senderAddress: from, + recipients: { to: [{ address: email }] }, + content: { subject: c.subject, plainText: c.text, html: c.html }, + }); + } + private siteSender(site: Site) { if (this.emailFrom[site.id]) return this.emailFrom[site.id]; for (const d of site.domains ?? []) { diff --git a/apps/api/src/passkeys.ts b/apps/api/src/passkeys.ts new file mode 100644 index 0000000..ce3afc4 --- /dev/null +++ b/apps/api/src/passkeys.ts @@ -0,0 +1,68 @@ +// Passkeys (WebAuthn): Face ID, fingerprint, Windows Hello, a phone or a security key. +// A passkey belongs to the site's own domain (afterh.com), so it works on app.afterh.com and can +// never be used on another WhatBox site. Local dev uses "localhost". +import type { PasskeyVerifier, Site } from '@whatbox/core'; +import { + generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse, + type AuthenticationResponseJSON, type RegistrationResponseJSON, +} from '@simplewebauthn/server'; +import { isoBase64URL } from '@simplewebauthn/server/helpers'; +import { config } from './config'; + +/** The passkey's domain for a site, and the web addresses allowed to use it. */ +export function passkeyRp(site: Site): { id: string; origins: string[] } { + const d = (site.domains.find((x) => !x.endsWith('.localhost') && x !== 'localhost') ?? '').replace(/^www\./, '').toLowerCase(); + const extra = config.passkeyOrigins; + if (!d || config.passkeyRpId) return { id: config.passkeyRpId || 'localhost', origins: extra }; + return { id: d, origins: [`https://app.${d}`, `https://${d}`, `https://www.${d}`, ...extra] }; +} + +export class WebAuthnPasskeys implements PasskeyVerifier { + async registrationOptions(site: Site, a: { userId: string; userName: string; exclude: { id: string; transports?: string[] }[] }) { + const rp = passkeyRp(site); + const options = await generateRegistrationOptions({ + rpName: site.name, rpID: rp.id, + userName: a.userName, userDisplayName: a.userName, + userID: new TextEncoder().encode(a.userId), + attestationType: 'none', + excludeCredentials: a.exclude, + // A discoverable passkey lets members sign in without typing their email first. + authenticatorSelection: { residentKey: 'required', userVerification: 'required' }, + }); + return { options, challenge: options.challenge }; + } + + async verifyRegistration(site: Site, response: unknown, challenge: string) { + const rp = passkeyRp(site); + const v = await verifyRegistrationResponse({ + response: response as RegistrationResponseJSON, expectedChallenge: challenge, + expectedOrigin: rp.origins, expectedRPID: rp.id, requireUserVerification: true, + }); + if (!v.verified) throw new Error('passkey registration not verified'); + const c = v.registrationInfo.credential; + return { + credentialId: c.id, publicKey: isoBase64URL.fromBuffer(c.publicKey), counter: c.counter, + transports: c.transports, backedUp: v.registrationInfo.credentialBackedUp, + }; + } + + async authenticationOptions(site: Site) { + const options = await generateAuthenticationOptions({ rpID: passkeyRp(site).id, userVerification: 'required' }); + return { options, challenge: options.challenge }; + } + + async verifyAuthentication(site: Site, response: unknown, challenge: string, cred: { credentialId: string; publicKey: string; counter: number; transports?: string[] }) { + const rp = passkeyRp(site); + const v = await verifyAuthenticationResponse({ + response: response as AuthenticationResponseJSON, expectedChallenge: challenge, + expectedOrigin: rp.origins, expectedRPID: rp.id, requireUserVerification: true, + credential: { id: cred.credentialId, publicKey: isoBase64URL.toBuffer(cred.publicKey), counter: cred.counter, transports: cred.transports as never }, + }); + if (!v.verified) throw new Error('passkey not verified'); + return { newCounter: v.authenticationInfo.newCounter }; + } +} + +export function createPasskeys(): PasskeyVerifier | undefined { + return config.passkeys ? new WebAuthnPasskeys() : undefined; +} diff --git a/apps/api/src/passwords.ts b/apps/api/src/passwords.ts new file mode 100644 index 0000000..d9603fe --- /dev/null +++ b/apps/api/src/passwords.ts @@ -0,0 +1,16 @@ +// Optional member passwords, hashed with argon2id (OWASP's recommended settings: 19 MiB, 2 passes). +import { hash, verify } from '@node-rs/argon2'; +import { Pbkdf2Hasher, type PasswordHasher } from '@whatbox/core'; + +const ARGON2ID = 2; // Algorithm.Argon2id (a const enum, so not importable at runtime under tsx) + +export class Argon2Hasher implements PasswordHasher { + private pbkdf2 = new Pbkdf2Hasher(); + async hash(password: string) { + return hash(password.normalize('NFKC'), { algorithm: ARGON2ID, memoryCost: 19_456, timeCost: 2, parallelism: 1 }); + } + async verify(stored: string, password: string) { + if (stored.startsWith('pbkdf2$')) return this.pbkdf2.verify(stored, password); + try { return await verify(stored, password.normalize('NFKC')); } catch { return false; } + } +} diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 9c85a50..b684ecd 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -2,13 +2,14 @@ // PgControlRepo talks to the shared control database; each PgSiteRepo talks to one site's own database. import type { Campaign, MailKind, MailLogEntry, MailSend, MailSendStatus, MemberStatus, - AdminChallenge, AdminSession, AdminUser, Block, EventRsvp, SiteEvent, ContactOptIn, ContentPage, ControlRepo, Favorite, Like, Pass, Member, MemberQuery, MemberSession, + AdminChallenge, AdminSession, AdminUser, Block, MemberCredential, EventRsvp, SiteEvent, ContactOptIn, ContentPage, ControlRepo, Favorite, Like, Pass, Member, MemberQuery, MemberSession, Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteKpiRaw, SiteRepo, Subscription, TrafficHit, UsageKind, AuditEntry, VerificationChallenge, View, } from '@whatbox/core'; import type { Pool } from 'pg'; import { NETWORK_KEEP_DAYS } from '@whatbox/core'; const docs = (rows: { doc: T }[]) => rows.map((r) => r.doc); +const sessionRow = (r: any): MemberSession => ({ ...(r.doc ?? {}), token: r.token, memberId: r.member_id, expiresAt: new Date(r.expires_at).toISOString() }); export class PgControlRepo implements ControlRepo { constructor(private db: Pool) {} @@ -36,13 +37,21 @@ export class PgControlRepo implements ControlRepo { return (await this.db.query('SELECT doc FROM admins WHERE lower(email)=lower($1)', [email])).rows[0]?.doc ?? null; } async saveAdminSession(s: AdminSession) { - await this.db.query('INSERT INTO admin_sessions (token, admin_id, expires_at) VALUES ($1,$2,$3)', [s.token, s.adminId, s.expiresAt]); + await this.db.query( + `INSERT INTO admin_sessions (token, admin_id, expires_at, created_at, last_used_at) VALUES ($1,$2,$3,$4,$5) + ON CONFLICT (token) DO UPDATE SET expires_at=$3, last_used_at=$5`, + [s.token, s.adminId, s.expiresAt, s.createdAt ?? null, s.lastUsedAt ?? null], + ); } - async getAdminSession(token: string) { - const r = (await this.db.query('SELECT token, admin_id, expires_at FROM admin_sessions WHERE token=$1', [token])).rows[0]; - return r ? { token: r.token, adminId: r.admin_id, expiresAt: new Date(r.expires_at).toISOString() } : null; + async getAdminSession(token: string): Promise { + const r = (await this.db.query('SELECT token, admin_id, expires_at, created_at, last_used_at FROM admin_sessions WHERE token=$1', [token])).rows[0]; + return r ? { + token: r.token, adminId: r.admin_id, expiresAt: new Date(r.expires_at).toISOString(), + createdAt: r.created_at ? new Date(r.created_at).toISOString() : undefined, lastUsedAt: r.last_used_at ? new Date(r.last_used_at).toISOString() : undefined, + } : null; } async deleteAdminSession(token: string) { await this.db.query('DELETE FROM admin_sessions WHERE token=$1', [token]); } + async deleteAdminSessionsOf(adminId: string) { await this.db.query('DELETE FROM admin_sessions WHERE admin_id=$1', [adminId]); } async saveAdminChallenge(c: AdminChallenge) { await this.db.query( `INSERT INTO admin_challenges (id, admin_id, code_hash, expires_at, attempts) VALUES ($1,$2,$3,$4,$5) @@ -436,11 +445,25 @@ export class PgSiteRepo implements SiteRepo { } async getChallenge(id: string) { return (await this.db.query('SELECT doc FROM challenges WHERE id=$1', [id])).rows[0]?.doc ?? null; } async saveSession(s: MemberSession) { - await this.db.query('INSERT INTO sessions VALUES ($1,$2,$3)', [s.token, s.memberId, s.expiresAt]); + const { token, memberId, expiresAt, ...doc } = s; + await this.db.query( + 'INSERT INTO sessions (token, member_id, expires_at, doc) VALUES ($1,$2,$3,$4) ON CONFLICT (token) DO UPDATE SET expires_at=$3, doc=$4', + [token, memberId, expiresAt, doc], + ); + } + async listSessionsOf(memberId: string): Promise { + const rows = (await this.db.query('SELECT * FROM sessions WHERE member_id=$1', [memberId])).rows; + return rows.map(sessionRow); + } + async listCredentials(memberId: string) { return docs((await this.db.query('SELECT doc FROM credentials WHERE member_id=$1', [memberId])).rows); } + async getCredential(id: string) { return (await this.db.query('SELECT doc FROM credentials WHERE id=$1', [id])).rows[0]?.doc ?? null; } + async saveCredential(c: MemberCredential) { + await this.db.query('INSERT INTO credentials (id, member_id, kind, doc) VALUES ($1,$2,$3,$4) ON CONFLICT (id) DO UPDATE SET doc=$4', [c.id, c.memberId, c.kind, c]); } + async deleteCredential(id: string) { await this.db.query('DELETE FROM credentials WHERE id=$1', [id]); } async getSession(t: string) { const r = (await this.db.query('SELECT * FROM sessions WHERE token=$1', [t])).rows[0]; - return r ? { token: r.token, memberId: r.member_id, expiresAt: iso(r.expires_at) } : null; + return r ? sessionRow(r) : null; } async deleteSession(t: string) { await this.db.query('DELETE FROM sessions WHERE token=$1', [t]); } diff --git a/apps/member/package.json b/apps/member/package.json index 3ddfcd5..efa5cc0 100644 --- a/apps/member/package.json +++ b/apps/member/package.json @@ -5,6 +5,7 @@ "dependencies": { "@expo/metro-runtime": "~58.0.17", "@react-native-async-storage/async-storage": "^2.2.0", + "@simplewebauthn/browser": "^14.0.0", "@whatbox/core": "*", "expo": "~58.1.0", "expo-apple-authentication": "~58.0.3", diff --git a/apps/member/src/app/(app)/me.tsx b/apps/member/src/app/(app)/me.tsx index 32ac0e4..469cbd1 100644 --- a/apps/member/src/app/(app)/me.tsx +++ b/apps/member/src/app/(app)/me.tsx @@ -10,6 +10,7 @@ import { LocationPicker, type PickedLocation } from '../../ui/LocationPicker'; import { DISTANCE_STEPS, distanceLabel } from '../../lib/distance'; import { TIERS, type Tier, type TierPerms, type Units } from '@whatbox/core'; import { PhotoManager } from '../../ui/PhotoManager'; +import { SecurityCard } from '../../ui/SecurityCard'; type Tab = 'profile' | 'photos' | 'access' | 'settings'; const NOTIFY_ROWS: [keyof NotifyPrefs, string][] = [ @@ -275,6 +276,7 @@ function SettingsTab() { Signed in with {m.contact || 'a verified contact'}. This is encrypted and never shown to other members. { await signOut(); router.replace('/'); }} /> + ); diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 45a284c..cf176bf 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -64,7 +64,7 @@ function Admin() { if (!checked || !api) return ; if (!me) return { api.setToken(token); await storage.set(TOKEN_KEY, token); setMe(await api.me()); }} />; - return setMe(await api.me())} onOut={async () => { await storage.set(TOKEN_KEY, null); setMe(null); }} />; + return setMe(await api.me())} onOut={async (everywhere) => { await api.signOut(everywhere); await storage.set(TOKEN_KEY, null); setMe(null); }} />; } function AdminLogin({ api, onIn }: { api: AdminApi; onIn: (token: string) => Promise }) { @@ -116,7 +116,7 @@ function WhatBoxMark() { ); } -function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited>; reload: () => void; onOut: () => void }) { +function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited>; reload: () => void; onOut: (everywhere?: boolean) => void }) { const t = useTheme(); const wide = useWide(980); const [siteId, setSiteId] = useState(me.sites[0]?.id); @@ -164,7 +164,11 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited {me.admin.name} {me.admin.email} · {me.admin.role === 'platform' ? 'Platform admin' : 'Owner'} - + Stays signed in for 30 days after you last use the admin. + + onOut()} /> + onOut(true)} /> + ); diff --git a/apps/member/src/app/faster-sign-in.tsx b/apps/member/src/app/faster-sign-in.tsx new file mode 100644 index 0000000..85f60b7 --- /dev/null +++ b/apps/member/src/app/faster-sign-in.tsx @@ -0,0 +1,65 @@ +// Shown once after a code sign-in to members with no password or passkey: make next time faster. +import { ApiError } from '@whatbox/core'; +import { router } from 'expo-router'; +import { useState } from 'react'; +import { View } from 'react-native'; +import { fasterSignInNotNow } from '../lib/after-sign-in'; +import { passkeysSupported } from '../lib/passkey'; +import { useSession } from '../lib/session'; +import { AuthFrame } from '../ui/AuthFrame'; +import { Btn, ErrorText, H, Icon, Notice, Txt, useTheme } from '../ui/kit'; +import { addPasskeyFlow, PasswordForm } from '../ui/SecurityCard'; + +export default function FasterSignIn() { + const { api, site, siteKey, me } = useSession(); + const t = useTheme(); + const [mode, setMode] = useState<'pick' | 'password'>('pick'); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(null); + const [done, setDone] = useState(null); + const passkey = !!site.signIn?.passkeys && passkeysSupported(); + const go = () => router.replace(me?.member.profileComplete ? '/discover' : '/onboarding'); + const fail = (e: unknown) => setError(e instanceof ApiError && e.code === 'reauth_needed' + ? 'That took a while, so for your security add it from Settings instead.' + : e instanceof Error ? e.message : 'Something went wrong. Try again.'); + + return ( + + + + + + Skip the code next time? + You'll stay signed in on this device for 90 days. For other devices, or after that, you can sign in {passkey ? 'with your face or fingerprint, or a password,' : 'with a password'} instead of waiting for an email. + + + {done ? ( + <> + {done} + + + ) : mode === 'password' ? ( + setMode('pick')} onSave={async (pw) => { + setBusy('pw'); setError(null); + try { await api.setPassword(pw); setDone('Password saved. Next time choose "Use my password instead".'); return true; } + catch (e) { fail(e); return false; } finally { setBusy(null); } + }} /> + ) : ( + <> + {passkey ? ( + { + setBusy('pk'); setError(null); + try { if (await addPasskeyFlow(api)) setDone('All set. Next time tap "Sign in with Face ID or fingerprint".'); } + catch (e) { fail(e); } finally { setBusy(null); } + }} /> + ) : null} + setMode('password')} /> + { await fasterSignInNotNow(siteKey); go(); }} /> + You can change this any time in Settings. The emailed code always works too. + + )} + + + + ); +} diff --git a/apps/member/src/app/verify.tsx b/apps/member/src/app/verify.tsx index fc45019..ad158d8 100644 --- a/apps/member/src/app/verify.tsx +++ b/apps/member/src/app/verify.tsx @@ -2,12 +2,14 @@ import { ApiError } from '@whatbox/core'; import { router, useLocalSearchParams } from 'expo-router'; import { useEffect, useRef, useState } from 'react'; import { Pressable, TextInput, View } from 'react-native'; +import { afterCodeSignIn } from '../lib/after-sign-in'; import { useSession } from '../lib/session'; import { AuthFrame } from '../ui/AuthFrame'; import { Btn, ErrorText, Eyebrow, fonts, H, Notice, Txt, useTheme } from '../ui/kit'; export default function Verify() { - const params = useLocalSearchParams<{ challengeId: string; sentTo: string; channel: string; devCode?: string }>(); + const params = useLocalSearchParams<{ challengeId: string; sentTo: string; channel: string; devCode?: string; remember?: string }>(); + const remember = params.remember !== '0'; const { api, signIn } = useSession(); const t = useTheme(); const [code, setCode] = useState(''); @@ -27,9 +29,9 @@ export default function Verify() { if (value.length !== 6) { setError('Enter all 6 digits.'); return; } setBusy(true); setError(null); try { - const r = await api.verify(challenge!, value); - const me = await signIn(r.token); - router.replace(me?.member.profileComplete ? '/discover' : '/onboarding'); + const r = await api.verify(challenge!, value, { remember }); + const me = await signIn(r.token, remember); + await afterCodeSignIn(api, me); } catch (e) { setError(e instanceof ApiError ? e.message : 'Something went wrong.'); setCode(''); diff --git a/apps/member/src/lib/after-sign-in.ts b/apps/member/src/lib/after-sign-in.ts new file mode 100644 index 0000000..8cca652 --- /dev/null +++ b/apps/member/src/lib/after-sign-in.ts @@ -0,0 +1,28 @@ +// Where to go after signing in. After a code sign-in, members with no password or passkey get one +// gentle offer to make next time faster; "Not now" hides it for 30 days on that device. +import type { MemberApi, MyProfile } from '@whatbox/core'; +import { router } from 'expo-router'; +import { storage } from './storage'; + +const NOT_NOW = (site: string) => `whatbox.faster-sign-in.later.${site}`; +const LATER_MS = 30 * 86_400_000; + +export function afterSignIn(me: MyProfile | null) { + router.replace(me?.member.profileComplete ? '/discover' : '/onboarding'); +} + +export async function afterCodeSignIn(api: MemberApi, me: MyProfile | null) { + if (!me?.member.profileComplete) return afterSignIn(me); + try { + const later = Number(await storage.get(NOT_NOW(api.siteKey))); + if (!(later && Date.now() - later < LATER_MS)) { + const sec = await api.security(); + if (!sec.hasPassword && sec.passkeys.length === 0) { router.replace('/faster-sign-in'); return; } + } + } catch { /* never block sign-in on this */ } + afterSignIn(me); +} + +export async function fasterSignInNotNow(siteKey: string) { + await storage.set(NOT_NOW(siteKey), String(Date.now())); +} diff --git a/apps/member/src/lib/passkey.ts b/apps/member/src/lib/passkey.ts new file mode 100644 index 0000000..e6d1d3f --- /dev/null +++ b/apps/member/src/lib/passkey.ts @@ -0,0 +1,40 @@ +// Passkeys (Face ID, fingerprint, Windows Hello) in the browser. The iPhone and Android apps don't offer +// them yet: that needs the app's Apple Team ID and Android signing key published on each site's domain, +// which comes with the app store accounts. In the apps, members stay signed in and can use a password. +import { browserSupportsWebAuthn, startAuthentication, startRegistration, WebAuthnError } from '@simplewebauthn/browser'; +import { Platform } from 'react-native'; + +export function passkeysSupported(): boolean { + if (Platform.OS !== 'web') return false; + try { return browserSupportsWebAuthn(); } catch { return false; } +} + +/** What to call the new passkey in Settings, e.g. "iPhone" or "Windows". */ +export function passkeyDeviceName(): string { + const ua = typeof navigator !== 'undefined' ? navigator.userAgent : ''; + if (/iPhone/.test(ua)) return 'iPhone'; + if (/iPad/.test(ua)) return 'iPad'; + if (/Android/.test(ua)) return 'Android phone'; + if (/Macintosh/.test(ua)) return 'Mac'; + if (/Windows/.test(ua)) return 'Windows'; + if (/CrOS/.test(ua)) return 'Chromebook'; + return 'Passkey'; +} + +/** Null when the member closed the prompt; throws a friendly message otherwise. */ +export async function createPasskey(options: unknown) { + try { return await startRegistration({ optionsJSON: options as never }); } + catch (e) { return handle(e); } +} + +export async function signPasskey(options: unknown) { + try { return await startAuthentication({ optionsJSON: options as never }); } + catch (e) { return handle(e); } +} + +function handle(e: unknown): null { + const name = (e as { name?: string })?.name; + if (name === 'NotAllowedError' || name === 'AbortError') return null; // cancelled, or timed out + if (e instanceof WebAuthnError && e.code === 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED') throw new Error('This device already has a passkey for your account.'); + throw new Error("This device couldn't make a passkey. You can still sign in with a code or a password."); +} diff --git a/apps/member/src/lib/session.tsx b/apps/member/src/lib/session.tsx index be2f4ac..d9cb254 100644 --- a/apps/member/src/lib/session.tsx +++ b/apps/member/src/lib/session.tsx @@ -3,7 +3,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, use import { registerForPush } from './push'; import { Platform } from 'react-native'; import { DEFAULT_SITE, IS_PREVIEW, memberApi } from './backend'; -import { storage } from './storage'; +import { storage, tabStorage } from './storage'; interface SessionState { api: MemberApi; @@ -12,8 +12,9 @@ interface SessionState { me: MyProfile | null; ready: boolean; signedIn: boolean; - signIn(token: string): Promise; - signOut(): Promise; + /** remember false: web only, the token lives in this tab until it closes. */ + signIn(token: string, remember?: boolean): Promise; + signOut(opts?: { everywhere?: boolean }): Promise; refreshMe(): Promise; setMe(me: MyProfile): void; switchSite(key: string): Promise; @@ -63,11 +64,11 @@ export function SessionProvider({ children, fallback }: { children: ReactNode; f try { const a = await memberApi(key); const s = await a.site(); - const token = await storage.get(tokenKey(key)); + const token = (await storage.get(tokenKey(key))) ?? tabStorage.get(tokenKey(key)); a.setToken(token); let profile: MyProfile | null = null; if (token) { - try { profile = await a.me(); } catch { a.setToken(null); await storage.set(tokenKey(key), null); } + try { profile = await a.me(); } catch { a.setToken(null); await storage.set(tokenKey(key), null); tabStorage.set(tokenKey(key), null); } } setApi(a); setSite(s); setMe(profile); setSignedIn(!!profile); setSiteKey(key); if (profile?.member.profileComplete) a.unreadCount().then(setUnread).catch(() => {}); @@ -87,16 +88,18 @@ export function SessionProvider({ children, fallback }: { children: ReactNode; f if (!api || !site || !siteKey) return null; return { api, site, siteKey, me, ready: true, signedIn, unread, - async signIn(token) { + async signIn(token, remember = true) { api.setToken(token); - await storage.set(tokenKey(siteKey), token); + await storage.set(tokenKey(siteKey), remember ? token : null); + tabStorage.set(tokenKey(siteKey), remember ? null : token); const p = await api.me(); setMe(p); setSignedIn(true); return p; }, - async signOut() { - try { await api.signOut(); } catch {} + async signOut(opts) { + try { await (opts?.everywhere ? api.signOutEverywhere() : api.signOut()); } catch {} await storage.set(tokenKey(siteKey), null); + tabStorage.set(tokenKey(siteKey), null); setMe(null); setSignedIn(false); setUnread(0); }, async refreshMe() { diff --git a/apps/member/src/lib/storage.ts b/apps/member/src/lib/storage.ts index c89e6d5..b7e906c 100644 --- a/apps/member/src/lib/storage.ts +++ b/apps/member/src/lib/storage.ts @@ -4,6 +4,14 @@ import { Platform } from 'react-native'; const web = Platform.OS === 'web'; +/** Web only: kept until the browser tab closes ("not my device"). Native apps always remember. */ +export const tabStorage = { + get(key: string): string | null { try { return web ? globalThis.sessionStorage?.getItem(key) ?? null : null; } catch { return null; } }, + set(key: string, value: string | null) { + try { if (web) { if (value === null) globalThis.sessionStorage?.removeItem(key); else globalThis.sessionStorage?.setItem(key, value); } } catch { /* blocked */ } + }, +}; + export const storage = { async get(key: string): Promise { try { diff --git a/apps/member/src/ui/JoinForm.tsx b/apps/member/src/ui/JoinForm.tsx index 4e6e6d3..3ab17fc 100644 --- a/apps/member/src/ui/JoinForm.tsx +++ b/apps/member/src/ui/JoinForm.tsx @@ -1,52 +1,94 @@ import { ApiError } from '@whatbox/core'; import { router } from 'expo-router'; import { useState } from 'react'; -import { View } from 'react-native'; +import { Platform, View } from 'react-native'; +import { passkeysSupported, signPasskey } from '../lib/passkey'; import { useSession } from '../lib/session'; +import { afterSignIn } from '../lib/after-sign-in'; import { SocialSignIn } from './SocialSignIn'; import { Btn, Check, ErrorText, Field, H, Icon, Segmented, Txt, useTheme } from './kit'; export function JoinForm({ title = 'Join free', signIn = false }: { title?: string; signIn?: boolean }) { - const { api } = useSession(); + const { api, site, signIn: keep } = useSession(); const t = useTheme(); const [channel, setChannel] = useState<'email' | 'phone'>('email'); const [target, setTarget] = useState(''); const [agree, setAgree] = useState(signIn); - const [busy, setBusy] = useState(false); + const [usePassword, setUsePassword] = useState(false); + const [password, setPassword] = useState(''); + // The apps are always on the member's own phone. On the web, a shared computer can opt out. + const [remember, setRemember] = useState(true); + const [busy, setBusy] = useState(null); const [error, setError] = useState(null); + const passkeys = signIn && !!site.signIn?.passkeys && passkeysSupported(); + const web = Platform.OS === 'web'; - async function send() { - setError(null); + async function run(kind: 'code' | 'password' | 'passkey', fn: () => Promise) { + setError(null); setBusy(kind); + try { await fn(); } + catch (e) { setError(e instanceof ApiError || e instanceof Error ? e.message : 'Something went wrong. Try again.'); } + finally { setBusy(null); } + } + + const send = () => { if (!agree) { setError('Please confirm you are 18 or older and agree to the terms.'); return; } - setBusy(true); - try { + return run('code', async () => { const r = await api.startVerification(channel, target); - router.push({ pathname: '/verify', params: { challengeId: r.challengeId, sentTo: r.sentTo, channel, devCode: r.devCode ?? '' } }); - } catch (e) { - setError(e instanceof ApiError ? e.message : 'Something went wrong. Try again.'); - } finally { setBusy(false); } - } + router.push({ pathname: '/verify', params: { challengeId: r.challengeId, sentTo: r.sentTo, channel, devCode: r.devCode ?? '', remember: remember ? '1' : '0' } }); + }); + }; + + const withPassword = () => run('password', async () => { + const r = await api.signInWithPassword(target, password, { remember }); + const me = await keep(r.token, remember); + afterSignIn(me); + }); + + const withPasskey = () => run('passkey', async () => { + const o = await api.passkeyOptions(); + const response = await signPasskey(o.options); + if (!response) return; // closed the prompt + const r = await api.signInWithPasskey(o.ticket, response, { remember }); + const me = await keep(r.token, remember); + afterSignIn(me); + }); + const pw = signIn && usePassword && channel === 'email'; return ( {title} - We send a 6-digit code to confirm it is really you. + {pw ? 'Sign in with the password you set in Settings.' : 'We send a 6-digit code to confirm it is really you.'} - { setChannel(v); setError(null); }} /> + {passkeys ? ( + + + Works once you've added a passkey in Settings. Otherwise use your email below. + + ) : null} + {!pw ? { setChannel(v); setError(null); }} /> : null} {channel === 'email' ? ( - + ) : ( )} + {pw ? ( + + ) : null} {!signIn ? ( ) : null} + {web ? : null} + {web && !remember ? On a shared computer: you'll be signed out when you close this tab, or after 12 hours. : null} - + {pw ? : } + {signIn && channel === 'email' ? ( + { setUsePassword(!pw); setError(null); }} /> + ) : null} {signIn ? ( - Had a password on the old site? You don't need it anymore. Enter the same email and we'll send you a code. + Had a password on the old site? It didn't carry over. Sign in with a code, then add a new password or Face ID in Settings if you like. router.push('/lost-email')} /> ) : null} diff --git a/apps/member/src/ui/SecurityCard.tsx b/apps/member/src/ui/SecurityCard.tsx new file mode 100644 index 0000000..757a55f --- /dev/null +++ b/apps/member/src/ui/SecurityCard.tsx @@ -0,0 +1,207 @@ +// Settings > Sign-in and security: an optional password, passkeys (Face ID, fingerprint) on the web, +// and the devices that are signed in. The emailed code always works as well. +import { ApiError, PASSWORD_MIN, type SecurityInfo } from '@whatbox/core'; +import { router } from 'expo-router'; +import { useCallback, useEffect, useState } from 'react'; +import { Platform, View } from 'react-native'; +import { createPasskey, passkeyDeviceName, passkeysSupported } from '../lib/passkey'; +import { useSession } from '../lib/session'; +import { Btn, Card, ErrorText, Field, H, Icon, Notice, relTime, Txt, useTheme } from './kit'; + +const METHOD: Record = { code: 'emailed code', password: 'password', passkey: 'passkey', apple: 'Apple', google: 'Google' }; +const message = (e: unknown) => (e instanceof ApiError || e instanceof Error ? e.message : 'Something went wrong. Try again.'); + +/** Loads the member's sign-in options and runs changes, asking them to confirm it's them first when needed. */ +export function useSecurity() { + const { api } = useSession(); + const [sec, setSec] = useState(null); + const [confirming, setConfirming] = useState Promise)>(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + const reload = useCallback(() => api.security().then(setSec).catch((e) => setError(message(e))), [api]); + useEffect(() => { reload(); }, [reload]); + + async function run(key: string, fn: () => Promise): Promise { + setBusy(key); setError(null); + try { + const r = await fn(); + if (r) setSec(r); + return true; + } catch (e) { + if (e instanceof ApiError && e.code === 'reauth_needed') setConfirming(() => async () => { await run(key, fn); }); + else setError(message(e)); + return false; + } finally { setBusy(null); } + } + return { sec, reload, run, busy, error, setError, confirming, setConfirming }; +} + +/** "Confirm it's you": a code to their email, or their current password. Then the change it was for runs again. */ +export function ConfirmIdentity({ hasPassword, onDone, onCancel }: { hasPassword: boolean; onDone: () => Promise; onCancel: () => void }) { + const { api } = useSession(); + const [sent, setSent] = useState<{ challengeId: string; sentTo: string; devCode?: string } | null>(null); + const [code, setCode] = useState(''); + const [password, setPassword] = useState(''); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const go = async (fn: () => Promise) => { + setBusy(true); setError(null); + try { await fn(); } catch (e) { setError(message(e)); } finally { setBusy(false); } + }; + return ( + + + {!sent ? ( + <> + This keeps anyone who picks up your unlocked phone from changing how you sign in. + + go(async () => setSent(await api.reauthStart()))} /> + + + {hasPassword ? ( + + + go(async () => { await api.reauth({ password }); await onDone(); })} /> + + ) : null} + + ) : ( + <> + {sent.devCode ? `Prototype: your code is ${sent.devCode}.` : `We sent a 6-digit code to ${sent.sentTo}.`} + setCode(v.replace(/\D/g, '').slice(0, 6))} keyboardType="number-pad" autoComplete="one-time-code" textContentType="oneTimeCode" maxLength={6} /> + + go(async () => { await api.reauth({ challengeId: sent.challengeId, code }); await onDone(); })} /> + + + + )} + + + + ); +} + +export function PasswordForm({ hasPassword, busy, onSave, onCancel }: { hasPassword: boolean; busy: boolean; onSave: (pw: string) => Promise; onCancel?: () => void }) { + const [pw, setPw] = useState(''); + const [again, setAgain] = useState(''); + const [show, setShow] = useState(false); + const [error, setError] = useState(null); + return ( + + + + + + { + setError(null); + if (pw !== again) { setError("Those two don't match."); return; } + if (await onSave(pw)) { setPw(''); setAgain(''); } + }} /> + setShow(!show)} /> + {onCancel ? : null} + + + ); +} + +export async function addPasskeyFlow(api: ReturnType['api']): Promise { + const o = await api.passkeyRegisterOptions(); + const response = await createPasskey(o.options); + if (!response) return null; // closed the prompt + return api.addPasskey(o.ticket, response, passkeyDeviceName()); +} + +export function SecurityCard() { + const { api, signOut } = useSession(); + const t = useTheme(); + const s = useSecurity(); + const [editPw, setEditPw] = useState(false); + const [note, setNote] = useState(null); + const sec = s.sec; + if (!sec) return Sign-in and security; + const canPasskey = sec.passkeysAvailable && passkeysSupported(); + const others = sec.devices.filter((d) => !d.current); + const row = { flexDirection: 'row' as const, alignItems: 'center' as const, gap: 12, paddingVertical: 10, borderTopWidth: 1, borderColor: t.line, flexWrap: 'wrap' as const }; + + return ( + + + Sign-in and security + You stay signed in on your own devices for 90 days after you last use them. A code to your email always works too. + + {s.confirming ? ( + s.setConfirming(null)} onDone={async () => { const again = s.confirming!; s.setConfirming(null); await again(); }} /> + ) : null} + {note ? {note} : null} + + + + Face ID or fingerprint + {Platform.OS !== 'web' ? ( + You stay signed in to the app. Passkeys for the app are coming; for now you can add one on the website. + ) : !sec.passkeysAvailable ? ( + Not available in this preview. + ) : !canPasskey ? ( + This browser doesn't support passkeys. Try Safari, Chrome or Edge. + ) : ( + Sign in with your face, fingerprint or device PIN instead of a code. Nothing about your face or finger leaves your device. + )} + {sec.passkeys.map((p) => ( + + + + {p.name} + Added {relTime(p.createdAt)}{p.lastUsedAt ? ` · last used ${relTime(p.lastUsedAt)}` : ''} + + s.run('rm' + p.id, () => api.removePasskey(p.id))} /> + + ))} + {canPasskey ? ( + { setNote(null); if (await s.run('passkey', () => addPasskeyFlow(api))) s.reload(); }} /> + ) : null} + + + + Password + {sec.hasPassword ? `You can sign in with your email and password${sec.passwordSetAt ? ` (set ${relTime(sec.passwordSetAt)})` : ''}.` : 'Optional. Sign in with your email and a password instead of waiting for a code.'} + {editPw || !sec.hasPassword ? ( + editPw ? ( + setEditPw(false)} onSave={async (pw) => { + setNote(null); + const had = sec.hasPassword; + const ok = await s.run('pw', () => api.setPassword(pw)); + if (ok) { setEditPw(false); setNote(had ? 'Password changed. Your other devices were signed out.' : 'Password saved.'); } + return ok; + }} /> + ) : setEditPw(true)} /> + ) : ( + + setEditPw(true)} /> + s.run('rmpw', () => api.removePassword())} /> + + )} + + + + Where you're signed in + {sec.devices.map((d) => ( + + + + {d.device}{d.current ? ' (this device)' : ''} + {[d.method ? `Signed in with ${METHOD[d.method] ?? d.method}` : null, d.lastUsedAt ? `active ${relTime(d.lastUsedAt)}` : null].filter(Boolean).join(' · ') || 'Signed in earlier'} + + {!d.current && d.id ? s.run('dev' + d.id, () => api.signOutDevice(d.id))} /> : null} + + ))} + + {others.length ? s.run('others', () => api.signOutOthers())} /> : null} + { await signOut({ everywhere: true }); router.replace('/'); }} /> + + Lost a phone, or used a shared computer? Sign out everywhere, then sign back in here. + + + ); +} diff --git a/apps/member/src/ui/kit.tsx b/apps/member/src/ui/kit.tsx index ad11915..7f3b1d2 100644 --- a/apps/member/src/ui/kit.tsx +++ b/apps/member/src/ui/kit.tsx @@ -268,6 +268,8 @@ const ICONS = { heart: ['M19.5 12.6 12 20l-7.5-7.4A4.8 4.8 0 0 1 12 6.3a4.8 4.8 0 0 1 7.5 6.3Z'], chat: ['M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12Z'], lock: ['rect:4,11,16,10,2', 'M8 11V7a4 4 0 0 1 8 0v4'], + key: ['circle:7.5,15.5,5.5', 'm21 2-9.6 9.6', 'm15.5 7.5 3 3L22 7l-3-3'], + phone: ['rect:6,2,12,20,2', 'M11 18h2'], shield: ['M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z'], check: ['M20 6 9 17l-5-5'], back: ['m15 18-6-6 6-6'], diff --git a/package-lock.json b/package-lock.json index 7ce14b7..032b7a3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,6 +20,8 @@ "@nestjs/common": "^11.2.12", "@nestjs/core": "^11.2.12", "@nestjs/platform-express": "^11.2.12", + "@node-rs/argon2": "^2.2.2", + "@simplewebauthn/server": "^14.1.0", "@whatbox/core": "^0.1.0", "all-the-cities": "3.1.0", "jose": "^6.2.18", @@ -82,6 +84,7 @@ "dependencies": { "@expo/metro-runtime": "~58.0.17", "@react-native-async-storage/async-storage": "^2.2.0", + "@simplewebauthn/browser": "^14.0.0", "@whatbox/core": "*", "expo": "~58.1.0", "expo-apple-authentication": "~58.0.3", @@ -2751,6 +2754,12 @@ "excpretty": "build/cli.js" } }, + "node_modules/@hexagon/base64": { + "version": "1.1.28", + "resolved": "https://registry.npmjs.org/@hexagon/base64/-/base64-1.1.28.tgz", + "integrity": "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==", + "license": "MIT" + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -3344,6 +3353,12 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@levischuck/tiny-cbor": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/@levischuck/tiny-cbor/-/tiny-cbor-0.2.11.tgz", + "integrity": "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==", + "license": "MIT" + }, "node_modules/@lukeed/csprng": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz", @@ -3590,6 +3605,238 @@ ], "license": "MIT" }, + "node_modules/@node-rs/argon2": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2/-/argon2-2.2.2.tgz", + "integrity": "sha512-NtdlPPWtR5U4BxX5EGJYza+UklNaoWORmkaKCMqf/nyKeXWKVwNt8KfQoRpNT7OB1DcEwmePafO4wZyW+sbfCQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@node-rs/argon2-android-arm-eabi": "2.2.2", + "@node-rs/argon2-android-arm64": "2.2.2", + "@node-rs/argon2-darwin-arm64": "2.2.2", + "@node-rs/argon2-darwin-x64": "2.2.2", + "@node-rs/argon2-freebsd-x64": "2.2.2", + "@node-rs/argon2-linux-arm-gnueabihf": "2.2.2", + "@node-rs/argon2-linux-arm64-gnu": "2.2.2", + "@node-rs/argon2-linux-arm64-musl": "2.2.2", + "@node-rs/argon2-linux-x64-gnu": "2.2.2", + "@node-rs/argon2-linux-x64-musl": "2.2.2", + "@node-rs/argon2-win32-arm64-msvc": "2.2.2", + "@node-rs/argon2-win32-ia32-msvc": "2.2.2", + "@node-rs/argon2-win32-x64-msvc": "2.2.2" + } + }, + "node_modules/@node-rs/argon2-android-arm-eabi": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-android-arm-eabi/-/argon2-android-arm-eabi-2.2.2.tgz", + "integrity": "sha512-c11BOrPLBWNC1cDyzGB+Bil+flmxfZbB2hv8EhcobmAsFKMyqkHPNhUY4qhcjv1U+4+Vmw4G8H+l224iO2g/Dw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-android-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-android-arm64/-/argon2-android-arm64-2.2.2.tgz", + "integrity": "sha512-dpMYIoxhN/wY6hFH+3MM5kQErcH3luMekkszbkDF3NKqhB1kFRntkOLDpFY87oItBSHJrsoYkXC3vBRhjYoCjQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-darwin-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-darwin-arm64/-/argon2-darwin-arm64-2.2.2.tgz", + "integrity": "sha512-vxVAXcIG0iiHizkCuImmzVhOFsRnU4Z79xiOxdISLyI+QhOAWbbTaVSXw0PNfThB3zAdkzzDJ/WWu52Hs/qHGg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-darwin-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-darwin-x64/-/argon2-darwin-x64-2.2.2.tgz", + "integrity": "sha512-r7GbSFpFZZ9EAV9cvIm9prUjOupK7QQXTyP+FJ6bWSMq0h+qRDBlUOXQXduDIIrLEGoBVelixKUtf4ksZ0ljoQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-freebsd-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-freebsd-x64/-/argon2-freebsd-x64-2.2.2.tgz", + "integrity": "sha512-AmWxDSmQgprilD6NX3jmxCgcDvWAW7kGJnnWQo+0qav6nfMXdPZYgSezK/skmw1GBWipr4yZMIUzpeNHnVpMxg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-arm-gnueabihf": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm-gnueabihf/-/argon2-linux-arm-gnueabihf-2.2.2.tgz", + "integrity": "sha512-M1gnPBTr9GFeEUWkQ53qCJeTsX03C3kcUeHnDbN7dU2xkI58wMP4Z1sEBN7WmKJ/fTHYEgti4truz7r4A82DLg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-arm64-gnu": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm64-gnu/-/argon2-linux-arm64-gnu-2.2.2.tgz", + "integrity": "sha512-4CYDlIdITlLSVcAXYUtEoGUahRaayPXM+4Rcfg3BZx9WGi6UB8HUycs6GNMTPYXV5kVXCpyE2u1HmYUpgmIzOQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-arm64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm64-musl/-/argon2-linux-arm64-musl-2.2.2.tgz", + "integrity": "sha512-FYlfj3XgQ1xrx6HzQbKbUcKiYMG/3iSi/X81KyhHaItTJ7vZlMwrbVLl9yqDmvotKUF6VjrhrlZ8KRbbzchseA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-x64-gnu": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-x64-gnu/-/argon2-linux-x64-gnu-2.2.2.tgz", + "integrity": "sha512-ULXLs8UFYZANlwiROM7AeccxZndr2Xk3IstADq3jAUhnwV2W75mxMBTABUZ+7AdKRhPLOrxU77OgnMWlDkYJQg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-x64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-x64-musl/-/argon2-linux-x64-musl-2.2.2.tgz", + "integrity": "sha512-zgjIwc9TyGodn62vGc+36DGwFqVV5e7L8Ptd2FQWuBxe5aFrcFxvtDGn1/qfYwoHLv09utgtR+RBAPCXepWG3Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-win32-arm64-msvc": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-arm64-msvc/-/argon2-win32-arm64-msvc-2.2.2.tgz", + "integrity": "sha512-3nLhvLie/ec5xfxUBXXqGMb7oGeqF+YXrcGckqaTaGkPtOBozho0Kh2IuP/zi9BcOriirTG2LW3gtIOfpuh+mQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-win32-ia32-msvc": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-ia32-msvc/-/argon2-win32-ia32-msvc-2.2.2.tgz", + "integrity": "sha512-6RJKD6cFl7UeiYJLjRsXPywVXSFSaSDdr6xGpztNDV31QHCEecWnsnNmKxzi4gVpln2F9XeWEtIgM4Nqw1hLbA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-win32-x64-msvc": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-x64-msvc/-/argon2-win32-x64-msvc-2.2.2.tgz", + "integrity": "sha512-dQOO9S4QKBaVul0Uyk/2quJc/OBeHNZRJP+GZZTy1A5kYIaAfIJGHUYLY6oFoAlcuLIkdFouLaHX3fCl8tZm/w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, "node_modules/@noxcturnal/noxcturnal-darwin-arm64": { "version": "0.1.14", "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-darwin-arm64/-/noxcturnal-darwin-arm64-0.1.14.tgz", @@ -3727,6 +3974,239 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@peculiar/asn1-android": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-android/-/asn1-android-2.11.1.tgz", + "integrity": "sha512-AuUBRDNdWrgtnuJGXARa0Xdtq6OAD8GqezDQz6Qka7kyynMo9fzkcrtpBEHuX984uEB570BrhMZfJfkUDfpQfw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-asym-key": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-asym-key/-/asn1-asym-key-2.11.1.tgz", + "integrity": "sha512-YtXR0FbDtjHuNGvWXD4HFE7th5xYwG67O+ApDH/FZsjj5MOrWHzDvqwZ1vm6uFUJtMAkUDcF6VMPGOJ5gnLyUA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-pkcs8": "^2.11.1", + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-cms": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.11.1.tgz", + "integrity": "sha512-Bk+oatE62dW0Tzzpfk6vdQxfGGEfvuGdWgmijnKjcv7HqZCJISs85z4zw2uDArrk+R1Oel1wts/BBl7HHrtAcA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "@peculiar/asn1-x509-attr": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-csr": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.11.1.tgz", + "integrity": "sha512-KVfbXaKng8886/tOPG55t5K1XkTkGbR4amjIJzytXWobFU5nZgw/sKnSpa1hxP17nUSsrOF/7Mt9WUYeyLsi6Q==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-ecc": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.11.1.tgz", + "integrity": "sha512-7MSNji77fQa/oN3WAfwagMy8EoJFg50sW4hZ1dtr0zU1BSugit0I2DGpIdPhvkNplopQhz5bogxpn1077eaamA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pfx": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.11.1.tgz", + "integrity": "sha512-2SN2z8qkc2hk/GgTYA8RN54wtsCDZShg9gI2Mq1vLhdj1adcv5fhTbiEmExZUaAMqlizxiEpULQDfHM5iYtn1g==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.11.1", + "@peculiar/asn1-pkcs8": "^2.11.1", + "@peculiar/asn1-rsa": "^2.11.1", + "@peculiar/asn1-schema": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs8": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.11.1.tgz", + "integrity": "sha512-HqsSrnpQghRp9SM9QSmR6fa4z/BNktnKq7928+oq4qF0VAnuHZ4cyePKvcxh9fP4taBCP/WHNItlVNsYaQm2qw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs9": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.11.1.tgz", + "integrity": "sha512-OHFkTg8D2zYafILqFE4KPbqX8srpvd3diGDc2h2cduumawc765mOHGcuFMGvLWlL2bbCMWMmMSCtlXptsOuiPA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.11.1", + "@peculiar/asn1-pfx": "^2.11.1", + "@peculiar/asn1-pkcs8": "^2.11.1", + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "@peculiar/asn1-x509-attr": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-rsa": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.11.1.tgz", + "integrity": "sha512-6KwKGjulF489CpidZqkogNgLj6oGzgC4BL2FClM8PuJQ4t5NqT4q4a6A4vrSxBIBhMnL8hGYkLOpbVw0Vq38Tw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.1.tgz", + "integrity": "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g==", + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.11.1.tgz", + "integrity": "sha512-SXU4/X6B3FquqQAN6ARI0bFDUV7+L1WlvPEPMKzEMkstd2D7UyM0r93fv241+OjdhqAKYGx5MvV3gzZMAp0APA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509-attr": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.11.1.tgz", + "integrity": "sha512-n7RKFrbTzt8pGBlZ90kmKEn1qsLTTyw7lrvHMK0xsA42kQugPk/GXYpNbEcl7DkkdVsU/one5UX7KQPfxLj8vQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509-post-quantum": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-post-quantum/-/asn1-x509-post-quantum-2.11.1.tgz", + "integrity": "sha512-yD/pxCQ97nzwF7MGAW4kRd1WVLiMPhD39HxOnAr38DfGFwbpVhPnMbq+r6WX0XUrxn4w8ulsTdUafwVl46igLA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-asym-key": "^2.11.1", + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/x509": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-2.2.0.tgz", + "integrity": "sha512-adpW58ySPQMOUPv8pTKT3RIyCFqfUFt8X05ukPdtkQToXDVr8dMtxuenik1yx8tNFTbpApWsM/Hi5SzlIx48+Q==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.11.0", + "@peculiar/asn1-csr": "^2.11.0", + "@peculiar/asn1-ecc": "^2.11.0", + "@peculiar/asn1-pkcs9": "^2.11.0", + "@peculiar/asn1-rsa": "^2.11.0", + "@peculiar/asn1-schema": "^2.11.0", + "@peculiar/asn1-x509": "^2.11.0", + "@peculiar/asn1-x509-post-quantum": "^2.11.0", + "pvtsutils": "^1.3.6", + "tslib": "^2.8.1", + "tsyringe": "^4.10.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@radix-ui/primitive": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", @@ -4325,6 +4805,33 @@ } } }, + "node_modules/@simplewebauthn/browser": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@simplewebauthn/browser/-/browser-14.0.0.tgz", + "integrity": "sha512-1odWVqeEBTl7lJ9zMKLEsmTlnyrDO5iRcTvfMKKk1WThUnp/i8JJdffdj2icP+tty159s4PgwE3BiMoEW9NFow==", + "license": "MIT" + }, + "node_modules/@simplewebauthn/server": { + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/@simplewebauthn/server/-/server-14.1.0.tgz", + "integrity": "sha512-HPRRBR4Vzr45+RVvbmf6JuCfGdYYcSs4Pnnnp9YSY2IABa4JKnG+wxybczoB7rmdLCOMS/mbBa2ZL/Bcz58UlA==", + "license": "MIT", + "dependencies": { + "@hexagon/base64": "^1.1.27", + "@levischuck/tiny-cbor": "^0.2.2", + "@peculiar/asn1-android": "^2.6.0", + "@peculiar/asn1-ecc": "^2.6.1", + "@peculiar/asn1-rsa": "^2.6.1", + "@peculiar/asn1-schema": "^2.6.0", + "@peculiar/asn1-x509": "^2.6.1", + "@peculiar/asn1-x509-post-quantum": "^2.9.4", + "@peculiar/x509": "^2.1.0", + "reflect-metadata": "^0.2.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.12", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", @@ -5149,6 +5656,20 @@ "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", "license": "MIT" }, + "node_modules/asn1js": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz", + "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==", + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.2.0", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/aws-ssl-profiles": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", @@ -9906,6 +10427,24 @@ "url": "https://opencollective.com/express" } }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/qs": { "version": "6.17.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", @@ -11290,6 +11829,24 @@ "fsevents": "~2.3.3" } }, + "node_modules/tsyringe": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz", + "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==", + "license": "MIT", + "dependencies": { + "tslib": "^1.9.3" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/tsyringe/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, "node_modules/type-fest": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.7.1.tgz", diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index b72c913..dafa0ca 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -4,6 +4,7 @@ import { RuleError } from './rules'; import type { AccessRow, Platform, ProfilePatch } from './services'; import type { RenderedMail } from './mail'; +import type { SecurityInfo, SignInOptions } from './signin'; import type { ActivityKind, ActivityList, AdminConversationRow, AdminMemberProfile, AdminMemberRow, AdminMessageRow, SuspendReason, SuspendResult, ClientPlatform, MemberEvent, DiscoverCard, ContentPage, ConversationSummary, ConversationView, MemberProfile, MemberStatus, ModerationDecision, ModerationView, MyProfile, PhotoKind, PhotoRating, ProfileFieldDef, PublicSite, SearchFilters, @@ -25,8 +26,27 @@ export interface MemberApi { page(slug: string): Promise; startVerification(channel: 'email' | 'phone', target: string): Promise<{ challengeId: string; sentTo: string; devCode?: string }>; - verify(challengeId: string, code: string): Promise<{ token: string; isNew: boolean; restored?: boolean }>; + verify(challengeId: string, code: string, opts?: SignInOptions): Promise<{ token: string; isNew: boolean; restored?: boolean }>; + /** Optional password, for members who set one in Settings. */ + signInWithPassword(email: string, password: string, opts?: SignInOptions): Promise<{ token: string; isNew: boolean; restored?: boolean }>; + /** Passkey (Face ID, fingerprint, device PIN): get a challenge, let the browser sign it, then send it back. */ + passkeyOptions(): Promise<{ options: unknown; ticket: string }>; + signInWithPasskey(ticket: string, response: unknown, opts?: SignInOptions): Promise<{ token: string; isNew: boolean; restored?: boolean }>; signOut(): Promise; + /** Signs out every device, this one too. */ + signOutEverywhere(): Promise; + // Settings > Sign-in and security + security(): Promise; + /** Sends a code to the member's own email so they can confirm it's them before adding a password or passkey. */ + reauthStart(): Promise<{ challengeId: string; sentTo: string; devCode?: string }>; + reauth(input: { challengeId?: string; code?: string; password?: string }): Promise<{ ok: boolean }>; + setPassword(password: string): Promise; + removePassword(): Promise; + passkeyRegisterOptions(): Promise<{ options: unknown; ticket: string }>; + addPasskey(ticket: string, response: unknown, name?: string): Promise; + removePasskey(id: string): Promise; + signOutDevice(id: string): Promise; + signOutOthers(): Promise; /** Lost the old email: ask an admin to move the account to a new address (confirmed with a code from startVerification). */ requestEmailChange(input: { challengeId: string; code: string; oldEmail: string; details: string }): Promise<{ ok: boolean }>; /** From the link in an announcement email; no sign-in needed. */ @@ -80,6 +100,8 @@ export interface AdminApi { setToken(token: string | null): void; start(email: string): Promise<{ challengeId: string; devCode?: string }>; verify(challengeId: string, code: string): Promise<{ token: string }>; + /** everywhere: every device this admin is signed in on. */ + signOut(everywhere?: boolean): Promise; me(): Promise<{ admin: { id: string; email: string; name: string; role: 'platform' | 'owner' }; sites: AdminSiteSummary[] }>; site(siteId: string): Promise; updateSite(siteId: string, patch: SitePatch): Promise; @@ -148,8 +170,22 @@ export function createLocalMemberApi(platform: Platform, siteKey: string, client pages: () => wrap(async () => platform.publicPages(await site())), page: (slug) => wrap(async () => platform.publicPage(await site(), slug)), startVerification: (ch, t) => wrap(async () => platform.startVerification(await site(), ch, t)), - verify: (id, code) => wrap(async () => platform.verifyCode(await site(), id, code)), + verify: (id, code, o) => wrap(async () => platform.verifyCode(await site(), id, code, { platform: clientPlatform, remember: o?.remember })), + signInWithPassword: (email, pw, o) => wrap(async () => platform.signInWithPassword(await site(), email, pw, { platform: clientPlatform, remember: o?.remember })), + passkeyOptions: () => wrap(async () => platform.passkeySignInStart(await site())), + signInWithPasskey: (ticket, r, o) => wrap(async () => platform.signInWithPasskey(await site(), ticket, r, { platform: clientPlatform, remember: o?.remember })), signOut: () => wrap(async () => { if (token) await platform.signOut(await site(), token); token = null; }), + signOutEverywhere: () => wrap(async () => { await platform.signOutEverywhere(await ctx()); token = null; }), + security: () => wrap(async () => platform.security(await ctx(), token!)), + reauthStart: () => wrap(async () => platform.reauthStart(await ctx())), + reauth: (input) => wrap(async () => platform.reauth(await ctx(), token!, input)), + setPassword: (pw) => wrap(async () => platform.setPassword(await ctx(), token!, pw)), + removePassword: () => wrap(async () => platform.removePassword(await ctx(), token!)), + passkeyRegisterOptions: () => wrap(async () => platform.passkeyRegisterStart(await ctx(), token!)), + addPasskey: (ticket, r, name) => wrap(async () => platform.passkeyRegisterFinish(await ctx(), token!, ticket, r, name)), + removePasskey: (id) => wrap(async () => platform.removePasskey(await ctx(), token!, id)), + signOutDevice: (id) => wrap(async () => platform.signOutDevice(await ctx(), token!, id)), + signOutOthers: () => wrap(async () => platform.signOutOthers(await ctx(), token!)), me: () => wrap(async () => platform.myProfile(await ctx())), updateMe: (p) => wrap(async () => platform.updateProfile(await ctx(), p)), geoCountries: () => wrap(async () => { await ctx(); return platform.geoCountries(); }), @@ -190,7 +226,7 @@ export function createLocalMemberApi(platform: Platform, siteKey: string, client requestEmailChange: (input) => wrap(async () => platform.requestEmailChange(await site(), input)), unsubscribe: (m, sig) => wrap(async () => platform.unsubscribe(await site(), m, sig)), deleteAccount: (c) => wrap(async () => { const r = await platform.deleteAccount(await ctx(), c); token = null; return r; }), - signInWithProvider: (p, t) => wrap(async () => platform.signInWithProvider(await site(), p, t)), + signInWithProvider: (p, t) => wrap(async () => platform.signInWithProvider(await site(), p, t, { platform: clientPlatform })), conversations: () => wrap(async () => platform.conversations(await ctx())), conversation: (id) => wrap(async () => platform.conversation(await ctx(), id)), send: (id, b) => wrap(async () => platform.send(await ctx(), id, b)), @@ -206,6 +242,7 @@ export function createLocalAdminApi(platform: Platform): AdminApi { setToken: (t) => { token = t; }, start: (email) => wrap(() => platform.adminStart(email)), verify: (id, code) => wrap(() => platform.adminVerify(id, code)), + signOut: (everywhere) => wrap(async () => { await platform.adminSignOut(token, everywhere); token = null; }), me: () => wrap(async () => { const a = await admin(); return { admin: { id: a.id, email: a.email, name: a.name, role: a.role }, sites: await platform.adminSites(a) }; diff --git a/packages/core/src/http-client.ts b/packages/core/src/http-client.ts index 5420b6a..e8864da 100644 --- a/packages/core/src/http-client.ts +++ b/packages/core/src/http-client.ts @@ -80,7 +80,21 @@ export function createHttpMemberApi(baseUrl: string, siteKey: string, platform: pages: () => req('GET', '/v1/site/pages'), page: (slug) => req('GET', '/v1/site/pages/' + encodeURIComponent(slug)), startVerification: (channel, target) => req('POST', '/v1/auth/start', { channel, target }), - verify: (challengeId, code) => req('POST', '/v1/auth/verify', { challengeId, code }), + verify: (challengeId, code, o) => req('POST', '/v1/auth/verify', { challengeId, code, remember: o?.remember }), + signInWithPassword: (email, password, o) => req('POST', '/v1/auth/password', { email, password, remember: o?.remember }), + passkeyOptions: () => req('POST', '/v1/auth/passkey/options', {}), + signInWithPasskey: (ticket, response, o) => req('POST', '/v1/auth/passkey', { ticket, response, remember: o?.remember }), + signOutEverywhere: async () => { await req('POST', '/v1/auth/sign-out-everywhere'); token = null; }, + security: () => req('GET', '/v1/me/security'), + reauthStart: () => req('POST', '/v1/me/security/confirm/start', {}), + reauth: (input) => req('POST', '/v1/me/security/confirm', input), + setPassword: (password) => req('PUT', '/v1/me/security/password', { password }), + removePassword: () => req('DELETE', '/v1/me/security/password'), + passkeyRegisterOptions: () => req('POST', '/v1/me/security/passkeys/options', {}), + addPasskey: (ticket, response, name) => req('POST', '/v1/me/security/passkeys', { ticket, response, name }), + removePasskey: (id) => req('DELETE', '/v1/me/security/passkeys/' + encodeURIComponent(id)), + signOutDevice: (id) => req('DELETE', '/v1/me/security/devices/' + encodeURIComponent(id)), + signOutOthers: () => req('POST', '/v1/me/security/devices/sign-out-others', {}), requestEmailChange: (input) => req('POST', '/v1/auth/email-change', input), unsubscribe: (memberId, sig) => req('POST', '/v1/unsubscribe', { m: memberId, t: sig }), signOut: async () => { await req('POST', '/v1/auth/sign-out'); token = null; }, @@ -145,6 +159,7 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { setToken: (t) => { token = t; }, start: (email) => req('POST', '/v1/admin/auth/start', { email }), verify: (challengeId, code) => req('POST', '/v1/admin/auth/verify', { challengeId, code }), + signOut: async (everywhere) => { await req('POST', '/v1/admin/auth/sign-out', { everywhere: !!everywhere }).catch(() => {}); token = null; }, me: () => req('GET', '/v1/admin/me'), site: (id) => req('GET', s(id)), updateSite: (id, patch) => req('PATCH', s(id), patch), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 65b0134..aa599e1 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -20,3 +20,4 @@ export * from './update-check'; export * from './mail'; export * from './safety-notice'; export * from './network-risk'; +export * from './signin'; diff --git a/packages/core/src/memory-platform.ts b/packages/core/src/memory-platform.ts index 6e3c6ae..ccb06ba 100644 --- a/packages/core/src/memory-platform.ts +++ b/packages/core/src/memory-platform.ts @@ -1,7 +1,7 @@ // Builds a fully seeded, in-memory platform. Used by tests and the browser preview. import { DevKeyProvider, SiteCrypto } from './crypto'; import { MemoryControlRepo, MemorySiteRepo, type ControlSnapshot, type SiteSnapshot } from './memory-repo'; -import type { Clock, IdTokenVerifier, Notifier, PaymentGateway } from './repo'; +import type { Clock, IdTokenVerifier, Notifier, PasskeyVerifier, PasswordHasher, PaymentGateway, SecurityChange } from './repo'; import type { IpIntel } from './network-risk'; import { DEMO_MEMBER_EMAIL, seedAdmins, seedSite, seedSites } from './seed'; import { Platform } from './services'; @@ -17,6 +17,7 @@ export interface MemoryPlatform { snapshot(): MemoryPlatformSnapshot; sentCodes: { site: string; channel: string; target: string; code: string }[]; sentNotices: { site: string; email: string; displayName: string }[]; + sentSecurity: { site: string; email: string; change: SecurityChange }[]; } export async function createMemoryPlatform(opts: { @@ -31,11 +32,14 @@ export async function createMemoryPlatform(opts: { idTokens?: IdTokenVerifier; demoAnalytics?: boolean; // placeholder dashboard history (the preview turns it on) ipIntel?: IpIntel; // tests only: stands in for the API's local IP database + passkeys?: PasskeyVerifier; // tests only: the preview has no passkeys + passwords?: PasswordHasher; } = {}): Promise { const keys = new DevKeyProvider(opts.masterKey ?? 'preview-master-key'); const now = opts.clock?.now() ?? new Date(); const sentCodes: MemoryPlatform['sentCodes'] = []; const sentNotices: MemoryPlatform['sentNotices'] = []; + const sentSecurity: MemoryPlatform['sentSecurity'] = []; let control: MemoryControlRepo; const sites = new Map(); @@ -61,6 +65,7 @@ export async function createMemoryPlatform(opts: { const notifier: Notifier = { async sendCode({ site, channel, target, code }) { sentCodes.push({ site: site.slug, channel, target, code }); }, async sendSafetyNotice({ site, email, displayName }) { sentNotices.push({ site: site.slug, email, displayName }); }, + async sendSecurityNotice({ site, email, change }) { sentSecurity.push({ site: site.slug, email, change }); }, }; const platform = new Platform({ @@ -72,10 +77,11 @@ export async function createMemoryPlatform(opts: { }, keys, notifier, clock: opts.clock, exposeDevCodes: opts.exposeDevCodes ?? true, onChange: opts.onChange, rateLimitScale: opts.rateLimitScale, idTokens: opts.idTokens, events: new LocalEventHub(), allowSelfServeTier: opts.allowSelfServeTier ?? true, payments: opts.payments, ipIntel: opts.ipIntel, + passkeys: opts.passkeys, passwords: opts.passwords, }); return { - platform, control, sites, sentCodes, sentNotices, + platform, control, sites, sentCodes, sentNotices, sentSecurity, snapshot: () => ({ v: 1, control: control.snapshot(), sites: Object.fromEntries([...sites.entries()].map(([k, v]) => [k, v.snapshot()])), diff --git a/packages/core/src/memory-repo.ts b/packages/core/src/memory-repo.ts index 020f50f..6e01e42 100644 --- a/packages/core/src/memory-repo.ts +++ b/packages/core/src/memory-repo.ts @@ -2,7 +2,7 @@ // snapshotted to localStorage. Each site gets its own MemorySiteRepo instance, mirroring // the one-database-per-site layout of production. import { pruneNetwork } from './network-risk'; -import type { AdminChallenge, AdminSession, ControlRepo, MailKind, MailLogEntry, MemberQuery, MemberSession, SiteRepo } from './repo'; +import type { AdminChallenge, AdminSession, ControlRepo, MailKind, MailLogEntry, MemberCredential, MemberQuery, MemberSession, SiteRepo } from './repo'; import type { Campaign, MailSend, MailSendStatus, MemberStatus, UsageKind, AuditEntry, EventRsvp, SiteEvent, AdminUser, Block, Favorite, Pass, ContactOptIn, ContentPage, Like, Member, Message, ModerationItem, Photo, PrivateAccess, SiteKpiRaw, TrafficDay, TrafficHit, PushToken, Report, Subscription, ReviewStatus, Site, VerificationChallenge, View, @@ -44,7 +44,8 @@ export class MemoryControlRepo implements ControlRepo { async getAdminByEmail(email: string) { return clone(this.admins.find((a) => a.email.toLowerCase() === email.toLowerCase()) ?? null); } - async saveAdminSession(s: AdminSession) { this.sessions.push(clone(s)); } + async saveAdminSession(s: AdminSession) { this.sessions = this.sessions.filter((x) => x.token !== s.token).concat(clone(s)); } + async deleteAdminSessionsOf(adminId: string) { this.sessions = this.sessions.filter((x) => x.adminId !== adminId); } async getAdminSession(token: string) { return clone(this.sessions.find((s) => s.token === token) ?? null); } async deleteAdminSession(token: string) { this.sessions = this.sessions.filter((s) => s.token !== token); } private challenges = new Map(); @@ -99,7 +100,7 @@ export interface SiteSnapshot { members: Member[]; photos: Photo[]; access: PrivateAccess[]; likes: Like[]; views: View[]; blocks: Block[]; passes: Pass[]; favorites: Favorite[]; messages: Message[]; optins: ContactOptIn[]; reports: Report[]; moderation: ModerationItem[]; pages: ContentPage[]; challenges: VerificationChallenge[]; - sessions: MemberSession[]; push?: PushToken[]; subscriptions?: Subscription[]; + sessions: MemberSession[]; credentials?: MemberCredential[]; push?: PushToken[]; subscriptions?: Subscription[]; events?: SiteEvent[]; rsvps?: EventRsvp[]; analytics?: MemoryAnalytics; campaigns?: Campaign[]; mailSends?: MailSend[]; @@ -168,6 +169,7 @@ export class MemorySiteRepo implements SiteRepo { d.reports = d.reports.filter((x) => !pair(x.reporterId, x.targetId)); d.moderation = d.moderation.filter((x) => x.memberId !== id); d.sessions = d.sessions.filter((x) => x.memberId !== id); + d.credentials = (d.credentials ?? []).filter((x) => x.memberId !== id); d.subscriptions = (d.subscriptions ?? []).filter((x) => x.memberId !== id); d.push = (d.push ?? []).filter((x) => x.memberId !== id); d.mailSends = (d.mailSends ?? []).filter((x) => x.memberId !== id); @@ -337,7 +339,12 @@ export class MemorySiteRepo implements SiteRepo { async saveChallenge(c: VerificationChallenge) { this.upsert(this.d.challenges, c, (x) => x.id === c.id); } async getChallenge(id: string) { return clone(this.d.challenges.find((c) => c.id === id) ?? null); } - async saveSession(s: MemberSession) { this.d.sessions.push(clone(s)); } + async saveSession(s: MemberSession) { this.upsert(this.d.sessions, s, (x) => x.token === s.token); } + async listSessionsOf(memberId: string) { return clone(this.d.sessions.filter((s) => s.memberId === memberId)); } + async listCredentials(memberId: string) { return clone((this.d.credentials ?? []).filter((c) => c.memberId === memberId)); } + async getCredential(id: string) { return clone((this.d.credentials ?? []).find((c) => c.id === id) ?? null); } + async saveCredential(c: MemberCredential) { this.upsert((this.d.credentials ??= []), c, (x) => x.id === c.id); } + async deleteCredential(id: string) { this.d.credentials = (this.d.credentials ?? []).filter((c) => c.id !== id); } async getSession(t: string) { return clone(this.d.sessions.find((s) => s.token === t) ?? null); } async deleteSession(t: string) { this.d.sessions = this.d.sessions.filter((s) => s.token !== t); } diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index 41c81ee..c000c56 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -5,9 +5,36 @@ import type { Photo, PrivateAccess, PushToken, Report, Subscription, SubscriptionStatus, ReviewStatus, Site, SiteKpiRaw, TrafficHit, UsageKind, VerificationChallenge, View, } from './types'; -export interface AdminSession { token: string; adminId: string; expiresAt: string } +export interface AdminSession { token: string; adminId: string; expiresAt: string; createdAt?: string; lastUsedAt?: string } export interface AdminChallenge { id: string; adminId: string; codeHash: string; expiresAt: string; attempts: number } -export interface MemberSession { token: string; memberId: string; expiresAt: string } +export type SignInMethod = 'code' | 'password' | 'passkey' | 'apple' | 'google'; +/** One signed-in device. Only the HMAC of the token is stored (as `token`); `id` is a separate random id + * that is safe to show the member so they can sign that device out. Sessions from before Nov 2026 have + * only token, memberId and expiresAt. */ +export interface MemberSession { + token: string; memberId: string; expiresAt: string; + id?: string; + createdAt?: string; + lastUsedAt?: string; + method?: SignInMethod; + device?: string; // "iPhone app", "Chrome on Windows" + remember?: boolean; // false: ends after 12 hours and never extends ("not my device") + reauthAt?: string; // when the member last confirmed it's them (code or password) on this device +} +/** A password or a passkey. Kept apart from the member record so it can never be sent to a client by accident. */ +export interface MemberCredential { + id: string; // pw_ or pk_ + memberId: string; + kind: 'password' | 'passkey'; + createdAt: string; + lastUsedAt?: string; + // password + hash?: string; + fails?: number; // wrong tries in a row + lockedUntil?: string; + // passkey + passkey?: { credentialId: string; publicKey: string; counter: number; transports?: string[]; name: string; backedUp?: boolean }; +} export interface ControlRepo { listSites(): Promise; @@ -19,9 +46,10 @@ export interface ControlRepo { listAdmins(): Promise; saveAdmin(a: AdminUser): Promise; deleteAdmin(id: string): Promise; - saveAdminSession(s: AdminSession): Promise; + saveAdminSession(s: AdminSession): Promise; // insert or update (sliding expiry) getAdminSession(token: string): Promise; deleteAdminSession(token: string): Promise; + deleteAdminSessionsOf(adminId: string): Promise; saveAdminChallenge(c: AdminChallenge): Promise; getAdminChallenge(id: string): Promise; deleteAdminChallenge(id: string): Promise; @@ -144,9 +172,15 @@ export interface SiteRepo { // auth saveChallenge(c: VerificationChallenge): Promise; getChallenge(id: string): Promise; - saveSession(s: MemberSession): Promise; + saveSession(s: MemberSession): Promise; // insert or update (sliding expiry) getSession(token: string): Promise; deleteSession(token: string): Promise; + listSessionsOf(memberId: string): Promise; + // passwords and passkeys + listCredentials(memberId: string): Promise; + getCredential(id: string): Promise; + saveCredential(c: MemberCredential): Promise; + deleteCredential(id: string): Promise; // billing saveSubscription(s: Subscription): Promise; @@ -183,6 +217,8 @@ export interface Notifier { // Sends a verification code. Dev/preview implementations just record it. sendCode(args: { site: Site; channel: 'email' | 'phone'; target: string; code: string }): Promise; sendAdminCode?(args: { email: string; code: string }): Promise; + /** "A password was added to your account": sent whenever sign-in options change. */ + sendSecurityNotice?(args: { site: Site; email: string; change: SecurityChange }): Promise; /** Tells a member that someone they messaged was removed for breaking the safety guidelines. Sent regardless of email preferences. */ sendSafetyNotice?(args: { site: Site; email: string; displayName: string }): Promise; } @@ -219,5 +255,22 @@ export interface EventSink { emit(site: Site, memberId: string, event: MemberEvent): void; } +export type SecurityChange = 'password_set' | 'password_changed' | 'password_removed' | 'passkey_added' | 'passkey_removed'; + +/** Slow, salted password hashing. The API uses argon2id; the preview and tests use PBKDF2 from WebCrypto. */ +export interface PasswordHasher { + hash(password: string): Promise; + verify(stored: string, password: string): Promise; +} + +/** WebAuthn (passkeys: Face ID, fingerprint, Windows Hello, a phone or a security key). The API implements + * it with @simplewebauthn/server; it is absent in the preview, which then hides passkeys. */ +export interface PasskeyVerifier { + registrationOptions(site: Site, a: { userId: string; userName: string; exclude: { id: string; transports?: string[] }[] }): Promise<{ options: unknown; challenge: string }>; + verifyRegistration(site: Site, response: unknown, challenge: string): Promise<{ credentialId: string; publicKey: string; counter: number; transports?: string[]; backedUp?: boolean }>; + authenticationOptions(site: Site): Promise<{ options: unknown; challenge: string }>; + verifyAuthentication(site: Site, response: unknown, challenge: string, cred: { credentialId: string; publicKey: string; counter: number; transports?: string[] }): Promise<{ newCounter: number }>; +} + export interface Clock { now(): Date } export const systemClock: Clock = { now: () => new Date() }; diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 033788c..2b2d690 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -8,7 +8,11 @@ import { memberFlags, type NicheFlag, outsideNiche, textFlags } from './niche'; import { buildSiteDashboard, cleanHitPath, combineDashboards, DASHBOARD_DAYS, emptySiteDashboard, isBotAgent, publicGoogleTags, referrerHost, utcDay, addDays, validateGoogleTags, } from './analytics'; -import type { ControlRepo, Clock, EventSink, IdTokenVerifier, MailSender, Notifier, PaymentGateway, PhotoStore, SiteProvisioner, SiteRepo } from './repo'; +import type { ControlRepo, Clock, EventSink, IdTokenVerifier, MailSender, MemberCredential, MemberSession, Notifier, PasskeyVerifier, PasswordHasher, PaymentGateway, PhotoStore, SecurityChange, SignInMethod, SiteProvisioner, SiteRepo } from './repo'; +import { + ADMIN_SESSION_IDLE_MS, checkPasswordStrength, deviceLabel, MAX_SESSIONS, MEMBER_SESSION_IDLE_MS, PASSWORD_LOCK_AFTER, passwordLockMs, + Pbkdf2Hasher, REAUTH_WINDOW_MS, SESSION_TOUCH_MS, SHORT_SESSION_MS, type SecurityInfo, +} from './signin'; import { campaignProblems, relaunchCopy, renderCampaign, siteAppUrl, type RenderedMail } from './mail'; import { systemClock } from './repo'; import { DEFAULT_LICENSING, DELETED_RETENTION_DAYS, DEFAULT_NOTIFY, DEFAULT_STRICT, isGender, type HiddenPrefs, type NotifyPrefs, type StrictPrefs } from './types'; @@ -31,6 +35,8 @@ export interface PlatformDeps { notifier: Notifier; photos?: PhotoStore; // absent in the preview, which keeps data URIs idTokens?: IdTokenVerifier; // Apple and Google sign-in; absent where not configured + passwords?: PasswordHasher; // argon2id in the API; PBKDF2 (WebCrypto) when absent + passkeys?: PasskeyVerifier; // WebAuthn; absent in the preview, which then hides passkeys events?: EventSink; payments?: Partial>; // by provider: paypal, stripe, ccbill, stub allowSelfServeTier?: boolean; @@ -93,12 +99,14 @@ export interface ProfilePatch { export interface AccessRow { member: MemberCard; status: AccessStatus; updatedAt: string } -const SESSION_TTL_MS = 30 * 86_400_000; const NAME_MAX = 24; const ABOUT_MAX = 2000; const MESSAGE_MAX = 2000; const PHOTO_MAX_BYTES = 10 * 1024 * 1024; +/** Where a sign-in comes from: for the device list, "stay signed in" and the network check. */ +export interface SignInMeta { ip?: string; userAgent?: string; platform?: ClientPlatform; remember?: boolean } + function maskTarget(channel: 'email' | 'phone', target: string): string { if (channel === 'email') { const [u, d] = target.split('@'); @@ -154,6 +162,7 @@ export class Platform { units: site.settings.units, nicheIncludeLabel: site.settings.niche?.includeLabel, googleTags: publicGoogleTags(site), + signIn: { password: true, passkeys: !!this.deps.passkeys }, }; } @@ -216,7 +225,7 @@ export class Platform { return { challengeId: id, sentTo: maskTarget(channel, target), devCode: this.deps.exposeDevCodes ? code : undefined }; } - async verifyCode(site: Site, challengeId: string, code: string, meta: { ip?: string } = {}) { + async verifyCode(site: Site, challengeId: string, code: string, meta: SignInMeta = {}) { const repo = await this.repo(site); const c = await this.consumeChallenge(site, challengeId, code); let member = await repo.findMemberByHash(c.channel, c.targetHash); @@ -231,7 +240,8 @@ export class Platform { await repo.saveMember(member); } if (member.status !== 'suspended') await this.noteNetwork(site, repo, member, meta.ip); - return this.startSession(site, member, isNew); + await this.clearPasswordLock(repo, member.id); // they proved they own the email, so let them try their password again + return this.startSession(site, member, isNew, { ...meta, method: 'code' }); } private async consumeChallenge(site: Site, challengeId: string, code: string) { @@ -298,7 +308,7 @@ export class Platform { return this.crypto(site).lookupHash('session:' + token); } - private async startSession(site: Site, member: Member, isNew: boolean) { + private async startSession(site: Site, member: Member, isNew: boolean, meta: SignInMeta & { method: SignInMethod }) { if (member.status === 'suspended') throw new RuleError('suspended', 'This account is suspended.', 403); const repo = await this.repo(site); // Signing in within the 6 months brings a deleted account back, just as it was. @@ -309,7 +319,14 @@ export class Platform { restored = true; } const token = site.slug + '.' + randomId(); - await repo.saveSession({ token: await this.sessionKey(site, token), memberId: member.id, expiresAt: new Date(this.now().getTime() + SESSION_TTL_MS).toISOString() }); + const remember = meta.remember !== false || meta.platform === 'ios' || meta.platform === 'android'; // the app is always a member's own phone + const now = this.iso(); + await repo.saveSession({ + token: await this.sessionKey(site, token), memberId: member.id, + expiresAt: new Date(this.now().getTime() + (remember ? MEMBER_SESSION_IDLE_MS : SHORT_SESSION_MS)).toISOString(), + id: randomId('ses_'), createdAt: now, lastUsedAt: now, method: meta.method, device: deviceLabel(meta.platform, meta.userAgent), remember, + }); + await this.trimSessions(repo, member.id); const day = utcDay(this.now()); await repo.bumpDaily('sign_ins', day).catch(() => {}); await repo.markActive(member.id, day).catch(() => {}); @@ -318,7 +335,7 @@ export class Platform { } // Apple or Google. Links to an existing account with the same verified email, otherwise creates one. - async signInWithProvider(site: Site, provider: 'apple' | 'google', idToken: string, meta: { ip?: string } = {}) { + async signInWithProvider(site: Site, provider: 'apple' | 'google', idToken: string, meta: SignInMeta = {}) { if (!this.deps.idTokens) throw new RuleError('provider_off', 'That sign-in option is not available yet.', 400); if (meta.ip) await this.limit(`idp-ip:${meta.ip}`, 3600, 60, 'Too many sign-in attempts from this network. Try again later.'); let claims: Awaited>; @@ -343,7 +360,7 @@ export class Platform { member.identityHashes = [...new Set([...(member.identityHashes ?? []), idHash])]; await repo.saveMember(member); if (member.status !== 'suspended') await this.noteNetwork(site, repo, member, meta.ip); - return this.startSession(site, member, isNew); + return this.startSession(site, member, isNew, { ...meta, method: provider }); } // Soft delete: hidden from every member at once and never emailed again. The account is kept for @@ -388,6 +405,13 @@ export class Platform { const me = await repo.getMember(s.memberId); if (!me || me.status === 'deleted') throw new RuleError('signed_out', 'Please sign in.', 401); if (me.status === 'suspended') throw new RuleError('suspended', 'This account is suspended.', 403); + // Stay signed in: each day the device is used pushes the end back to 90 days from now. + if (s.remember !== false && this.now().getTime() - Date.parse(s.lastUsedAt ?? '1970-01-01') > SESSION_TOUCH_MS) { + s.lastUsedAt = this.iso(); + s.expiresAt = new Date(this.now().getTime() + MEMBER_SESSION_IDLE_MS).toISOString(); + if (!s.id) s.id = randomId('ses_'); // sessions from before devices were listed + await repo.saveSession(s).catch(() => {}); + } // touch activity at most once a minute, and note each day they use the site const today = utcDay(this.now()); const newDay = me.lastActiveAt.slice(0, 10) !== today; @@ -405,6 +429,266 @@ export class Platform { this.changed(); } + // ---------------- Passwords, passkeys and signed-in devices ---------------- + + private hasher(): PasswordHasher { return this.deps.passwords ?? (this.fallbackHasher ??= new Pbkdf2Hasher()); } + private fallbackHasher?: PasswordHasher; + private dummyHash?: Promise; // checked when an email has no password, so both cases take as long + + private async trimSessions(repo: SiteRepo, memberId: string) { + const all = await repo.listSessionsOf(memberId); + if (all.length <= MAX_SESSIONS) return; + const oldest = [...all].sort((a, b) => (a.lastUsedAt ?? a.createdAt ?? '').localeCompare(b.lastUsedAt ?? b.createdAt ?? '')).slice(0, all.length - MAX_SESSIONS); + for (const x of oldest) await repo.deleteSession(x.token); + } + + private async clearPasswordLock(repo: SiteRepo, memberId: string) { + const pw = await repo.getCredential('pw_' + memberId).catch(() => null); + if (pw && (pw.fails || pw.lockedUntil)) await repo.saveCredential({ ...pw, fails: 0, lockedUntil: undefined }); + } + + private async currentSession(ctx: MemberCtx, token: string): Promise { + const s = await ctx.repo.getSession(await this.sessionKey(ctx.site, token)); + if (!s || s.memberId !== ctx.me.id) throw new RuleError('signed_out', 'Please sign in.', 401); + return s; + } + + private isRecent(s: MemberSession) { + const at = Math.max(Date.parse(s.createdAt ?? '') || 0, Date.parse(s.reauthAt ?? '') || 0); + return this.now().getTime() - at < REAUTH_WINDOW_MS; + } + + private async requireRecent(ctx: MemberCtx, token: string) { + if (!this.isRecent(await this.currentSession(ctx, token))) { + throw new RuleError('reauth_needed', "For your security, confirm it's you first. We'll send a code to your email.", 403); + } + } + + private async contactOf(site: Site, m: Member): Promise<{ channel: 'email' | 'phone'; target: string } | null> { + const crypto = this.crypto(site); + if (m.emailEnc) return { channel: 'email', target: await crypto.decrypt(m.emailEnc) }; + if (m.phoneEnc) return { channel: 'phone', target: await crypto.decrypt(m.phoneEnc) }; + return null; + } + + private async securityNotice(ctx: MemberCtx, change: SecurityChange) { + if (!ctx.me.emailEnc || ctx.me.emailBouncedAt || !this.deps.notifier.sendSecurityNotice) return; + try { + const email = await this.crypto(ctx.site).decrypt(ctx.me.emailEnc); + await this.deps.notifier.sendSecurityNotice({ site: ctx.site, email, change }); + await this.deps.control.logMail({ siteId: ctx.site.id, kind: 'notice', at: this.iso() }).catch(() => {}); + } catch (e) { console.error('[security-notice]', ctx.site.id, (e as Error).message); } + } + + async security(ctx: MemberCtx, token: string): Promise { + const cur = await this.currentSession(ctx, token); + const creds = await ctx.repo.listCredentials(ctx.me.id); + const pw = creds.find((c) => c.kind === 'password'); + const sessions = (await ctx.repo.listSessionsOf(ctx.me.id)).filter((s) => Date.parse(s.expiresAt) > this.now().getTime()); + return { + hasPassword: !!pw, passwordSetAt: pw?.createdAt, + passkeysAvailable: !!this.deps.passkeys, + passkeys: creds.filter((c) => c.kind === 'passkey' && c.passkey).map((c) => ({ id: c.id, name: c.passkey!.name, createdAt: c.createdAt, lastUsedAt: c.lastUsedAt })), + devices: sessions + .sort((a, b) => (b.lastUsedAt ?? '').localeCompare(a.lastUsedAt ?? '')) + .map((s) => ({ id: s.id ?? '', device: s.device ?? 'Signed in before November 2026', method: s.method, createdAt: s.createdAt, lastUsedAt: s.lastUsedAt, current: s.token === cur.token })), + recent: this.isRecent(cur), + }; + } + + /** Sends a code to the member's own email (or phone) so they can confirm it's them before changing sign-in options. */ + async reauthStart(ctx: MemberCtx, meta: { ip?: string } = {}) { + const contact = await this.contactOf(ctx.site, ctx.me); + if (!contact) throw new RuleError('no_contact', 'This account has no email or phone to send a code to.'); + return this.startVerification(ctx.site, contact.channel, contact.target, meta); + } + + /** Confirms it's them with that code, or with their current password. Lasts 30 minutes on this device. */ + async reauth(ctx: MemberCtx, token: string, input: { challengeId?: string; code?: string; password?: string }, meta: { ip?: string } = {}) { + const s = await this.currentSession(ctx, token); + if (input.password) { + await this.checkPassword(ctx.site, ctx.repo, ctx.me.id, input.password, meta); + } else { + const c = await this.consumeChallenge(ctx.site, String(input.challengeId ?? ''), String(input.code ?? '')); + const mine = c.channel === 'email' ? ctx.me.emailHash : ctx.me.phoneHash; + if (!mine || c.targetHash !== mine) throw new RuleError('code_invalid', 'That code was not sent to this account.'); + } + await ctx.repo.saveSession({ ...s, reauthAt: this.iso() }); + return { ok: true }; + } + + async setPassword(ctx: MemberCtx, token: string, password: string) { + await this.requireRecent(ctx, token); + const contact = await this.contactOf(ctx.site, ctx.me); + checkPasswordStrength(password, { email: contact?.channel === 'email' ? contact.target : undefined, siteName: ctx.site.name }); + const id = 'pw_' + ctx.me.id; + const had = await ctx.repo.getCredential(id); + await ctx.repo.saveCredential({ id, memberId: ctx.me.id, kind: 'password', createdAt: this.iso(), hash: await this.hasher().hash(password), fails: 0 }); + // A new password signs out every other device, in case someone else knew the old one. + if (had) await this.signOutOthers(ctx, token); + await this.securityNotice(ctx, had ? 'password_changed' : 'password_set'); + this.changed(); + return this.security(ctx, token); + } + + async removePassword(ctx: MemberCtx, token: string) { + const id = 'pw_' + ctx.me.id; + if (await ctx.repo.getCredential(id)) { + await ctx.repo.deleteCredential(id); + await this.securityNotice(ctx, 'password_removed'); + this.changed(); + } + return this.security(ctx, token); + } + + /** Checks a member's password, counting wrong tries. Same error for "no password" and "wrong password". */ + private async checkPassword(site: Site, repo: SiteRepo, memberId: string | null, password: string, meta: { ip?: string }) { + const pw = memberId ? await repo.getCredential('pw_' + memberId) : null; + const wrong = new RuleError('password_wrong', "That email and password don't match. You can sign in with an emailed code instead.", 401); + if (pw?.lockedUntil && Date.parse(pw.lockedUntil) > this.now().getTime()) { + const mins = Math.max(1, Math.ceil((Date.parse(pw.lockedUntil) - this.now().getTime()) / 60_000)); + throw new RuleError('password_locked', `Too many wrong passwords. Sign in with an emailed code, or try your password again in ${mins} minute${mins === 1 ? '' : 's'}.`, 429); + } + if (!pw?.hash) { + this.dummyHash ??= this.hasher().hash(randomId()); + await this.hasher().verify(await this.dummyHash, password).catch(() => false); // same time either way, so the form doesn't reveal who has a password + throw wrong; + } + if (!(await this.hasher().verify(pw.hash, password))) { + const fails = (pw.fails ?? 0) + 1; + const lock = passwordLockMs(fails); + await repo.saveCredential({ ...pw, fails, lockedUntil: lock ? new Date(this.now().getTime() + lock).toISOString() : pw.lockedUntil }); + if (lock && fails % PASSWORD_LOCK_AFTER === 0) console.warn('[password] locked after wrong tries', site.id, `${Math.round(lock / 60_000)} min`); + throw wrong; + } + await repo.saveCredential({ ...pw, fails: 0, lockedUntil: undefined, lastUsedAt: this.iso() }); + } + + async signInWithPassword(site: Site, rawEmail: string, password: string, meta: SignInMeta = {}) { + const email = normalizeTarget('email', rawEmail); + const crypto = this.crypto(site); + const emailHash = await crypto.lookupHash(email); + if (meta.ip) await this.limit(`pw-ip:${meta.ip}`, 3600, 60, 'Too many sign-in attempts from this network. Try again later.'); + await this.limit(`pw:${site.id}:${emailHash}`, 3600, 20, 'Too many tries for this email. Sign in with an emailed code instead.'); + if (!password) throw new RuleError('password_wrong', 'Enter your password.', 400); + const repo = await this.repo(site); + const member = await repo.findMemberByHash('email', emailHash); + await this.checkPassword(site, repo, member?.id ?? null, password, meta); + if (member!.status !== 'suspended') await this.noteNetwork(site, repo, member!, meta.ip); + return this.startSession(site, member!, false, { ...meta, method: 'password' }); + } + + // Passkey challenges are signed and short-lived instead of stored; each can be used once. + private async passkeyTicket(site: Site, challenge: string, purpose: 'reg' | 'auth', memberId = '') { + const exp = this.now().getTime() + 5 * 60_000; + const body = `${purpose}.${exp}.${memberId}.${challenge}`; + return `${body}.${await hmacHex(await this.keys.siteKey(site.id), 'passkey:' + body)}`; + } + private async openTicket(site: Site, ticket: string, purpose: 'reg' | 'auth', memberId = '') { + const parts = String(ticket ?? '').split('.'); + const bad = new RuleError('passkey_expired', 'That took too long. Please try again.', 400); + if (parts.length !== 5) throw bad; + const [p, exp, mid, challenge, sig] = parts; + const body = `${p}.${exp}.${mid}.${challenge}`; + if (sig !== (await hmacHex(await this.keys.siteKey(site.id), 'passkey:' + body))) throw bad; + if (p !== purpose || mid !== memberId || Number(exp) < this.now().getTime()) throw bad; + if ((await this.deps.control.hit(`passkey-used:${site.id}:${challenge}`, 600, this.iso())) > 1) throw bad; + return challenge; + } + private passkeysOn() { + if (!this.deps.passkeys) throw new RuleError('passkeys_off', 'Passkeys are not available here yet.', 400); + return this.deps.passkeys; + } + + async passkeyRegisterStart(ctx: MemberCtx, token: string) { + const pk = this.passkeysOn(); + await this.requireRecent(ctx, token); + const existing = (await ctx.repo.listCredentials(ctx.me.id)).filter((c) => c.passkey); + const contact = await this.contactOf(ctx.site, ctx.me); + const { options, challenge } = await pk.registrationOptions(ctx.site, { + userId: ctx.me.id, + userName: contact?.target ?? (ctx.me.displayName || 'member'), + exclude: existing.map((c) => ({ id: c.passkey!.credentialId, transports: c.passkey!.transports })), + }); + return { options, ticket: await this.passkeyTicket(ctx.site, challenge, 'reg', ctx.me.id) }; + } + + async passkeyRegisterFinish(ctx: MemberCtx, token: string, ticket: string, response: unknown, name?: string) { + const pk = this.passkeysOn(); + await this.requireRecent(ctx, token); + const challenge = await this.openTicket(ctx.site, ticket, 'reg', ctx.me.id); + let v: Awaited>; + try { v = await pk.verifyRegistration(ctx.site, response, challenge); } + catch { throw new RuleError('passkey_failed', "We couldn't save that passkey. Please try again.", 400); } + const label = (name ?? '').trim().slice(0, 40) || 'Passkey'; + const cred: MemberCredential = { + id: 'pk_' + v.credentialId, memberId: ctx.me.id, kind: 'passkey', createdAt: this.iso(), + passkey: { credentialId: v.credentialId, publicKey: v.publicKey, counter: v.counter, transports: v.transports, name: label, backedUp: v.backedUp }, + }; + const clash = await ctx.repo.getCredential(cred.id); + if (clash && clash.memberId !== ctx.me.id) throw new RuleError('passkey_failed', "We couldn't save that passkey. Please try again.", 400); + await ctx.repo.saveCredential(cred); + await this.securityNotice(ctx, 'passkey_added'); + this.changed(); + return this.security(ctx, token); + } + + async removePasskey(ctx: MemberCtx, token: string, id: string) { + const c = await ctx.repo.getCredential(id); + if (c && c.memberId === ctx.me.id && c.kind === 'passkey') { + await ctx.repo.deleteCredential(id); + await this.securityNotice(ctx, 'passkey_removed'); + this.changed(); + } + return this.security(ctx, token); + } + + async passkeySignInStart(site: Site, meta: { ip?: string } = {}) { + const pk = this.passkeysOn(); + if (meta.ip) await this.limit(`passkey-ip:${meta.ip}`, 3600, 120, 'Too many sign-in attempts from this network. Try again later.'); + const { options, challenge } = await pk.authenticationOptions(site); + return { options, ticket: await this.passkeyTicket(site, challenge, 'auth') }; + } + + async signInWithPasskey(site: Site, ticket: string, response: unknown, meta: SignInMeta = {}) { + const pk = this.passkeysOn(); + const challenge = await this.openTicket(site, ticket, 'auth'); + const credId = typeof (response as { id?: unknown })?.id === 'string' ? (response as { id: string }).id : ''; + const repo = await this.repo(site); + const cred = credId ? await repo.getCredential('pk_' + credId) : null; + const unknown = new RuleError('passkey_unknown', "We don't recognise that passkey here. Sign in with an emailed code, then add a passkey in Settings.", 401); + if (!cred?.passkey) throw unknown; + let v: { newCounter: number }; + try { v = await pk.verifyAuthentication(site, response, challenge, cred.passkey); } + catch { throw new RuleError('passkey_failed', "That passkey didn't work. Try again, or sign in with an emailed code.", 401); } + await repo.saveCredential({ ...cred, lastUsedAt: this.iso(), passkey: { ...cred.passkey, counter: v.newCounter } }); + const member = await repo.getMember(cred.memberId); + if (!member) throw unknown; + if (member.status !== 'suspended') await this.noteNetwork(site, repo, member, meta.ip); + return this.startSession(site, member, false, { ...meta, method: 'passkey' }); + } + + async signOutDevice(ctx: MemberCtx, token: string, id: string) { + const cur = await this.currentSession(ctx, token); + for (const s of await ctx.repo.listSessionsOf(ctx.me.id)) if (s.id === id && s.token !== cur.token) await ctx.repo.deleteSession(s.token); + this.changed(); + return this.security(ctx, token); + } + + async signOutOthers(ctx: MemberCtx, token: string) { + const cur = await this.currentSession(ctx, token); + for (const s of await ctx.repo.listSessionsOf(ctx.me.id)) if (s.token !== cur.token) await ctx.repo.deleteSession(s.token); + this.changed(); + return this.security(ctx, token); + } + + /** Signs out every device, this one too. */ + async signOutEverywhere(ctx: MemberCtx) { + await ctx.repo.deleteSessionsOf(ctx.me.id); + this.changed(); + return { ok: true }; + } + private requireComplete(ctx: MemberCtx) { if (!ctx.me.profileComplete) throw new RuleError('profile_incomplete', 'Finish your profile first.', 403); } @@ -1450,7 +1734,8 @@ export class Platform { } await this.deps.control.deleteAdminChallenge(challengeId); const token = 'adm.' + randomId(); - await this.deps.control.saveAdminSession({ token: await this.adminSessionKey(token), adminId: c.adminId, expiresAt: new Date(this.now().getTime() + SESSION_TTL_MS).toISOString() }); + const now = this.iso(); + await this.deps.control.saveAdminSession({ token: await this.adminSessionKey(token), adminId: c.adminId, expiresAt: new Date(this.now().getTime() + ADMIN_SESSION_IDLE_MS).toISOString(), createdAt: now, lastUsedAt: now }); const who = await this.deps.control.getAdmin(c.adminId); if (who) await this.audit(who, 'admin.sign_in'); this.changed(); @@ -1463,9 +1748,23 @@ export class Platform { if (!s || Date.parse(s.expiresAt) < this.now().getTime()) throw new RuleError('signed_out', 'Please sign in.', 401); const a = await this.deps.control.getAdmin(s.adminId); if (!a) throw new RuleError('signed_out', 'Please sign in.', 401); + // Admins stay signed in while they use the admin at least once every 30 days. + if (this.now().getTime() - Date.parse(s.lastUsedAt ?? '1970-01-01') > SESSION_TOUCH_MS) { + await this.deps.control.saveAdminSession({ ...s, lastUsedAt: this.iso(), expiresAt: new Date(this.now().getTime() + ADMIN_SESSION_IDLE_MS).toISOString() }).catch(() => {}); + } return a; } + async adminSignOut(token: string | null | undefined, everywhere = false) { + if (!token) return { ok: true }; + const key = await this.adminSessionKey(token); + const s = await this.deps.control.getAdminSession(key); + if (s && everywhere) await this.deps.control.deleteAdminSessionsOf(s.adminId); + else await this.deps.control.deleteAdminSession(key); + this.changed(); + return { ok: true }; + } + async adminSites(admin: AdminUser) { const all = await this.deps.control.listSites(); const sites = admin.role === 'platform' ? all : all.filter((s) => admin.siteIds.includes(s.id)); diff --git a/packages/core/src/signin.ts b/packages/core/src/signin.ts new file mode 100644 index 0000000..4b17fee --- /dev/null +++ b/packages/core/src/signin.ts @@ -0,0 +1,126 @@ +// Faster sign-in for returning members: how long a device stays signed in, optional passwords and +// passkeys. The emailed code always keeps working, as the fallback and for recovery. +import type { PasswordHasher, SecurityChange } from './repo'; +import { RuleError } from './rules'; +import type { ClientPlatform, Site } from './types'; + +const DAY = 86_400_000; +/** A member's own device stays signed in while it is used at least once every 90 days. */ +export const MEMBER_SESSION_IDLE_MS = 90 * DAY; +/** "Not my device": signed out after 12 hours, however much it is used. */ +export const SHORT_SESSION_MS = 12 * 3_600_000; +/** Owner and Platform Admins: signed out after 30 days without use. */ +export const ADMIN_SESSION_IDLE_MS = 30 * DAY; +/** Sliding expiry is written at most this often, so ordinary requests don't all write to the database. */ +export const SESSION_TOUCH_MS = DAY; +/** Adding a password or passkey needs a sign-in or confirmation this recent on that device. */ +export const REAUTH_WINDOW_MS = 30 * 60_000; +/** Oldest sessions beyond this many per member are signed out. */ +export const MAX_SESSIONS = 20; + +export const PASSWORD_MIN = 10; +export const PASSWORD_MAX = 128; +/** Wrong passwords in a row before the account is locked for a while (the emailed code still works). */ +export const PASSWORD_LOCK_AFTER = 5; + +/** How long to lock password sign-in after `fails` wrong tries in a row: 15 minutes, doubling each round, at most a day. */ +export function passwordLockMs(fails: number): number { + if (fails < PASSWORD_LOCK_AFTER) return 0; + const round = Math.floor(fails / PASSWORD_LOCK_AFTER) - 1; + return Math.min(15 * 60_000 * 2 ** round, DAY); +} + +// The most common passwords that are 10+ characters. Anything on this list is refused. +const COMMON = new Set([ + '1234567890', '0123456789', '0987654321', '1111111111', '1q2w3e4r5t', 'qwertyuiop', 'password12', 'password123', + 'password1234', 'iloveyou12', 'iloveyou123', 'qwerty1234', 'qwerty12345', 'abc1234567', 'abcdefghij', 'letmein123', + 'welcome123', 'welcome1234', 'football123', 'baseball123', 'princess123', 'sunshine123', 'superman123', 'trustno1234', + 'changeme123', 'passw0rd123', 'p@ssw0rd123', 'p@ssword123', 'administrator', 'aaaaaaaaaa', '1234554321', '1q2w3e4r5t6y', + 'zaq12wsxcde', 'qazwsxedcrfv', 'asdfghjkl1', 'asdfghjkl;', 'mypassword', 'mypassword1', 'mypassword123', 'secret1234', +]); + +/** Throws a friendly RuleError when the password is too weak. */ +export function checkPasswordStrength(password: string, ctx: { email?: string; siteName?: string } = {}) { + if (password.length < PASSWORD_MIN) throw new RuleError('weak_password', `Use at least ${PASSWORD_MIN} characters. A short phrase is easiest to remember.`); + if (password.length > PASSWORD_MAX) throw new RuleError('weak_password', `Use at most ${PASSWORD_MAX} characters.`); + const lower = password.toLowerCase(); + if (COMMON.has(lower) || /^(.)\1+$/.test(password) || /^(?:0123456789|1234567890|abcdefghij)+/.test(lower)) { + throw new RuleError('weak_password', 'That password is too common. Try a short phrase only you would know.'); + } + const local = ctx.email?.split('@')[0]?.toLowerCase(); + if (local && local.length >= 4 && lower.includes(local)) throw new RuleError('weak_password', "Don't use your email address in your password."); + const site = ctx.siteName?.toLowerCase().replace(/\s+/g, ''); + if (site && lower.replace(/[^a-z]/g, '').startsWith(site) && lower.length < site.length + 6) { + throw new RuleError('weak_password', "Don't base your password on the site's name."); + } +} + +const te = new TextEncoder(); +function b64(bytes: Uint8Array) { let s = ''; for (const b of bytes) s += String.fromCharCode(b); return btoa(s); } +function unb64(s: string) { const bin = atob(s); const o = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) o[i] = bin.charCodeAt(i); return o; } + +/** PBKDF2-SHA256 from WebCrypto, for the preview and tests (the API uses argon2id). Format: pbkdf2$$$. */ +export class Pbkdf2Hasher implements PasswordHasher { + constructor(private iterations = 210_000) {} + private async derive(password: string, salt: Uint8Array, iterations: number) { + const subtle = (globalThis as any).crypto.subtle as SubtleCrypto; + const key = await subtle.importKey('raw', te.encode(password.normalize('NFKC')), 'PBKDF2', false, ['deriveBits']); + return new Uint8Array(await subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt: salt as BufferSource, iterations }, key, 256)); + } + async hash(password: string) { + const salt = new Uint8Array(16); + (globalThis as any).crypto.getRandomValues(salt); + return `pbkdf2$${this.iterations}$${b64(salt)}$${b64(await this.derive(password, salt, this.iterations))}`; + } + async verify(stored: string, password: string) { + const [kind, it, salt, hash] = stored.split('$'); + if (kind !== 'pbkdf2' || !it || !salt || !hash) return false; + const got = await this.derive(password, unb64(salt), Number(it)); + const want = unb64(hash); + if (got.length !== want.length) return false; + let diff = 0; + for (let i = 0; i < got.length; i++) diff |= got[i] ^ want[i]; + return diff === 0; + } +} + +/** A short, human name for a signed-in device, from the app platform and browser user agent. No version numbers. */ +export function deviceLabel(platform: ClientPlatform | undefined, userAgent: string | undefined): string { + if (platform === 'ios') return 'iPhone or iPad app'; + if (platform === 'android') return 'Android app'; + const ua = userAgent ?? ''; + const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) ? 'iPad' : /Android/.test(ua) ? 'Android' + : /Windows/.test(ua) ? 'Windows' : /Macintosh|Mac OS X/.test(ua) ? 'Mac' : /CrOS/.test(ua) ? 'Chromebook' : /Linux/.test(ua) ? 'Linux' : ''; + const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\/|Opera/.test(ua) ? 'Opera' : /Firefox\/|FxiOS/.test(ua) ? 'Firefox' + : /SamsungBrowser/.test(ua) ? 'Samsung Internet' : /Chrome\/|CriOS/.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : ''; + if (browser && os) return `${browser} on ${os}`; + return browser || os || 'Web browser'; +} + +/** The email sent when sign-in options change, so a member notices if someone else did it. */ +export function securityNoticeContent(site: Site, change: SecurityChange) { + const what: Record = { + password_set: 'A password was added to your account', + password_changed: 'Your password was changed', + password_removed: 'Your password was removed', + passkey_added: 'A passkey (Face ID, fingerprint or device PIN) was added to your account', + passkey_removed: 'A passkey was removed from your account', + }; + const line = what[change]; + const subject = `${site.name}: your sign-in settings changed`; + const text = `${line}.\n\nIf this was you, there is nothing to do.\n\nIf it wasn't you, sign in with a code sent to this email, open Settings, remove anything you don't recognise and choose "Sign out everywhere". Then reply to this email so we can help.`; + const html = `

${line}.

If this was you, there is nothing to do.

If it wasn't you, sign in with a code sent to this email, open Settings, remove anything you don't recognise and choose Sign out everywhere. Then reply to this email so we can help.

`; + return { subject, text, html }; +} + +/** What a member sees under Settings > Sign-in and security. */ +export interface SecurityInfo { + hasPassword: boolean; + passwordSetAt?: string; + passkeysAvailable: boolean; // false where the server has no passkey support (preview) + passkeys: { id: string; name: string; createdAt: string; lastUsedAt?: string }[]; + devices: { id: string; device: string; method?: string; createdAt?: string; lastUsedAt?: string; current: boolean }[]; + /** Signed in or confirmed on this device in the last 30 minutes, so passwords and passkeys can be added without a new code. */ + recent: boolean; +} +export interface SignInOptions { remember?: boolean } diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 5d78fe2..aaf1ee6 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -586,6 +586,8 @@ export interface PublicSite { nicheIncludeLabel?: string; /** Present only when the owner turned Google tags on. restricted: sensitive site, no ad personalization or Google signals. */ googleTags?: { ga4Id?: string; adsId?: string; adsJoinLabel?: string; restricted: boolean }; + /** Sign-in options besides the emailed code. Passkeys need server support (not in the preview). */ + signIn?: { password: boolean; passkeys: boolean }; } export interface SearchFilters { diff --git a/packages/core/test/signin.test.ts b/packages/core/test/signin.test.ts new file mode 100644 index 0000000..6e64e5f --- /dev/null +++ b/packages/core/test/signin.test.ts @@ -0,0 +1,207 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + ApiError, checkPasswordStrength, createLocalAdminApi, createLocalMemberApi, createMemoryPlatform, DEMO_MEMBER_EMAIL, DEMO_OWNER_EMAIL, + deviceLabel, passwordLockMs, Pbkdf2Hasher, type PasskeyVerifier, +} from '../src/index'; + +const DAY = 86_400_000; + +function clockAt(start = Date.parse('2026-12-01T12:00:00Z')) { + let t = start; + return { now: () => new Date(t), advance: (ms: number) => { t += ms; } }; +} + +// Stands in for @simplewebauthn/server: a "response" is just { id, challenge, sig: 'ok' }. +const fakePasskeys: PasskeyVerifier = { + async registrationOptions(_site, a) { return { options: { user: a.userName, exclude: a.exclude.length }, challenge: 'reg' + Math.random().toString(36).slice(2) }; }, + async verifyRegistration(_site, response: any, challenge) { + if (response.challenge !== challenge) throw new Error('challenge'); + return { credentialId: response.id, publicKey: 'pk-' + response.id, counter: 0 }; + }, + async authenticationOptions() { return { options: {}, challenge: 'auth' + Math.random().toString(36).slice(2) }; }, + async verifyAuthentication(_site, response: any, challenge, cred) { + if (response.challenge !== challenge || response.sig !== 'ok' || cred.publicKey !== 'pk-' + response.id) throw new Error('bad'); + return { newCounter: cred.counter + 1 }; + }, +}; + +async function setup(opts: { passkeys?: boolean } = {}) { + const clock = clockAt(); + const mp = await createMemoryPlatform({ clock, passkeys: opts.passkeys ? fakePasskeys : undefined, passwords: new Pbkdf2Hasher(1000) }); + const api = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const s = await api.startVerification('email', DEMO_MEMBER_EMAIL); + const { token } = await api.verify(s.challengeId, s.devCode!); + api.setToken(token); + return { mp, api, clock, token }; +} + +test('a device stays signed in for 90 days from its last use, not 30 from sign-in', async () => { + const { api, clock } = await setup(); + clock.advance(80 * DAY); + await api.me(); // used on day 80: pushed out to day 170 + clock.advance(80 * DAY); + assert.ok((await api.me()).member.id); + clock.advance(91 * DAY); + await assert.rejects(api.me(), /sign in/i); +}); + +test('"not my device" ends after 12 hours however much it is used', async () => { + const { mp, clock } = await setup(); + const api = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const s = await api.startVerification('email', DEMO_MEMBER_EMAIL); + api.setToken((await api.verify(s.challengeId, s.devCode!, { remember: false })).token); + clock.advance(11 * 3_600_000); + await api.me(); + clock.advance(2 * 3_600_000); + await assert.rejects(api.me(), /sign in/i); +}); + +test('password: weak ones are refused, then sign in with it; wrong tries lock it but the code still works', async () => { + const { api, mp, clock } = await setup(); + await assert.rejects(api.setPassword('short'), /at least 10/); + await assert.rejects(api.setPassword('password123'), /too common/); + await assert.rejects(api.setPassword('alex-is-my-name'), /email address/); + const sec = await api.setPassword('blue kettle sings'); + assert.equal(sec.hasPassword, true); + assert.deepEqual(mp.sentSecurity.map((x) => x.change), ['password_set']); + // never sent to the app + assert.ok(!JSON.stringify(await api.me()).includes('pbkdf2')); + + const other = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const ok = await other.signInWithPassword('ALEX@example.com ', 'blue kettle sings'); + other.setToken(ok.token); + assert.equal((await other.me()).member.id, (await api.me()).member.id); + + for (let i = 0; i < 5; i++) await assert.rejects(other.signInWithPassword(DEMO_MEMBER_EMAIL, 'wrong password ' + i), /don't match/); + await assert.rejects(other.signInWithPassword(DEMO_MEMBER_EMAIL, 'blue kettle sings'), /Too many wrong passwords/); + clock.advance(16 * 60_000); + await other.signInWithPassword(DEMO_MEMBER_EMAIL, 'blue kettle sings'); + // an emailed code clears a lock straight away + for (let i = 0; i < 5; i++) await assert.rejects(other.signInWithPassword(DEMO_MEMBER_EMAIL, 'nope nope ' + i)); + const c = await other.startVerification('email', DEMO_MEMBER_EMAIL); + await other.verify(c.challengeId, c.devCode!); + await other.signInWithPassword(DEMO_MEMBER_EMAIL, 'blue kettle sings'); +}); + +test('password sign-in gives the same answer for unknown emails and accounts without a password', async () => { + const { mp } = await setup(); + const api = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const a = await api.signInWithPassword('nobody@example.com', 'whatever whatever').catch((e) => e); + const b = await api.signInWithPassword(DEMO_MEMBER_EMAIL, 'whatever whatever').catch((e) => e); + assert.ok(a instanceof ApiError && b instanceof ApiError); + assert.equal(a.message, b.message); +}); + +test('adding a password later needs a fresh code; changing it signs out other devices', async () => { + const { api, mp, clock } = await setup(); + await api.setPassword('first long password'); + const phone = createLocalMemberApi(mp.platform, 'afterh', 'ios'); + phone.setToken((await phone.signInWithPassword(DEMO_MEMBER_EMAIL, 'first long password')).token); + clock.advance(2 * 3_600_000); + await assert.rejects(api.setPassword('second long password'), (e: ApiError) => e.code === 'reauth_needed'); + await assert.rejects(api.reauth({ password: 'not it at all' }), /don't match/); + await api.reauth({ password: 'first long password' }); + await api.setPassword('second long password'); + await assert.rejects(phone.me(), /sign in/i); + assert.ok(await api.me()); + clock.advance(2 * 3_600_000); + const r = await api.reauthStart(); + await api.reauth({ challengeId: r.challengeId, code: r.devCode }); + const sec = await api.removePassword(); + assert.equal(sec.hasPassword, false); + assert.deepEqual(mp.sentSecurity.map((x) => x.change), ['password_set', 'password_changed', 'password_removed']); +}); + +test("a code for someone else's email can't confirm this account", async () => { + const { api, mp, clock } = await setup(); + clock.advance(2 * 3_600_000); + const stranger = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const s = await stranger.startVerification('email', 'someone.else@example.com'); + await assert.rejects(api.reauth({ challengeId: s.challengeId, code: s.devCode }), /not sent to this account/); +}); + +test('devices: listed by name, sign out one, sign out others, sign out everywhere', async () => { + const { api, mp } = await setup(); + const phone = createLocalMemberApi(mp.platform, 'afterh', 'ios'); + const s = await phone.startVerification('email', DEMO_MEMBER_EMAIL); + phone.setToken((await phone.verify(s.challengeId, s.devCode!)).token); + let sec = await api.security(); + assert.equal(sec.devices.length, 2); + assert.ok(sec.devices.some((d) => d.current && d.method === 'code')); + const app = sec.devices.find((d) => d.device === 'iPhone or iPad app')!; + sec = await api.signOutDevice(app.id); + assert.equal(sec.devices.length, 1); + await assert.rejects(phone.me(), /sign in/i); + await api.signOutEverywhere(); + await assert.rejects(api.me(), /sign in/i); +}); + +test('passkeys: add one, sign in with it without email, remove it', async () => { + const { api, mp } = await setup({ passkeys: true }); + assert.equal((await api.site()).signIn?.passkeys, true); + const reg = await api.passkeyRegisterOptions(); + const challenge = reg.ticket.split('.')[3]; + let sec = await api.addPasskey(reg.ticket, { id: 'cred1', challenge }, 'My iPhone'); + assert.equal(sec.passkeys[0].name, 'My iPhone'); + assert.deepEqual(mp.sentSecurity.map((x) => x.change), ['passkey_added']); + // the same ticket can't be used twice + await assert.rejects(api.addPasskey(reg.ticket, { id: 'cred2', challenge }), /try again/); + + const fresh = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const o = await fresh.passkeyOptions(); + const ac = o.ticket.split('.')[3]; + await assert.rejects(fresh.signInWithPasskey(o.ticket, { id: 'cred1', challenge: ac, sig: 'forged' }), /didn't work/); + const o2 = await fresh.passkeyOptions(); + const r = await fresh.signInWithPasskey(o2.ticket, { id: 'cred1', challenge: o2.ticket.split('.')[3], sig: 'ok' }); + fresh.setToken(r.token); + sec = await fresh.security(); + assert.equal(sec.devices.find((d) => d.current)?.method, 'passkey'); + assert.ok(sec.passkeys[0].lastUsedAt); + + sec = await fresh.removePasskey(sec.passkeys[0].id); + assert.equal(sec.passkeys.length, 0); + const o3 = await fresh.passkeyOptions(); + await assert.rejects(fresh.signInWithPasskey(o3.ticket, { id: 'cred1', challenge: o3.ticket.split('.')[3], sig: 'ok' }), /don't recognise/); +}); + +test('passkeys are a site-by-site thing: a ticket from one site is refused on another', async () => { + const { mp } = await setup({ passkeys: true }); + const a = createLocalMemberApi(mp.platform, 'afterh', 'web'); + const b = createLocalMemberApi(mp.platform, 'hfriends', 'web'); + const o = await a.passkeyOptions(); + await assert.rejects(b.signInWithPasskey(o.ticket, { id: 'x', challenge: o.ticket.split('.')[3], sig: 'ok' }), /try again/); +}); + +test('the preview has no passkeys and says so', async () => { + const { api } = await setup(); + assert.equal((await api.site()).signIn?.passkeys, false); + await assert.rejects(api.passkeyOptions(), /not available/); +}); + +test('admins stay signed in 30 days from last use and can sign out everywhere', async () => { + const clock = clockAt(); + const mp = await createMemoryPlatform({ clock }); + const one = createLocalAdminApi(mp.platform), two = createLocalAdminApi(mp.platform); + for (const a of [one, two]) { const s = await a.start(DEMO_OWNER_EMAIL); a.setToken((await a.verify(s.challengeId, s.devCode!)).token); } + clock.advance(25 * DAY); + await one.me(); + clock.advance(25 * DAY); + assert.ok(await one.me()); + await assert.rejects(two.me(), /sign in/i); + const s = await two.start(DEMO_OWNER_EMAIL); two.setToken((await two.verify(s.challengeId, s.devCode!)).token); + await one.signOut(true); + await assert.rejects(two.me(), /sign in/i); +}); + +test('helpers: lock times, device names, strength', () => { + assert.equal(passwordLockMs(4), 0); + assert.equal(passwordLockMs(5), 15 * 60_000); + assert.equal(passwordLockMs(10), 30 * 60_000); + assert.equal(passwordLockMs(100), DAY); + assert.equal(deviceLabel('web', 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'), 'Safari on iPhone'); + assert.equal(deviceLabel('web', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36 Edg/140.0'), 'Edge on Windows'); + assert.equal(deviceLabel('android', ''), 'Android app'); + assert.doesNotThrow(() => checkPasswordStrength('correct horse battery')); + assert.throws(() => checkPasswordStrength('aaaaaaaaaaaa'), /too common/); +});