Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```
Expand Down
2 changes: 2 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
14 changes: 14 additions & 0 deletions apps/api/scripts/smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')!;
Expand Down
5 changes: 5 additions & 0 deletions apps/api/sql/control.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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);
13 changes: 13 additions & 0 deletions apps/api/sql/site.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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_<member id> or pk_<credential id>
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);
51 changes: 48 additions & 3 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -59,10 +66,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 }) {
Expand Down Expand Up @@ -108,6 +127,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); }
Expand Down Expand Up @@ -200,6 +244,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) };
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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,
Expand Down
16 changes: 15 additions & 1 deletion apps/api/src/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)'}`);
},
Expand Down Expand Up @@ -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 ?? []) {
Expand Down
68 changes: 68 additions & 0 deletions apps/api/src/passkeys.ts
Original file line number Diff line number Diff line change
@@ -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;
}
16 changes: 16 additions & 0 deletions apps/api/src/passwords.ts
Original file line number Diff line number Diff line change
@@ -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; }
}
}
Loading
Loading