Sign people in by a proven email, with a display name, and Google's email
Before adoption: this commit came in with the history the project adopted, so no landing records it.
An account is written only once the code mailed to its address comes back: the pending sign-up is sealed into the form with the code's HMAC under the cookie key, so no code is stored. Sign-in takes an email or a handle; an account made before emails adds and proves one before its grant. A password resets by a mailed code, and reads the same for an address no account has. Google asks for email and profile, links to the account that proved the same address, and a new person sets a handle and display name. Mail goes through a Mailer port over Email Service's send_email binding, with a memory adapter.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+2831 added−375 removed
- tests:+1321 added−146 removed
- other:+1510 added−229 removed
Provenance
- Commit
125964c- Tree
939194a- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
78a5062
28 files changed+2831 added−375 removed
added:apps/platform/migrations/0006_account_email.sql+11 added
1+-- An account's email and display name. `email` is always one whose owner2+-- proved it: sign-up writes the account only after the code mailed to it3+-- came back, and Google's address only when Google says it verified it.4+-- `email_key` is the address lowercased, so two spellings are one address5+-- and a racing second sign-up fails on the index. Accounts made before this6+-- migration have neither until their person adds an email at sign-in; a7+-- unique index lets any number of rows hold NULL.8+ALTER TABLE accounts ADD COLUMN email TEXT;9+ALTER TABLE accounts ADD COLUMN email_key TEXT;10+ALTER TABLE accounts ADD COLUMN display_name TEXT;11+CREATE UNIQUE INDEX accounts_by_email ON accounts (email_key);modified:apps/platform/src/adapters/accounts-d1.ts+96 added-24 removed
12345567891011121314151617189192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172732021227475767778798026272829303132333481828384858687888990919293949596979899100101102103104105381061071081091101114041421121131141151164445464748491171181191201211221231241257 unmodified linesimport { Handle } from "@repo/protocol/ids";import { Array, Clock, Effect, Layer, Option, Schema } from "effect";import type { Types } from "effect";import { SqlClient } from "effect/sql/SqlClient";
import { Accounts, handleKey, HandleTaken } from "../auth/accounts.ts";import { Accounts, DisplayName, Email, EmailTaken, emailKey, handleKey, HandleTaken,} from "../auth/accounts.ts";import type { Account } from "../auth/accounts.ts";import { PasswordHash } from "../auth/password.ts";
const Rows = Schema.Array( Schema.Struct({ handle: Handle, password_hash: PasswordHash }) Schema.Struct({ display_name: Schema.NullOr(DisplayName), email: Schema.NullOr(Email), handle: Handle, password_hash: PasswordHash, }));
const decodeRows = Schema.decodeUnknownEffect(Rows);
// An account made before emails has neither column set.const accountOf = (row: (typeof Rows.Type)[number]): Account => { const account: Types.Mutable<Account> = { handle: row.handle, hash: row.password_hash, };
if (row.display_name !== null) { account.displayName = row.display_name; }
if (row.email !== null) { account.email = row.email; }
return account;};
const one = (rows: readonly unknown[]) => Effect.map(decodeRows(rows), (decoded) => Option.map(Array.head(decoded), accountOf) );
export const AccountsD1 = Layer.effect( Accounts, Effect.gen(function* () { const sql = yield* SqlClient;
const find = (handle: Handle) => sql` SELECT handle, password_hash, email, display_name FROM accounts WHERE handle_key = ${handleKey(handle)}`.pipe( Effect.flatMap(one), Effect.orDie );
const findByEmail = (email: Email) => sql` SELECT handle, password_hash, email, display_name FROM accounts WHERE email_key = ${emailKey(email)}`.pipe( Effect.flatMap(one), Effect.orDie );
return Accounts.of({ // One statement: a second sign-up under the same key inserts nothing // and returns no row, however the two race. create: (handle, hash) => // One statement: a second sign-up under the same handle or email // inserts nothing and returns no row, however the two race; which key // it lost on is read after. create: (account) => Effect.gen(function* () { const now = yield* Clock.currentTimeMillis;
yield* sql` INSERT INTO accounts (handle_key, handle, password_hash, created_at) VALUES (${handleKey(handle)}, ${handle}, ${hash}, ${now}) ON CONFLICT (handle_key) DO NOTHING RETURNING handle_key`.pipe( Effect.orDie, Effect.filterOrFail( (inserted) => inserted.length > 0, () => new HandleTaken({ handle }) const inserted = yield* sql` INSERT INTO accounts (handle_key, handle, password_hash, created_at, email, email_key, display_name) VALUES ( ${handleKey(account.handle)}, ${account.handle}, ${account.hash}, ${now}, ${account.email ?? null}, ${account.email === undefined ? null : emailKey(account.email)}, ${account.displayName ?? null} ) ON CONFLICT DO NOTHING RETURNING handle_key`.pipe(Effect.orDie);
const lost = Effect.flatMap( find(account.handle), (held): Effect.Effect<never, HandleTaken | EmailTaken> => Option.isSome(held) || account.email === undefined ? Effect.fail(new HandleTaken({ handle: account.handle })) : Effect.fail(new EmailTaken({ email: account.email })) );
return yield* inserted.length > 0 ? Effect.void : lost; }), find: (handle) => find, findByEmail, // `OR IGNORE` skips the row when another account holds the address, // so nothing comes back. setEmail: (handle, email) => sql` SELECT handle, password_hash FROM accounts WHERE handle_key = ${handleKey(handle)}`.pipe( Effect.flatMap(decodeRows), UPDATE OR IGNORE accounts SET email = ${email}, email_key = ${emailKey(email)} WHERE handle_key = ${handleKey(handle)} RETURNING handle_key`.pipe( Effect.orDie, Effect.map((rows) => Option.map(Array.head(rows), (row) => ({ handle: row.handle, hash: row.password_hash, })) ) Effect.filterOrFail( (updated) => updated.length > 0, () => new EmailTaken({ email }) ), Effect.asVoid ), setPasswordHash: (handle, hash) => sql` UPDATE accounts SET password_hash = ${hash}7 unmodified linesmodified:apps/platform/src/auth/accounts/memory.ts+84 added-15 removed
123456783491011121314151617181920212223242526271028293013313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081171819828384858687888990919293949596222397989910010127282930313210210310410510 unmodified linesimport { Effect, Layer, Option, Ref } from "effect";
import { Accounts, EmailTaken, emailKey, handleKey, HandleTaken,import { Accounts, handleKey, HandleTaken } from "../accounts.ts";import type { Account } from "../accounts.ts";} from "../accounts.ts";import type { Account, Email } from "../accounts.ts";
const holderOf = ( accounts: ReadonlyMap<string, Account>, email: Email): Option.Option<Account> => Option.fromUndefinedOr( [...accounts.values()].find( (account) => account.email !== undefined && emailKey(account.email) === emailKey(email) ) );
export const AccountsMemory = { layer: Layer.effect( Accounts, Effect.gen(function* () { const store = yield* Ref.make(new Map<string, Account>()); const store = yield* Ref.make<ReadonlyMap<string, Account>>(new Map());
return Accounts.of({ create: (handle, hash) => create: (account) => Effect.gen(function* () { const key = handleKey(account.handle);
const refused = yield* Ref.modify( store, ( accounts ): readonly [ Option.Option<HandleTaken | EmailTaken>, ReadonlyMap<string, Account>, ] => { if (accounts.has(key)) { return [ Option.some(new HandleTaken({ handle: account.handle })), accounts, ]; }
if ( account.email !== undefined && Option.isSome(holderOf(accounts, account.email)) ) { return [ Option.some(new EmailTaken({ email: account.email })), accounts, ]; }
return [Option.none(), new Map(accounts).set(key, account)]; } );
return yield* Option.isSome(refused) ? Effect.fail(refused.value) : Effect.void; }), find: (handle) => Ref.get(store).pipe( Effect.map((accounts) => Option.fromUndefinedOr(accounts.get(handleKey(handle))) ) ), findByEmail: (email) => Ref.get(store).pipe( Effect.map((accounts) => holderOf(accounts, email)) ), setEmail: (handle, email) => Ref.modify(store, (accounts) => { const key = handleKey(handle);
return accounts.has(key) ? [false, accounts] : [true, new Map(accounts).set(key, { handle, hash })]; const account = accounts.get(key);
const holder = holderOf(accounts, email);
// As D1's update, which changes no row for a handle nobody holds. if ( account === undefined || Option.exists(holder, (held) => handleKey(held.handle) !== key) ) { return [false, accounts]; }
return [true, new Map(accounts).set(key, { ...account, email })]; }).pipe( Effect.filterOrFail( (created) => created, () => new HandleTaken({ handle }) (set) => set, () => new EmailTaken({ email }) ), Effect.asVoid ), find: (handle) => Ref.get(store).pipe( Effect.map((accounts) => Option.fromUndefinedOr(accounts.get(handleKey(handle))) ) ), setPasswordHash: (handle, hash) => Ref.update(store, (accounts) => { const key = handleKey(handle);
10 unmodified linesadded:apps/platform/src/auth/mailer/binding.ts+29 added
1234567891011121314151617181920212223242526272829// Cloudflare Email Service's `send_email` binding. The sending domain is// the brand's, onboarded for sending on the account.import { Brand } from "@repo/brand";import { Effect, Layer } from "effect";
import { MailFailed, Mailer } from "../mailer.ts";
export const MAIL_FROM = { email: `no-reply@${Brand.domain}`, name: Brand.name,} as const;
export const MailerBinding = (binding: SendEmail) => Layer.succeed( Mailer, Mailer.of({ send: (mail) => Effect.tryPromise({ catch: () => new MailFailed(), try: () => binding.send({ from: MAIL_FROM, subject: mail.subject, text: mail.text, to: mail.to, }), }).pipe(Effect.asVoid), }) );added:apps/platform/src/auth/mailer/memory.ts+24 added
1+import { Effect, Layer, Ref } from "effect";2+3+import { MailFailed, Mailer } from "../mailer.ts";4+import type { Mail } from "../mailer.ts";5+6+// Keeps every mail sent, newest last; `failing` makes each send fail.7+export const MailerMemory = {8+ make: (options: { readonly failing?: boolean } = {}) =>9+ Effect.gen(function* () {10+ const sent = yield* Ref.make<readonly Mail[]>([]);11+12+ const layer = Layer.succeed(13+ Mailer,14+ Mailer.of({15+ send: (mail) =>16+ options.failing === true17+ ? Effect.fail(new MailFailed())18+ : Ref.update(sent, (all) => [...all, mail]),19+ })20+ );21+22+ return { layer, sent: Ref.get(sent) };23+ }),24+};modified:apps/platform/src/auth/accounts.ts+47 added-4 removed
1 import type { Handle } from "@repo/protocol/ids";2-import { Context, Data } from "effect";2+import { Context, Data, Schema } from "effect";3 import type { Effect, Option } from "effect";4 5 import type { PasswordHash } from "./password.ts";6 7+// Enough to catch a typo; the mailed code is what proves the address.8+export const Email = Schema.String.check(9+ Schema.isMaxLength(254),10+ Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/u)11+).pipe(Schema.brand("Email"));12+13+export type Email = typeof Email.Type;14+15+// The rule two spellings of one address are compared by.16+export const emailKey = (email: Email) => email.toLowerCase();17+18+const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });19+20+export const DisplayName = Schema.String.check(21+ Schema.makeFilter((name) => {22+ const { length } = [...graphemes.segment(name)];23+24+ return name === name.trim() &&25+ length >= 1 &&26+ length <= 64 &&27+ !/\p{Cc}/u.test(name)28+ ? true29+ : "1 to 64 characters, with no space at either end";30+ })31+).pipe(Schema.brand("DisplayName"));32+33+export type DisplayName = typeof DisplayName.Type;34+35+// Sign-up always sets `email` and `displayName`; only accounts made before36+// either existed lack them.37 export interface Account {38+ readonly displayName?: DisplayName;39+ readonly email?: Email;40 readonly handle: Handle;41 readonly hash: PasswordHash;42 }43 44 export class HandleTaken extends Data.TaggedError("HandleTaken")<{45 readonly handle: Handle;46 }> {}47 48+export class EmailTaken extends Data.TaggedError("EmailTaken")<{49+ readonly email: Email;50+}> {}51+52 // The rule `sameHandle` compares by, so a racing second sign-up fails on the key.53 export const handleKey = (handle: Handle) => handle.toLowerCase();54 55 export class Accounts extends Context.Service<56 Accounts,57 {58 readonly create: (23- handle: Handle,24- hash: PasswordHash25- ) => Effect.Effect<void, HandleTaken>;59+ account: Account60+ ) => Effect.Effect<void, HandleTaken | EmailTaken>;61 readonly find: (handle: Handle) => Effect.Effect<Option.Option<Account>>;62+ readonly findByEmail: (63+ email: Email64+ ) => Effect.Effect<Option.Option<Account>>;65+ // Only once its person proved the address.66+ readonly setEmail: (67+ handle: Handle,68+ email: Email69+ ) => Effect.Effect<void, EmailTaken>;70 readonly setPasswordHash: (71 handle: Handle,72 hash: PasswordHash73 ) => Effect.Effect<void>;2 unmodified linesadded:apps/platform/src/auth/codes.ts+105 added
1+// A mailed code proves a person reads an address. The code itself is kept2+// nowhere: the form carries its HMAC under the cookie key, bound to what it3+// is for and to the address, so the browser holding the form cannot guess it4+// offline, and a code mailed for one purpose or address opens no other.5+import { Effect, Option, Redacted, Schema } from "effect";6+7+import { emailKey } from "./accounts.ts";8+import type { Email } from "./accounts.ts";9+10+export const CODE_DIGITS = 6;11+12+const SPACE = 10 ** CODE_DIGITS;13+14+// The largest multiple of SPACE a Uint32 holds, so every code is as likely.15+const FAIR = Math.floor(2 ** 32 / SPACE) * SPACE;16+17+export const freshCode = Effect.sync(() => {18+ const draw = new Uint32Array(1);19+20+ do {21+ crypto.getRandomValues(draw);22+ } while ((draw[0] ?? FAIR) >= FAIR);23+24+ return ((draw[0] ?? 0) % SPACE).toString().padStart(CODE_DIGITS, "0");25+});26+27+export type CodePurpose = "sign-up" | "add-email" | "reset";28+29+const Tag = Schema.Uint8ArrayFromBase64Url;30+31+const encodeTag = Schema.encodeEffect(Tag);32+33+const decodeTag = Schema.decodeEffect(Tag);34+35+const utf8 = (text: string) => new TextEncoder().encode(text);36+37+const hmacKey = (key: Redacted.Redacted) =>38+ Effect.promise(() =>39+ crypto.subtle.importKey(40+ "raw",41+ utf8(Redacted.value(key)),42+ { hash: "SHA-256", name: "HMAC" },43+ false,44+ ["sign", "verify"]45+ )46+ );47+48+const bound = (purpose: CodePurpose, email: Email, code: string) =>49+ utf8(`code.${purpose}.${emailKey(email)}.${code}`);50+51+export const codeTag = (52+ key: Redacted.Redacted,53+ purpose: CodePurpose,54+ email: Email,55+ code: string56+) =>57+ Effect.gen(function* () {58+ const hmac = yield* hmacKey(key);59+60+ const signature = yield* Effect.promise(() =>61+ crypto.subtle.sign("HMAC", hmac, bound(purpose, email, code))62+ );63+64+ return yield* encodeTag(new Uint8Array(signature)).pipe(Effect.orDie);65+ });66+67+// A tag no code opens, for a form that must look like one that mailed a code.68+export const deadTag = Effect.sync(() =>69+ crypto.getRandomValues(new Uint8Array(32))70+).pipe(Effect.flatMap(encodeTag), Effect.orDie);71+72+// People paste codes with spaces or dashes in them.73+const typed = (entered: string) => entered.replaceAll(/[\s-]/gu, "");74+75+export const codeMatches = (76+ key: Redacted.Redacted,77+ purpose: CodePurpose,78+ email: Email,79+ tag: string,80+ entered: string81+) =>82+ Effect.gen(function* () {83+ const code = typed(entered);84+85+ if (!new RegExp(`^\\d{${CODE_DIGITS}}$`, "u").test(code)) {86+ return false;87+ }88+89+ const expected = yield* decodeTag(tag).pipe(Effect.option);90+91+ if (Option.isNone(expected)) {92+ return false;93+ }94+95+ const hmac = yield* hmacKey(key);96+97+ return yield* Effect.promise(() =>98+ crypto.subtle.verify(99+ "HMAC",100+ hmac,101+ new Uint8Array(expected.value),102+ bound(purpose, email, code)103+ )104+ );105+ });modified:apps/platform/src/auth/google.ts+177 added-72 removed
1-// Only Google's stable subject id (`sub`) is kept: no email, no name, and no Google token after the exchange.1+// Google's stable subject id (`sub`) is what links an account. Its email is2+// taken only when Google says it verified it, and its name only to fill in3+// the profile form; no Google token is kept after the exchange.4 import { Fetch } from "@repo/artifacts/fetch";5 import { Handle } from "@repo/protocol/ids";6 import {7 Array,9 unmodified lines17 Schema,18 } from "effect";19 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";20 19-import { Accounts } from "./accounts.ts";21+import { Accounts, Email } from "./accounts.ts";22+import type { Account } from "./accounts.ts";23 import { SignInAttempts } from "./attempts.ts";24 import { Identities } from "./identities.ts";25+import { Mailer } from "./mailer.ts";26 import { OAuthStore } from "./oauth-store.ts";23-import { GOOGLE_PATHS, pickHandlePage } from "./pages.ts";27+import { GOOGLE_PATHS, profilePage } from "./pages.ts";28+import type { ProfileValues } from "./pages.ts";29 import { hashPassword } from "./password.ts";30 import {31+ addEmailPageFor,32 addressOf,33 askerOf,34 Authorization,35 authorizeHref,36 byPassword,37+ chosenDisplayName,38 chosenHandle,39 completed,40 CSRF_COOKIE,41 csrfCookie,55 unmodified lines97 code_challenge_method: "S256",98 nonce: input.nonce,99 redirect_uri: input.redirectUri,100 response_type: "code",94- scope: "openid",101+ scope: "openid email profile",102 state: input.state,103 }).toString();104 105 return url.toString();28 unmodified lines134 135 const Claims = Schema.Struct({136 aud: Schema.Union([Schema.String, Schema.Array(Schema.String)]),137 azp: Schema.optionalKey(Schema.String),138+ email: Schema.optionalKey(Schema.String),139+ email_verified: Schema.optionalKey(Schema.Boolean),140 exp: Schema.Finite,141 iss: Schema.String,142+ name: Schema.optionalKey(Schema.String),143 nonce: Schema.optionalKey(Schema.String),144 sub: GoogleSubject,145 });146 147+export interface GooglePerson {148+ // Only an address Google verified.149+ readonly email: Option.Option<Email>;150+ readonly name: Option.Option<string>;151+ readonly subject: GoogleSubject;152+}153+154+const decodeEmail = Schema.decodeUnknownOption(Email);155+156+const personOf = (claims: typeof Claims.Type): GooglePerson => ({157+ email: Option.fromUndefinedOr(claims.email).pipe(158+ Option.filter(() => claims.email_verified === true),159+ Option.flatMap(decodeEmail)160+ ),161+ name: Option.fromUndefinedOr(claims.name),162+ subject: claims.sub,163+});164+165 const segment = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>166 Schema.decodeEffect(167 Schema.StringFromBase64Url.pipe(168 Schema.decodeTo(Schema.fromJsonString(schema))132 unmodified lines301 (audience.length === 1 || claims.azp === clientId)302 );303 };304 277-const verifiedSubject = (305+const verifiedPerson = (306 token: string,307 expected: { readonly clientId: string; readonly nonce: string }308 ) =>309 Effect.gen(function* () {40 unmodified lines350 issuedTo(said, expected.clientId) &&351 said.exp * 1000 > now &&352 said.nonce === expected.nonce;353 326- return holds ? said.sub : yield* unconfirmed;354+ return holds ? personOf(said) : yield* unconfirmed;355 });356 357 // Google's other tokens in the answer are never read, and nothing of it is kept.330-export const googleSubject = (input: {358+export const googlePerson = (input: {359 readonly clientId: string;360 readonly clientSecret: Redacted.Redacted;361 readonly code: string;362 readonly codeVerifier: string;363 readonly nonce: string;364 readonly redirectUri: string;337-}): Effect.Effect<GoogleSubject, SignInFailed, Fetch | GoogleKeys> =>365+}): Effect.Effect<GooglePerson, SignInFailed, Fetch | GoogleKeys> =>366 Effect.gen(function* () {367 const keys = yield* GoogleKeys;368 369 const fetch = yield* Fetch;19 unmodified lines389 method: "POST",390 })391 );392 365- return yield* verifiedSubject(id_token, input);393+ return yield* verifiedPerson(id_token, input);394 });395 396 interface Client {397 readonly id: string;7 unmodified lines405 406 const GoogleSays = {407 linkedElsewhere:408 "That Google account is linked to another handle. Sign in with that handle, or use another Google account.",409+ noEmail:410+ "Google did not share a verified email for that account. Sign up with an email and password instead.",411 } as const;412 413 // `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.414 const GOOGLE_COOKIE = "__Host-google-sign-in";25 unmodified lines440 const legs = sealing("google-leg", GoogleLeg);441 442 const PendingHandle = Schema.Struct({443 csrf: Schema.String,444+ email: Email,445+ name: Schema.optionalKey(Schema.String),446 request: AuthRequest,447 subject: GoogleSubject,448 });449 450+type PendingHandle = typeof PendingHandle.Type;451+452 const pendingHandles = sealing("google-handle", PendingHandle);453 454 const encodeBytes = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);455 78 unmodified lines534 });535 536 const link =537 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>504- byPassword(request, (handle, pending) =>505- toGoogle(client, pending.request, Option.some(handle))538+ byPassword(request, (account, pending) =>539+ toGoogle(client, pending.request, Option.some(account.handle))540 );541 542 const pickHandle = (509- subject: GoogleSubject,510- request: AuthRequest,543+ pending: Omit<PendingHandle, "csrf">,544+ values: ProfileValues,545 status: number,546 message?: string547 ) =>548 Effect.gen(function* () {549 const { cookieKey } = yield* SignInKeys;550 551 const csrf = yield* freshCsrf;552 519- const sealed = yield* pendingHandles.seal(cookieKey, {520- csrf,521- request,522- subject,523- });553+ const sealed = yield* pendingHandles.seal(cookieKey, { ...pending, csrf });554 525- const asker = yield* askerOf(request);555+ const asker = yield* askerOf(pending.request);556 557 return yield* htmlPage(528- pickHandlePage(558+ profilePage(559 asker,560 { csrf, request: sealed },531- authorizeHref(request),561+ authorizeHref(pending.request),562+ values,563 message564 ),565 status,535- request.redirectUri566+ pending.request.redirectUri567 ).pipe(568 HttpServerResponse.setCookie(CSRF_COOKIE, csrf, {569 ...csrfCookie,570 maxAge: SIGN_IN_LIFETIME,1 unmodified line572 Effect.orDie573 );574 });575 545-const signedInAs = (subject: GoogleSubject, request: AuthRequest) =>576+// Google just proved who the person is, so an account without an email577+// takes Google's verified one; if it has none, or another account holds it,578+// the person adds one before the grant, as a password sign-in would.579+const completedWithEmail = (580+ account: Account,581+ person: GooglePerson,582+ request: AuthRequest583+) =>584 Effect.gen(function* () {585+ const accounts = yield* Accounts;586+587+ if (account.email !== undefined) {588+ return yield* completed(account.handle, request);589+ }590+591+ const set = yield* Option.match(person.email, {592+ onNone: () => Effect.succeed(false),593+ onSome: (email) =>594+ accounts.setEmail(account.handle, email).pipe(595+ Effect.as(true),596+ Effect.catchTag("EmailTaken", () => Effect.succeed(false))597+ ),598+ });599+600+ return yield* set601+ ? completed(account.handle, request)602+ : addEmailPageFor(account.handle, request, 200);603+ });604+605+const linkedTo = (person: GooglePerson, handle: Handle, request: AuthRequest) =>606+ Effect.gen(function* () {607 const identities = yield* Identities;608 609 const accounts = yield* Accounts;610 551- const linked = yield* identities.handleOf("google", subject);611+ const linked = yield* identities612+ .link("google", person.subject, handle)613+ .pipe(614+ Effect.as(true),615+ Effect.catchTag("IdentityTaken", () => Effect.succeed(false))616+ );617 553- if (Option.isNone(linked)) {554- return yield* pickHandle(subject, request, 200);618+ if (!linked) {619+ return yield* signInPageFor(request, 409, GoogleSays.linkedElsewhere);620 }621 557- const account = yield* accounts.find(linked.value);622+ const account = yield* accounts.find(handle);623 624 return yield* Option.match(account, {625 onNone: () => signInPageFor(request, 401, unconfirmed.reason),561- onSome: (found) => completed(found.handle, request),626+ onSome: (found) => completedWithEmail(found, person, request),627 });628 });629 565-const linkedTo = (566- subject: GoogleSubject,567- handle: Handle,568- request: AuthRequest569-) =>630+const signedInAs = (person: GooglePerson, request: AuthRequest) =>631 Effect.gen(function* () {632 const identities = yield* Identities;633 573- const linked = yield* identities.link("google", subject, handle).pipe(574- Effect.as(true),575- Effect.catchTag("IdentityTaken", () => Effect.succeed(false))576- );634+ const accounts = yield* Accounts;635 578- return linked579- ? yield* completed(handle, request)580- : yield* signInPageFor(request, 409, GoogleSays.linkedElsewhere);636+ const linked = yield* identities.handleOf("google", person.subject);637+638+ if (Option.isSome(linked)) {639+ const account = yield* accounts.find(linked.value);640+641+ return yield* Option.match(account, {642+ onNone: () => signInPageFor(request, 401, unconfirmed.reason),643+ onSome: (found) => completedWithEmail(found, person, request),644+ });645+ }646+647+ if (Option.isNone(person.email)) {648+ return yield* signInPageFor(request, 401, GoogleSays.noEmail);649+ }650+651+ // Both Google and the account proved the address, so they are one person.652+ const holder = yield* accounts.findByEmail(person.email.value);653+654+ if (Option.isSome(holder)) {655+ return yield* linkedTo(person, holder.value.handle, request);656+ }657+658+ return yield* pickHandle(659+ {660+ email: person.email.value,661+ request,662+ subject: person.subject,663+ ...Option.match(person.name, {664+ onNone: () => ({}),665+ onSome: (name) => ({ name }),666+ }),667+ },668+ Option.match(person.name, {669+ onNone: () => ({}),670+ onSome: (displayName) => ({ displayName }),671+ }),672+ 200673+ );674 });675 676 const CallbackQuery = Schema.Struct({677 code: Schema.optionalKey(Schema.String),24 unmodified lines702 {703 // Google sends `error` and no code when the person declines.704 onNone: () => Effect.fail(unconfirmed),705 onSome: (code) =>613- googleSubject({706+ googlePerson({707 clientId: client.id,708 clientSecret: client.secret,709 code,710 codeVerifier: verifier,18 unmodified lines729 730 return yield* legDone(answered);731 });732 640-const PostedHandle = Schema.Struct({733+const PostedProfile = Schema.Struct({734 csrf: Schema.String,735+ displayName: Schema.String,736 handle: Schema.String,737 request: Schema.String,738 });739 646-// The account's password is one nobody is told: Google signs it in.740+// The account's password is one nobody is told: Google signs it in, and a741+// reset by its email sets a real one.742 const handleChosen = (request: HttpServerRequest.HttpServerRequest) =>743 Effect.gen(function* () {744 const { cookieKey, pepper } = yield* SignInKeys;745 5 unmodified lines751 752 const { handles: held } = yield* HeldHandles;753 754 const form = yield* HttpServerRequest.schemaBodyUrlParams(660- PostedHandle755+ PostedProfile756 ).pipe(Effect.mapError(() => startAgain));757 758 const pending = yield* pendingHandles.open(cookieKey, form.request);759 3 unmodified lines763 ) {764 return yield* startAgain;765 }766 672- if (!(yield* attempts.admit(`sign-up:${addressOf(request)}`))) {673- return yield* pickHandle(674- pending.subject,675- pending.request,676- 429,677- Says.tooManySignUps767+ const person: GooglePerson = {768+ email: Option.some(pending.email),769+ name: Option.fromUndefinedOr(pending.name),770+ subject: pending.subject,771+ };772+773+ const again = (status: number, message: string) =>774+ pickHandle(775+ pending,776+ { displayName: form.displayName, handle: form.handle },777+ status,778+ message779 );780+781+ if (!(yield* attempts.admit(`sign-up:${addressOf(request)}`))) {782+ return yield* again(429, Says.tooManySignUps);783 }784 785 if (Option.isSome(yield* identities.handleOf("google", pending.subject))) {682- return yield* signedInAs(pending.subject, pending.request);786+ return yield* signedInAs(person, pending.request);787 }788 685- const checked = chosenHandle(form.handle, held);789+ const checked = Result.all({790+ displayName: chosenDisplayName(form.displayName),791+ handle: chosenHandle(form.handle, held),792+ });793 794 if (Result.isFailure(checked)) {688- return yield* pickHandle(689- pending.subject,690- pending.request,691- checked.failure.status,692- checked.failure.message693- );795+ return yield* again(checked.failure.status, checked.failure.message);796 }797 798 const hash = yield* hashPassword(pepper, Redacted.make(yield* freshSecret));799 698- const created = yield* accounts.create(checked.success, hash).pipe(699- Effect.as(true),700- Effect.catchTag("HandleTaken", () => Effect.succeed(false))701- );702-703- if (!created) {704- return yield* pickHandle(705- pending.subject,706- pending.request,707- 409,708- Says.handleTaken800+ return yield* accounts801+ .create({802+ displayName: checked.success.displayName,803+ email: pending.email,804+ handle: checked.success.handle,805+ hash,806+ })807+ .pipe(808+ Effect.andThen(809+ linkedTo(person, checked.success.handle, pending.request)810+ ),811+ Effect.catchTags({812+ // Someone proved the same address since: they are one person.813+ EmailTaken: () => signedInAs(person, pending.request),814+ HandleTaken: () => again(409, Says.handleTaken),815+ })816 );710- }711-712- return yield* linkedTo(pending.subject, checked.success, pending.request);817 });818 819 export type GoogleServices = Fetch | GoogleClient | Identities | SignInServices;820 9 unmodified lines830 Context.add(Fetch, yield* Fetch),831 Context.add(GoogleKeys, yield* GoogleKeys),832 Context.add(HeldHandles, yield* HeldHandles),833 Context.add(Identities, yield* Identities),834+ Context.add(Mailer, yield* Mailer),835 Context.add(OAuthStore, yield* OAuthStore),836 Context.add(SignInAttempts, yield* SignInAttempts),837 Context.add(SignInKeys, yield* SignInKeys),838 Context.add(SignInOffers, yield* SignInOffers)22 unmodified linesadded:apps/platform/src/auth/mailer.ts+19 added
1+// The one way sign-in reaches a person outside the browser: a plain-text2+// mail, from the platform's own address, with a code in it.3+import { Context, Data } from "effect";4+import type { Effect } from "effect";5+6+import type { Email } from "./accounts.ts";7+8+export interface Mail {9+ readonly subject: string;10+ readonly text: string;11+ readonly to: Email;12+}13+14+export class MailFailed extends Data.TaggedError("MailFailed") {}15+16+export class Mailer extends Context.Service<17+ Mailer,18+ { readonly send: (mail: Mail) => Effect.Effect<void, MailFailed> }19+>()("platform/Mailer") {}modified:apps/platform/src/auth/pages.ts+118 added-9 removed
15 unmodified lines16 export interface Offers {17 readonly google: boolean;18 }19 20+// Under `/oauth/`, which the platform already keeps for sign-in.21+export const ACCOUNT_PATHS = {22+ addEmail: "/oauth/email",23+ addEmailVerify: "/oauth/email/verify",24+ reset: "/oauth/reset",25+ resetVerify: "/oauth/reset/verify",26+ signUpVerify: "/oauth/signup/verify",27+} as const;28+29 export const GOOGLE_PATHS = {30 callback: "/oauth/google/callback",31 handle: "/oauth/google/handle",32 link: "/oauth/google/link",103 unmodified lines136 offers.google137 ? {138 link: `<button type="submit" class="secondary" formaction="${GOOGLE_PATHS.link}">Sign in and link Google</button>`,139 start: `<p><a href="${GOOGLE_PATHS.start}?request=${encodeURIComponent(form.request)}" class="button">Continue with Google</a></p>131-<p class="muted">Or sign in with your handle and password.</p>`,140+<p class="muted">Or sign in with your email or handle and password.</p>`,141 }142 : { link: "", start: "" };143 144+const valueOf = (value?: string) =>145+ value === undefined ? "" : ` value="${escapeHtml(value)}"`;146+147+const withRequest = (path: string, form: PendingForm) =>148+ `${path}?request=${encodeURIComponent(form.request)}`;149+150 export const signInPage = (151 asker: Asker,152 form: PendingForm,153 offers: Offers,8 unmodified lines162 ${google.start}163 ${messageParagraph(message)}164 <form method="post" action="/authorize">165 ${hiddenFields(form)}151-<label>Handle <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" required></label>166+<label>Email or handle <input name="login" autocomplete="username" autocapitalize="none" spellcheck="false" required></label>167 <label>Password <input type="password" name="password" autocomplete="current-password" required></label>168 <div class="actions">169 <button type="submit">Sign in</button>170 ${google.link}171 </div>172 </form>158-<p>New here? <a href="/signup?request=${encodeURIComponent(form.request)}">Choose a handle and sign up</a>.</p>`173+<p><a href="${withRequest(ACCOUNT_PATHS.reset, form)}">Forgot your password?</a></p>174+<p>New here? <a href="${withRequest("/signup", form)}">Sign up</a>.</p>`175 );176 };177 178+export interface ProfileValues {179+ readonly displayName?: string;180+ readonly handle?: string;181+}182+183+const HANDLE_FIELD = (value?: string) =>184+ `<label>Handle, the name in your projects' addresses <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="39" required${valueOf(value)}></label>`;185+186+const DISPLAY_NAME_FIELD = (value?: string) =>187+ `<label>Display name <input name="displayName" autocomplete="name" maxlength="64" required${valueOf(value)}></label>`;188+162-export const pickHandlePage = (189+export const profilePage = (190 asker: Asker,191 form: PendingForm,192 signInHref: string,193+ values: ProfileValues,194 message?: string195 ) =>196 page(169- "Choose a handle",170- `<h1>Choose your handle on ${escapeHtml(Brand.name)}</h1>197+ "Set up your profile",198+ `<h1>Set up your profile on ${escapeHtml(Brand.name)}</h1>199 ${askerParagraphs(asker)}172-<p>Google confirmed who you are. This Google account has not signed in here before: choose the handle people will know you by.</p>200+<p>Google confirmed who you are. This Google account has not signed in here before: choose the handle and name people will know you by.</p>201 ${messageParagraph(message)}202 <form method="post" action="${GOOGLE_PATHS.handle}">203 ${hiddenFields(form)}176-<label>Handle <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="39" required></label>204+${DISPLAY_NAME_FIELD(values.displayName)}205+${HANDLE_FIELD(values.handle)}206 <div class="actions"><button type="submit">Sign up</button></div>207 </form>208 <p>Have an account with a password? <a href="${escapeHtml(signInHref)}">Sign in with it</a> and choose "Sign in and link Google".</p>`209 );210 211+export interface SignUpValues extends ProfileValues {212+ readonly email?: string;213+}214+215 export const signUpPage = (216 asker: Asker,217 form: PendingForm,218 signInHref: string,219+ values: SignUpValues,220 message?: string221 ) =>222 page(223 "Sign up",1 unmodified line225 ${askerParagraphs(asker)}226 ${messageParagraph(message)}227 <form method="post" action="/signup">228 ${hiddenFields(form)}195-<label>Handle <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="39" required></label>229+<label>Email <input type="email" name="email" autocomplete="email" autocapitalize="none" spellcheck="false" maxlength="254" required${valueOf(values.email)}></label>230+${DISPLAY_NAME_FIELD(values.displayName)}231+${HANDLE_FIELD(values.handle)}232 <label>Password, 12 to 256 characters <input type="password" name="password" autocomplete="new-password" minlength="12" maxlength="256" required></label>233 <div class="actions"><button type="submit">Sign up</button></div>234 </form>235+<p>We mail a code to the address, to check it is yours.</p>236 <p>Have an account? <a href="${escapeHtml(signInHref)}">Sign in</a>.</p>`237 );238 239+export interface CodeForm {240+ readonly action: string;241+ // Said above the form: where the code went, and what it is for.242+ readonly intro: string;243+ // A reset sets the new password in the same form.244+ readonly newPassword: boolean;245+ readonly startOverHref: string;246+}247+248+export const codePage = (249+ asker: Asker,250+ form: PendingForm,251+ code: CodeForm,252+ message?: string253+) =>254+ page(255+ "Enter the code",256+ `<h1>Enter the code we mailed you</h1>257+${askerParagraphs(asker)}258+<p>${escapeHtml(code.intro)} It works for 10 minutes.</p>259+${messageParagraph(message)}260+<form method="post" action="${code.action}">261+${hiddenFields(form)}262+<label>Code <input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9 -]*" maxlength="12" required></label>263+${code.newPassword ? `<label>New password, 12 to 256 characters <input type="password" name="password" autocomplete="new-password" minlength="12" maxlength="256" required></label>` : ""}264+<div class="actions"><button type="submit">Continue</button></div>265+</form>266+<p>No mail? Check your spam folder, or <a href="${escapeHtml(code.startOverHref)}">start again</a>.</p>`267+ );268+269+export const addEmailPage = (270+ asker: Asker,271+ form: PendingForm,272+ startOverHref: string,273+ value?: string,274+ message?: string275+) =>276+ page(277+ "Add your email",278+ `<h1>Add your email</h1>279+${askerParagraphs(asker)}280+<p>Your account has no email yet. Add one to finish signing in: we mail it a code, and it is how you reset your password.</p>281+${messageParagraph(message)}282+<form method="post" action="${ACCOUNT_PATHS.addEmail}">283+${hiddenFields(form)}284+<label>Email <input type="email" name="email" autocomplete="email" autocapitalize="none" spellcheck="false" maxlength="254" required${valueOf(value)}></label>285+<div class="actions"><button type="submit">Send the code</button></div>286+</form>287+<p><a href="${escapeHtml(startOverHref)}">Sign in as someone else</a></p>`288+ );289+290+export const resetPage = (291+ asker: Asker,292+ form: PendingForm,293+ signInHref: string,294+ value?: string,295+ message?: string296+) =>297+ page(298+ "Reset your password",299+ `<h1>Reset your password</h1>300+${askerParagraphs(asker)}301+<p>Enter your account's email. We mail it a code to set a new password with.</p>302+${messageParagraph(message)}303+<form method="post" action="${ACCOUNT_PATHS.reset}">304+${hiddenFields(form)}305+<label>Email <input type="email" name="email" autocomplete="email" autocapitalize="none" spellcheck="false" maxlength="254" required${valueOf(value)}></label>306+<div class="actions"><button type="submit">Send the code</button></div>307+</form>308+<p>Remembered it? <a href="${escapeHtml(signInHref)}">Sign in</a>.</p>`309+ );310+311 export const problemPage = (message: string) =>312 page(313 "Sign-in problem",314 `<h1>Signing in did not work</h1>3 unmodified linesmodified:apps/platform/src/auth/provider.ts+2 added
10 unmodified lines11 import { buildHandler } from "../router-build.ts";12 import { SignInAttemptsBinding } from "./attempts/binding.ts";13 import { GOOGLE_ACCOUNTS, GoogleClient, googleRoutes } from "./google.ts";14 import type { GoogleServices } from "./google.ts";15+import { MailerBinding } from "./mailer/binding.ts";16 import { OAuthStore } from "./oauth-store.ts";17 import { GOOGLE_PATHS } from "./pages.ts";18 import {19 Authorization,129 unmodified lines149 Layer.provide(D1Client.layer({ db: config.FRONT_PAGE })),150 Layer.orDie151 ),152 SignInAttemptsBinding(config.SIGN_IN_LIMIT),153+ MailerBinding(config.EMAIL),154 Layer.succeed(OAuthStore, config.OAUTH_KV),155 WorkerFetch156 );modified:apps/platform/src/auth/sign-in.ts+779 added-99 removed
18 unmodified lines19 Schema,20 } from "effect";21 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";22 23-import { Accounts, handleKey } from "./accounts.ts";23+import {24+ Accounts,25+ DisplayName,26+ Email,27+ emailKey,28+ handleKey,29+} from "./accounts.ts";30+import type { Account } from "./accounts.ts";31 import { SignInAttempts } from "./attempts.ts";32 import { CLI_CLIENT_PATH, cliClientMetadata } from "./cli-client.ts";33+import { codeMatches, codeTag, deadTag, freshCode } from "./codes.ts";34+import type { CodePurpose } from "./codes.ts";35+import { Mailer } from "./mailer.ts";36 import { OAuthStore } from "./oauth-store.ts";27-import { problemPage, signInPage, signUpPage } from "./pages.ts";28-import type { Asker, PendingForm } from "./pages.ts";37 import {38+ ACCOUNT_PATHS,39+ addEmailPage,40+ codePage,41+ problemPage,42+ resetPage,43+ signInPage,44+ signUpPage,45+} from "./pages.ts";46+import type { Asker, CodeForm, PendingForm, SignUpValues } from "./pages.ts";47+import {48 hashPassword,49 PasswordHash,50 PasswordPolicy,51 verifyPassword,52 } from "./password.ts";53 import {54+ AuthRequest,55 openState,56+ sealing,57 sealState,58 SIGN_IN_LIFETIME,59 SignInFailed,60 startAgain,61 } from "./state.ts";42-import type { AuthRequest, PendingSignIn } from "./state.ts";62+import type { PendingSignIn } from "./state.ts";63 64 export class SignInKeys extends Context.Service<65 SignInKeys,66 {34 unmodified lines101 export const SIGN_IN_PATHS = [102 "/authorize",103 "/signup",104 CLI_CLIENT_PATH,105+ ...Object.values(ACCOUNT_PATHS),106 ] as const;107 108 // A handle is an owner, the first segment of a project's address, so it may not be a word the web serves pages at.109 const RESERVED_HANDLES: ReadonlySet<string> = new Set([15 unmodified lines125 126 const PasswordLength = { max: 256, min: 12 } as const;127 128 export const Says = {129+ codeWrong:130+ "That code is wrong or has expired. Check the newest mail from us, or start again.",131+ displayName:132+ "A display name is 1 to 64 characters, with no space at either end.",133+ emailHeld: "Another account already uses that email. Add a different one.",134+ emailSpelling: "That does not look like an email address.",135+ emailTaken:136+ "That email already has an account. Sign in, or reset your password.",137 handleReserved: "That handle is reserved. Choose another.",138 handleSpelling:139 "A handle is 1 to 39 letters, digits and dashes, starting with a letter or digit.",140 handleTaken: "That handle is taken. Choose another, or sign in.",141+ handleTakenSince:142+ "Someone took that handle while you confirmed your email. Choose another.",143+ mailFailed: "We could not send the mail just now. Try again in a minute.",144 passwordLength: "A password is 12 to 256 characters.",145+ tooManyCodes:146+ "Too many codes tried for that address. Wait a minute, then try again.",147+ tooManyMails:148+ "Too many mails to that address, or from here. Wait a minute, then try again.",149 tooManySignIns:114- "Too many sign-in attempts for this handle or from here. Wait a minute, then try again.",150+ "Too many sign-in attempts for this account or from here. Wait a minute, then try again.",151 tooManySignUps: "Too many sign-ups from here. Wait a minute, then try again.",152 unverifiedClient:153 "This app could not be verified: its client metadata document could not be read.",118- wrong: "The handle or password is wrong.",154+ wrong: "The email, handle or password is wrong.",155 } as const;156 157 // Verified against when no account has the handle, so timing names nobody.158 const STAND_IN_HASH = PasswordHash.make(165 unmodified lines324 export const freshCsrf = Effect.sync(() =>325 crypto.getRandomValues(new Uint8Array(32))326 ).pipe(Effect.flatMap(encodeToken), Effect.orDie);327 292-const PostedForm = Schema.Struct({293- csrf: Schema.String,294- handle: Schema.String,295- password: Schema.String,296- request: Schema.String,297-});328+const decodeEmail = Schema.decodeUnknownOption(Email);329 299-type PostedForm = typeof PostedForm.Type;330+const decodeDisplayName = Schema.decodeUnknownOption(DisplayName);331 301-const postedSignIn = (request: HttpServerRequest.HttpServerRequest) =>302- Effect.gen(function* () {303- const { cookieKey } = yield* SignInKeys;304-305- const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedForm).pipe(306- Effect.mapError(() => startAgain)307- );308-309- const pending = yield* openState(cookieKey, form.request);310-311- const cookie = request.cookies[CSRF_COOKIE];312-313- if (pending.csrf !== form.csrf || cookie !== form.csrf) {314- return yield* startAgain;315- }316-317- return { form, pending };318- });319-332 export const addressOf = (request: HttpServerRequest.HttpServerRequest) =>333 request.headers["cf-connecting-ip"] ?? "unknown";334 335 const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });3 unmodified lines339 const passwordFits = (password: string) =>340 lengthOf(password) >= PasswordLength.min &&341 lengthOf(password) <= PasswordLength.max;342 343+const withCsrfCookie =344+ (csrf: string) => (response: HttpServerResponse.HttpServerResponse) =>345+ response.pipe(346+ HttpServerResponse.setCookie(CSRF_COOKIE, csrf, {347+ ...csrfCookie,348+ maxAge: SIGN_IN_LIFETIME,349+ }),350+ Effect.orDie351+ );352+353+// A form's own CSRF token, the one sealed into it and the cookie's agree, or the form was not opened here.354+const sameCsrf = (355+ request: HttpServerRequest.HttpServerRequest,356+ posted: string,357+ sealed: string358+) =>359+ sealed === posted && request.cookies[CSRF_COOKIE] === posted360+ ? Effect.void361+ : Effect.fail(startAgain);362+363 // The grant's user is the handle's key, so a grant is one account's in any case.364+// Every account it is given for has a proven email, or the person just proved365+// who they are to Google, whose address is then the account's.366 export const completed = (handle: Handle, request: AuthRequest) =>367 Effect.gen(function* () {368 const api = yield* oauthApi;369 50 unmodified lines420 const { cookieKey } = yield* SignInKeys;421 422 const csrf = yield* freshCsrf;423 390- const pending: PendingSignIn = { csrf, request };424+ const sealed = yield* sealState(cookieKey, { csrf, request });425 392- const sealed = yield* sealState(cookieKey, pending);393-426 const page = yield* offeredSignIn(427 request,428 { csrf, request: sealed },429 status,430 message431 );432 401- return yield* page.pipe(402- HttpServerResponse.setCookie(CSRF_COOKIE, csrf, {403- ...csrfCookie,404- maxAge: SIGN_IN_LIFETIME,405- }),406- Effect.orDie407- );433+ return yield* withCsrfCookie(csrf)(page);434 });435 436 const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>437 Effect.gen(function* () {5 unmodified lines443 444 return yield* signInPageFor(parsed, 200);445 });446 421-const signInAgain = (422- pending: PendingSignIn,423- form: PendingForm,447+// Mailing448+449+const MAIL_TEXT: Record<CodePurpose, (code: string) => string> = {450+ "add-email": (code) =>451+ `Your code to add this address to your ${Brand.name} account is ${code}. It works for 10 minutes.\n\nIf you did not ask for it, ignore this mail: nothing changes without the code.`,452+ reset: (code) =>453+ `Your code to set a new ${Brand.name} password is ${code}. It works for 10 minutes.\n\nIf you did not ask for it, ignore this mail: your password stays as it is.`,454+ "sign-up": (code) =>455+ `Your code to finish signing up for ${Brand.name} is ${code}. It works for 10 minutes.\n\nIf you did not sign up, ignore this mail: no account is made without the code.`,456+};457+458+// SIGN_IN_LIMIT's few mails a minute to one address, of any kind, so the forms are no way to flood an inbox.459+const mailAdmitted = (email: Email) =>460+ Effect.flatMap(SignInAttempts, (attempts) =>461+ attempts.admit(`mail:${emailKey(email)}`)462+ );463+464+const mailCode = (purpose: CodePurpose, email: Email) =>465+ Effect.gen(function* () {466+ const { cookieKey } = yield* SignInKeys;467+468+ const mailer = yield* Mailer;469+470+ const code = yield* freshCode;471+472+ yield* mailer.send({473+ subject: `${code} is your ${Brand.name} code`,474+ text: MAIL_TEXT[purpose](code),475+ to: email,476+ });477+478+ return yield* codeTag(cookieKey, purpose, email, code);479+ });480+481+// Sent in place of a code when the address already has an account, so the page reads the same either way.482+const mailAlreadyHeld = (email: Email) =>483+ Effect.gen(function* () {484+ const mailer = yield* Mailer;485+486+ yield* mailer.send({487+ subject: `You already have a ${Brand.name} account`,488+ text: `Someone, maybe you, tried to sign up for ${Brand.name} with this address, which already has an account. To get in, sign in, or choose "Forgot your password?" on the sign-in page.\n\nIf it was not you, ignore this mail: nothing changed.`,489+ to: email,490+ });491+492+ return yield* deadTag;493+ });494+495+const codeTried = (email: Email) =>496+ Effect.flatMap(SignInAttempts, (attempts) =>497+ attempts.admit(`code:${emailKey(email)}`)498+ );499+500+interface CodeStep {501+ readonly csrf: string;502+ readonly request: AuthRequest;503+ readonly sealed: string;504+}505+506+const codePageFor = (507+ step: CodeStep,508+ code: CodeForm,509 status: number,425- message: string426-) => offeredSignIn(pending.request, form, status, message);510+ message?: string511+) =>512+ Effect.map(askerOf(step.request), (asker) =>513+ htmlPage(514+ codePage(asker, { csrf: step.csrf, request: step.sealed }, code, message),515+ status,516+ step.request.redirectUri517+ )518+ );519 520+const codeSentTo = (email: Email) => `We mailed a code to ${email}.`;521+522+// Signing in523+524+const PostedSignIn = Schema.Struct({525+ csrf: Schema.String,526+ login: Schema.String,527+ password: Schema.String,528+ request: Schema.String,529+});530+531+// An `@` makes it an email; anything else is read as a handle.532+const accountNamed = (login: string) =>533+ Effect.gen(function* () {534+ const accounts = yield* Accounts;535+536+ const named = login.trim();537+538+ if (named.includes("@")) {539+ return yield* Option.match(decodeEmail(named), {540+ onNone: () => Effect.succeedNone,541+ onSome: accounts.findByEmail,542+ });543+ }544+545+ return yield* Option.match(decodeHandle(named), {546+ onNone: () => Effect.succeedNone,547+ onSome: accounts.find,548+ });549+ });550+428-// A wrong handle and a wrong password read the same.551+// A wrong login and a wrong password read the same.552 export const byPassword = <E, R>(553 request: HttpServerRequest.HttpServerRequest,554 signedIn: (432- handle: Handle,555+ account: Account,556 pending: PendingSignIn557 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>558 ) =>559 Effect.gen(function* () {437- const { pepper } = yield* SignInKeys;560+ const { cookieKey, pepper } = yield* SignInKeys;561 562 const accounts = yield* Accounts;563 564 const attempts = yield* SignInAttempts;565 443- const { form, pending } = yield* postedSignIn(request);566+ const form = yield* HttpServerRequest.schemaBodyUrlParams(567+ PostedSignIn568+ ).pipe(Effect.mapError(() => startAgain));569 570+ const pending = yield* openState(cookieKey, form.request);571+572+ yield* sameCsrf(request, form.csrf, pending.csrf);573+574 const shown: PendingForm = { csrf: form.csrf, request: form.request };575 447- const handle = decodeHandle(form.handle);576+ const again = (status: number, message: string) =>577+ offeredSignIn(pending.request, shown, status, message);578 579+ const fits = passwordFits(form.password);580+581+ const account = fits ? yield* accountNamed(form.login) : Option.none();582+583+ // An account is counted by its handle however it was named, so an email584+ // and a handle share one limit.585 const admitted = yield* Effect.all([586 attempts.admit(`address:${addressOf(request)}`),451- ...Option.match(handle, {452- onNone: () => [],453- onSome: (named) => [attempts.admit(`handle:${handleKey(named)}`)],454- }),587+ attempts.admit(588+ Option.match(account, {589+ onNone: () => `login:${form.login.trim().toLowerCase()}`,590+ onSome: ({ handle }) => `handle:${handleKey(handle)}`,591+ })592+ ),593 ]);594 595 if (!admitted.every(Boolean)) {458- return yield* signInAgain(pending, shown, 429, Says.tooManySignIns);596+ return yield* again(429, Says.tooManySignIns);597 }598 599 const password = Redacted.make(form.password);600 463- const account = passwordFits(form.password)464- ? yield* Option.match(handle, {465- onNone: () => Effect.succeedNone,466- onSome: accounts.find,467- })468- : Option.none();469-601 const { needsRehash, ok } = yield* verifyPassword(602 pepper,603 password,604 Option.match(account, {2 unmodified lines607 })608 );609 610 if (Option.isNone(account) || !ok) {480- return yield* signInAgain(pending, shown, 401, Says.wrong);611+ return yield* again(401, Says.wrong);612 }613 614 if (needsRehash) {615 yield* accounts.setPasswordHash(1 unmodified line617 yield* hashPassword(pepper, password)618 );619 }620 490- return yield* signedIn(account.value.handle, pending);621+ return yield* signedIn(account.value, pending);622 });623 624+// Adding an email: an account made before sign-up asked for one625+626+const NeedsEmail = Schema.Struct({627+ csrf: Schema.String,628+ handle: Handle,629+ request: AuthRequest,630+});631+632+const needingEmail = sealing("needs-email", NeedsEmail);633+634+const PendingEmail = Schema.Struct({635+ csrf: Schema.String,636+ email: Email,637+ handle: Handle,638+ request: AuthRequest,639+ tag: Schema.String,640+});641+642+const pendingEmails = sealing("email-code", PendingEmail);643+644+// The person proved their password, or Google proved who they are: only an email stands between them and the grant.645+export const addEmailPageFor = (646+ handle: Handle,647+ request: AuthRequest,648+ status: number,649+ message?: string,650+ value?: string651+) =>652+ Effect.gen(function* () {653+ const { cookieKey } = yield* SignInKeys;654+655+ const csrf = yield* freshCsrf;656+657+ const sealed = yield* needingEmail.seal(cookieKey, {658+ csrf,659+ handle,660+ request,661+ });662+663+ const asker = yield* askerOf(request);664+665+ return yield* withCsrfCookie(csrf)(666+ htmlPage(667+ addEmailPage(668+ asker,669+ { csrf, request: sealed },670+ authorizeHref(request),671+ value,672+ message673+ ),674+ status,675+ request.redirectUri676+ )677+ );678+ });679+680+// A signed-in account with no email adds one before its grant.681+export const signedInWithEmail = (account: Account, request: AuthRequest) =>682+ account.email === undefined683+ ? addEmailPageFor(account.handle, request, 200)684+ : completed(account.handle, request);685+686 const signIn = (request: HttpServerRequest.HttpServerRequest) =>494- byPassword(request, (handle, pending) => completed(handle, pending.request));687+ byPassword(request, (account, pending) =>688+ signedInWithEmail(account, pending.request)689+ );690 691+const addEmailCode = (request: AuthRequest, email: Email): CodeForm => ({692+ action: ACCOUNT_PATHS.addEmailVerify,693+ intro: codeSentTo(email),694+ newPassword: false,695+ startOverHref: authorizeHref(request),696+});697+698+const PostedEmail = Schema.Struct({699+ csrf: Schema.String,700+ email: Schema.String,701+ request: Schema.String,702+});703+704+const addEmail = (request: HttpServerRequest.HttpServerRequest) =>705+ Effect.gen(function* () {706+ const { cookieKey } = yield* SignInKeys;707+708+ const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedEmail).pipe(709+ Effect.mapError(() => startAgain)710+ );711+712+ const pending = yield* needingEmail.open(cookieKey, form.request);713+714+ yield* sameCsrf(request, form.csrf, pending.csrf);715+716+ const again = (status: number, message: string) =>717+ Effect.map(askerOf(pending.request), (asker) =>718+ htmlPage(719+ addEmailPage(720+ asker,721+ { csrf: form.csrf, request: form.request },722+ authorizeHref(pending.request),723+ form.email,724+ message725+ ),726+ status,727+ pending.request.redirectUri728+ )729+ );730+731+ const email = decodeEmail(form.email.trim());732+733+ if (Option.isNone(email)) {734+ return yield* again(400, Says.emailSpelling);735+ }736+737+ if (!(yield* mailAdmitted(email.value))) {738+ return yield* again(429, Says.tooManyMails);739+ }740+741+ // Mailed even when another account holds the address: that is said only742+ // once the code shows the person reads it.743+ const tag = yield* mailCode("add-email", email.value).pipe(Effect.option);744+745+ if (Option.isNone(tag)) {746+ return yield* again(503, Says.mailFailed);747+ }748+749+ const sealed = yield* pendingEmails.seal(cookieKey, {750+ csrf: form.csrf,751+ email: email.value,752+ handle: pending.handle,753+ request: pending.request,754+ tag: tag.value,755+ });756+757+ return yield* codePageFor(758+ { csrf: form.csrf, request: pending.request, sealed },759+ addEmailCode(pending.request, email.value),760+ 200761+ );762+ });763+764+const PostedCode = Schema.Struct({765+ code: Schema.String,766+ csrf: Schema.String,767+ request: Schema.String,768+});769+770+const addEmailVerified = (request: HttpServerRequest.HttpServerRequest) =>771+ Effect.gen(function* () {772+ const { cookieKey } = yield* SignInKeys;773+774+ const accounts = yield* Accounts;775+776+ const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedCode).pipe(777+ Effect.mapError(() => startAgain)778+ );779+780+ const pending = yield* pendingEmails.open(cookieKey, form.request);781+782+ yield* sameCsrf(request, form.csrf, pending.csrf);783+784+ const again = (status: number, message: string) =>785+ codePageFor(786+ {787+ csrf: form.csrf,788+ request: pending.request,789+ sealed: form.request,790+ },791+ addEmailCode(pending.request, pending.email),792+ status,793+ message794+ );795+796+ if (!(yield* codeTried(pending.email))) {797+ return yield* again(429, Says.tooManyCodes);798+ }799+800+ const right = yield* codeMatches(801+ cookieKey,802+ "add-email",803+ pending.email,804+ pending.tag,805+ form.code806+ );807+808+ if (!right) {809+ return yield* again(401, Says.codeWrong);810+ }811+812+ const set = yield* accounts.setEmail(pending.handle, pending.email).pipe(813+ Effect.as(true),814+ Effect.catchTag("EmailTaken", () => Effect.succeed(false))815+ );816+817+ return yield* set818+ ? completed(pending.handle, pending.request)819+ : addEmailPageFor(pending.handle, pending.request, 409, Says.emailHeld);820+ });821+822+// Signing up: the account is written only once the mailed code comes back823+824+const PendingSignUp = Schema.Struct({825+ csrf: Schema.String,826+ displayName: DisplayName,827+ email: Email,828+ handle: Handle,829+ // Peppered: worthless to the browser that holds the form.830+ hash: PasswordHash,831+ request: AuthRequest,832+ tag: Schema.String,833+});834+835+const pendingSignUps = sealing("sign-up-code", PendingSignUp);836+837 const showSignUp = Effect.gen(function* () {838 const { cookieKey } = yield* SignInKeys;839 840 const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(7 unmodified lines848 return htmlPage(849 signUpPage(850 asker,851 { csrf: pending.csrf, request: sealed },511- authorizeHref(pending.request)852+ authorizeHref(pending.request),853+ {}854 ),855 200,856 pending.request.redirectUri857 );7 unmodified lines865 export const chosenHandle = (866 handle: string,867 held: readonly Handle[]868 ): Result.Result<Handle, Refused> =>527- Option.match(decodeHandle(handle), {869+ Option.match(decodeHandle(handle.trim()), {870 onNone: () => Result.fail({ message: Says.handleSpelling, status: 400 }),871 onSome: (chosen) => {872 if (RESERVED_HANDLES.has(handleKey(chosen))) {873 return Result.fail({ message: Says.handleReserved, status: 400 });6 unmodified lines880 return Result.succeed(chosen);881 },882 });883 884+export const chosenDisplayName = (885+ name: string886+): Result.Result<DisplayName, Refused> =>887+ Option.match(decodeDisplayName(name.trim()), {888+ onNone: () => Result.fail({ message: Says.displayName, status: 400 }),889+ onSome: Result.succeed,890+ });891+892+const PostedSignUp = Schema.Struct({893+ csrf: Schema.String,894+ displayName: Schema.String,895+ email: Schema.String,896+ handle: Schema.String,897+ password: Schema.String,898+ request: Schema.String,899+});900+901+type PostedSignUp = typeof PostedSignUp.Type;902+903+interface SignUpChoice {904+ readonly displayName: DisplayName;905+ readonly email: Email;906+ readonly handle: Handle;907+}908+542-const signUpHandle = (543- form: PostedForm,909+const signUpChoice = (910+ form: PostedSignUp,911 held: readonly Handle[]545-): Result.Result<Handle, Refused> =>546- Result.flatMap(chosenHandle(form.handle, held), (handle) =>547- passwordFits(form.password)548- ? Result.succeed(handle)549- : Result.fail({ message: Says.passwordLength, status: 400 })912+): Result.Result<SignUpChoice, Refused> =>913+ Result.flatMap(914+ Result.all({915+ displayName: chosenDisplayName(form.displayName),916+ email: Option.match(decodeEmail(form.email.trim()), {917+ onNone: () =>918+ Result.fail<Refused>({ message: Says.emailSpelling, status: 400 }),919+ onSome: Result.succeed,920+ }),921+ handle: chosenHandle(form.handle, held),922+ }),923+ (choice) =>924+ passwordFits(form.password)925+ ? Result.succeed(choice)926+ : Result.fail({ message: Says.passwordLength, status: 400 })927 );928 929+const signUpPageFor = (930+ request: AuthRequest,931+ form: PendingForm,932+ values: SignUpValues,933+ status: number,934+ message: string935+) =>936+ Effect.map(askerOf(request), (asker) =>937+ htmlPage(938+ signUpPage(asker, form, authorizeHref(request), values, message),939+ status,940+ request.redirectUri941+ )942+ );943+944+const signUpCode = (request: AuthRequest, email: Email): CodeForm => ({945+ action: ACCOUNT_PATHS.signUpVerify,946+ intro: codeSentTo(email),947+ newPassword: false,948+ startOverHref: authorizeHref(request),949+});950+951 const signUp = (request: HttpServerRequest.HttpServerRequest) =>952 Effect.gen(function* () {554- const { pepper } = yield* SignInKeys;953+ const { cookieKey, pepper } = yield* SignInKeys;954 955 const accounts = yield* Accounts;956 957 const attempts = yield* SignInAttempts;958 959 const { handles: held } = yield* HeldHandles;960 562- const { form, pending } = yield* postedSignIn(request);961+ const form = yield* HttpServerRequest.schemaBodyUrlParams(962+ PostedSignUp963+ ).pipe(Effect.mapError(() => startAgain));964 965+ const pending = yield* openState(cookieKey, form.request);966+967+ yield* sameCsrf(request, form.csrf, pending.csrf);968+969 const again = (status: number, message: string) =>565- askerOf(pending.request).pipe(566- Effect.map((asker) =>567- htmlPage(568- signUpPage(569- asker,570- { csrf: form.csrf, request: form.request },571- authorizeHref(pending.request),572- message573- ),574- status,575- pending.request.redirectUri576- )577- )970+ signUpPageFor(971+ pending.request,972+ { csrf: form.csrf, request: form.request },973+ {974+ displayName: form.displayName,975+ email: form.email,976+ handle: form.handle,977+ },978+ status,979+ message980 );981 982 if (!(yield* attempts.admit(`sign-up:${addressOf(request)}`))) {983 return yield* again(429, Says.tooManySignUps);984 }985 584- const checked = signUpHandle(form, held);986+ const checked = signUpChoice(form, held);987 988 if (Result.isFailure(checked)) {989 return yield* again(checked.failure.status, checked.failure.message);990 }991 590- const hash = yield* hashPassword(pepper, Redacted.make(form.password));992+ const { displayName, email, handle } = checked.success;993 592- const created = yield* accounts.create(checked.success, hash).pipe(593- Effect.as(true),594- Effect.catchTag("HandleTaken", () => Effect.succeed(false))994+ if (Option.isSome(yield* accounts.find(handle))) {995+ return yield* again(409, Says.handleTaken);996+ }997+998+ if (!(yield* mailAdmitted(email))) {999+ return yield* again(429, Says.tooManyMails);1000+ }1001+1002+ const holder = yield* accounts.findByEmail(email);1003+1004+ const tag = yield* (1005+ Option.isSome(holder)1006+ ? mailAlreadyHeld(email)1007+ : mailCode("sign-up", email)1008+ ).pipe(Effect.option);1009+1010+ if (Option.isNone(tag)) {1011+ return yield* again(503, Says.mailFailed);1012+ }1013+1014+ const sealed = yield* pendingSignUps.seal(cookieKey, {1015+ csrf: form.csrf,1016+ displayName,1017+ email,1018+ handle,1019+ hash: yield* hashPassword(pepper, Redacted.make(form.password)),1020+ request: pending.request,1021+ tag: tag.value,1022+ });1023+1024+ return yield* codePageFor(1025+ { csrf: form.csrf, request: pending.request, sealed },1026+ signUpCode(pending.request, email),1027+ 2001028 );1029+ });1030 597- if (!created) {598- return yield* again(409, Says.handleTaken);1031+const signUpVerified = (request: HttpServerRequest.HttpServerRequest) =>1032+ Effect.gen(function* () {1033+ const { cookieKey } = yield* SignInKeys;1034+1035+ const accounts = yield* Accounts;1036+1037+ const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedCode).pipe(1038+ Effect.mapError(() => startAgain)1039+ );1040+1041+ const pending = yield* pendingSignUps.open(cookieKey, form.request);1042+1043+ yield* sameCsrf(request, form.csrf, pending.csrf);1044+1045+ const again = (status: number, message: string) =>1046+ codePageFor(1047+ { csrf: form.csrf, request: pending.request, sealed: form.request },1048+ signUpCode(pending.request, pending.email),1049+ status,1050+ message1051+ );1052+1053+ if (!(yield* codeTried(pending.email))) {1054+ return yield* again(429, Says.tooManyCodes);1055 }1056 601- return yield* completed(checked.success, pending.request);1057+ const right = yield* codeMatches(1058+ cookieKey,1059+ "sign-up",1060+ pending.email,1061+ pending.tag,1062+ form.code1063+ );1064+1065+ if (!right) {1066+ return yield* again(401, Says.codeWrong);1067+ }1068+1069+ return yield* accounts1070+ .create({1071+ displayName: pending.displayName,1072+ email: pending.email,1073+ handle: pending.handle,1074+ hash: pending.hash,1075+ })1076+ .pipe(1077+ Effect.andThen(completed(pending.handle, pending.request)),1078+ Effect.catchTags({1079+ EmailTaken: () =>1080+ signInPageFor(pending.request, 409, Says.emailTaken),1081+ HandleTaken: () =>1082+ Effect.gen(function* () {1083+ const csrf = yield* freshCsrf;1084+1085+ const sealed = yield* sealState(cookieKey, {1086+ csrf,1087+ request: pending.request,1088+ });1089+1090+ const page = yield* signUpPageFor(1091+ pending.request,1092+ { csrf, request: sealed },1093+ { displayName: pending.displayName, email: pending.email },1094+ 409,1095+ Says.handleTakenSince1096+ );1097+1098+ return yield* withCsrfCookie(csrf)(page);1099+ }),1100+ })1101+ );1102 });1103 1104+// Resetting a password by a code mailed to the account's address1105+1106+const PendingReset = Schema.Struct({1107+ csrf: Schema.String,1108+ email: Email,1109+ request: AuthRequest,1110+ tag: Schema.String,1111+});1112+1113+const pendingResets = sealing("reset-code", PendingReset);1114+1115+const showReset = Effect.gen(function* () {1116+ const { cookieKey } = yield* SignInKeys;1117+1118+ const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(1119+ Schema.Struct({ request: Schema.String })1120+ ).pipe(Effect.mapError(() => startAgain));1121+1122+ const pending = yield* openState(cookieKey, sealed);1123+1124+ const asker = yield* askerOf(pending.request);1125+1126+ return htmlPage(1127+ resetPage(1128+ asker,1129+ { csrf: pending.csrf, request: sealed },1130+ authorizeHref(pending.request)1131+ ),1132+ 200,1133+ pending.request.redirectUri1134+ );1135+});1136+1137+const resetCode = (request: AuthRequest, email: Email): CodeForm => ({1138+ action: ACCOUNT_PATHS.resetVerify,1139+ intro: `If an account uses ${email}, we mailed it a code.`,1140+ newPassword: true,1141+ startOverHref: authorizeHref(request),1142+});1143+1144+// Says the same whether or not an account has the address; only one that has gets a mail.1145+const reset = (request: HttpServerRequest.HttpServerRequest) =>1146+ Effect.gen(function* () {1147+ const { cookieKey } = yield* SignInKeys;1148+1149+ const accounts = yield* Accounts;1150+1151+ const attempts = yield* SignInAttempts;1152+1153+ const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedEmail).pipe(1154+ Effect.mapError(() => startAgain)1155+ );1156+1157+ const pending = yield* openState(cookieKey, form.request);1158+1159+ yield* sameCsrf(request, form.csrf, pending.csrf);1160+1161+ const again = (status: number, message: string) =>1162+ Effect.map(askerOf(pending.request), (asker) =>1163+ htmlPage(1164+ resetPage(1165+ asker,1166+ { csrf: form.csrf, request: form.request },1167+ authorizeHref(pending.request),1168+ form.email,1169+ message1170+ ),1171+ status,1172+ pending.request.redirectUri1173+ )1174+ );1175+1176+ const email = decodeEmail(form.email.trim());1177+1178+ if (Option.isNone(email)) {1179+ return yield* again(400, Says.emailSpelling);1180+ }1181+1182+ const admitted = yield* Effect.all([1183+ attempts.admit(`reset:${addressOf(request)}`),1184+ mailAdmitted(email.value),1185+ ]);1186+1187+ if (!admitted.every(Boolean)) {1188+ return yield* again(429, Says.tooManyMails);1189+ }1190+1191+ const account = yield* accounts.findByEmail(email.value);1192+1193+ const tag = yield* (1194+ Option.isSome(account) ? mailCode("reset", email.value) : deadTag1195+ ).pipe(Effect.option);1196+1197+ if (Option.isNone(tag)) {1198+ return yield* again(503, Says.mailFailed);1199+ }1200+1201+ const sealed = yield* pendingResets.seal(cookieKey, {1202+ csrf: form.csrf,1203+ email: email.value,1204+ request: pending.request,1205+ tag: tag.value,1206+ });1207+1208+ return yield* codePageFor(1209+ { csrf: form.csrf, request: pending.request, sealed },1210+ resetCode(pending.request, email.value),1211+ 2001212+ );1213+ });1214+1215+const PostedReset = Schema.Struct({1216+ code: Schema.String,1217+ csrf: Schema.String,1218+ password: Schema.String,1219+ request: Schema.String,1220+});1221+1222+const resetVerified = (request: HttpServerRequest.HttpServerRequest) =>1223+ Effect.gen(function* () {1224+ const { cookieKey, pepper } = yield* SignInKeys;1225+1226+ const accounts = yield* Accounts;1227+1228+ const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedReset).pipe(1229+ Effect.mapError(() => startAgain)1230+ );1231+1232+ const pending = yield* pendingResets.open(cookieKey, form.request);1233+1234+ yield* sameCsrf(request, form.csrf, pending.csrf);1235+1236+ const again = (status: number, message: string) =>1237+ codePageFor(1238+ { csrf: form.csrf, request: pending.request, sealed: form.request },1239+ resetCode(pending.request, pending.email),1240+ status,1241+ message1242+ );1243+1244+ if (!passwordFits(form.password)) {1245+ return yield* again(400, Says.passwordLength);1246+ }1247+1248+ if (!(yield* codeTried(pending.email))) {1249+ return yield* again(429, Says.tooManyCodes);1250+ }1251+1252+ const right = yield* codeMatches(1253+ cookieKey,1254+ "reset",1255+ pending.email,1256+ pending.tag,1257+ form.code1258+ );1259+1260+ const account = right1261+ ? yield* accounts.findByEmail(pending.email)1262+ : Option.none();1263+1264+ if (Option.isNone(account)) {1265+ return yield* again(401, Says.codeWrong);1266+ }1267+1268+ yield* accounts.setPasswordHash(1269+ account.value.handle,1270+ yield* hashPassword(pepper, Redacted.make(form.password))1271+ );1272+1273+ return yield* completed(account.value.handle, pending.request);1274+ });1275+1276 const cliClient = Effect.gen(function* () {1277 const { origin } = yield* Authorization;1278 1279 return HttpServerResponse.jsonUnsafe(cliClientMetadata(origin), {28 unmodified lines1308 1309 export type SignInServices =1310 | Accounts1311 | HeldHandles1312+ | Mailer1313 | OAuthStore1314 | SignInAttempts1315 | SignInKeys1316 | SignInOffers;1 unmodified line1318 export const signInRoutes = HttpRouter.use((router) =>1319 Effect.gen(function* () {1320 const services = Context.make(Accounts, yield* Accounts).pipe(1321 Context.add(HeldHandles, yield* HeldHandles),1322+ Context.add(Mailer, yield* Mailer),1323 Context.add(OAuthStore, yield* OAuthStore),1324 Context.add(SignInAttempts, yield* SignInAttempts),1325 Context.add(SignInKeys, yield* SignInKeys),1326 Context.add(SignInOffers, yield* SignInOffers)16 unmodified lines1343 yield* add("GET", "/authorize", showSignIn);1344 yield* add("POST", "/authorize", signIn);1345 yield* add("GET", "/signup", () => showSignUp);1346 yield* add("POST", "/signup", signUp);1347+ yield* add("POST", ACCOUNT_PATHS.signUpVerify, signUpVerified);1348+ yield* add("POST", ACCOUNT_PATHS.addEmail, addEmail);1349+ yield* add("POST", ACCOUNT_PATHS.addEmailVerify, addEmailVerified);1350+ yield* add("GET", ACCOUNT_PATHS.reset, () => showReset);1351+ yield* add("POST", ACCOUNT_PATHS.reset, reset);1352+ yield* add("POST", ACCOUNT_PATHS.resetVerify, resetVerified);1353 yield* add("GET", CLI_CLIENT_PATH, () => cliClient);1354 1355 for (const path of AUTHORIZATION_SERVER_PATHS) {1356 yield* add("*", path, authorizationServer);3 unmodified linesmodified:apps/platform/src/platform.ts+1 added
57 unmodified lines58 ),59 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),60 CODE_CACHE: binding<Env["CODE_CACHE"]>("an R2 bucket"),61 DRAFT_LIMIT: binding<Env["DRAFT_LIMIT"]>("a rate limit"),62+ EMAIL: binding<Env["EMAIL"]>("Email Service's send_email"),63 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),64 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),65 LOADER: binding<Env["LOADER"]>("a Worker Loader"),66 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),128 unmodified linesmodified:apps/platform/test/accounts.test.ts+125 added-11 removed
4 unmodified lines5 import { Effect, Exit, FileSystem, Layer, Option } from "effect";6 import { SqlClient } from "effect/sql/SqlClient";7 8 import { AccountsD1 } from "../src/adapters/accounts-d1.ts";9-import { Accounts, HandleTaken } from "../src/auth/accounts.ts";9+import {10+ Accounts,11+ DisplayName,12+ Email,13+ EmailTaken,14+ HandleTaken,15+} from "../src/auth/accounts.ts";16 import { AccountsMemory } from "../src/auth/accounts/memory.ts";17 import { PasswordHash } from "../src/auth/password.ts";18 19 const alice = Handle.make("alice");1 unmodified line21 const first = PasswordHash.make("pbkdf2-sha256$100000$Zmlyc3Q$Zmlyc3Q");22 23 const second = PasswordHash.make("pbkdf2-sha256$100000$c2Vjb25k$c2Vjb25k");24 25+const aliceEmail = Email.make("alice@mail.example");26+27+const aliceName = DisplayName.make("Alice Example");28+29 const find = (handle: string) =>30 Accounts.use((accounts) => accounts.find(Handle.make(handle)));31 32 const describeAccounts = (adapter: string, layer: Layer.Layer<Accounts>) => {1 unmodified line34 it.effect("finds an account by its handle, in any case", () =>35 Effect.gen(function* () {36 const accounts = yield* Accounts;37 28- yield* accounts.create(Handle.make("Alice"), first);38+ yield* accounts.create({ handle: Handle.make("Alice"), hash: first });39 40 const found = Option.some({41 handle: Handle.make("Alice"),42 hash: first,16 unmodified lines59 () =>60 Effect.gen(function* () {61 const accounts = yield* Accounts;62 53- yield* accounts.create(alice, first);63+ yield* accounts.create({ handle: alice, hash: first });64 65 const taken = yield* Effect.flip(56- accounts.create(Handle.make("ALICE"), second)66+ accounts.create({ handle: Handle.make("ALICE"), hash: second })67 );68 69 expect(taken).toStrictEqual(70 new HandleTaken({ handle: Handle.make("ALICE") })9 unmodified lines80 const accounts = yield* Accounts;81 82 const exits = yield* Effect.all(83 [74- Effect.exit(accounts.create(alice, first)),75- Effect.exit(accounts.create(Handle.make("Alice"), second)),84+ Effect.exit(accounts.create({ handle: alice, hash: first })),85+ Effect.exit(86+ accounts.create({ handle: Handle.make("Alice"), hash: second })87+ ),88 ],89 { concurrency: "unbounded" }90 );91 4 unmodified lines96 it.effect("replaces an account's password hash", () =>97 Effect.gen(function* () {98 const accounts = yield* Accounts;99 88- yield* accounts.create(alice, first);100+ yield* accounts.create({ handle: alice, hash: first });101 yield* accounts.setPasswordHash(Handle.make("ALICE"), second);102 103 expect(yield* find("alice")).toStrictEqual(104 Option.some({ handle: alice, hash: second })105 );106 }).pipe(Effect.provide(layer))107 );108+109+ it.effect(110+ "keeps an account's email and display name, and finds it by its email in any case",111+ () =>112+ Effect.gen(function* () {113+ const accounts = yield* Accounts;114+115+ const account = {116+ displayName: aliceName,117+ email: aliceEmail,118+ handle: alice,119+ hash: first,120+ };121+122+ yield* accounts.create(account);123+124+ expect(yield* find("ALICE")).toStrictEqual(Option.some(account));125+ expect(126+ yield* accounts.findByEmail(Email.make("ALICE@Mail.Example"))127+ ).toStrictEqual(Option.some(account));128+ expect(129+ yield* accounts.findByEmail(Email.make("bob@mail.example"))130+ ).toStrictEqual(Option.none());131+ }).pipe(Effect.provide(layer))132+ );133+134+ it.effect(135+ "refuses a second account with the same email in another case, and lets any number have none",136+ () =>137+ Effect.gen(function* () {138+ const accounts = yield* Accounts;139+140+ yield* accounts.create({141+ email: aliceEmail,142+ handle: alice,143+ hash: first,144+ });145+ yield* accounts.create({ handle: Handle.make("carol"), hash: first });146+ yield* accounts.create({ handle: Handle.make("dave"), hash: first });147+148+ const shouted = Email.make("ALICE@mail.example");149+150+ expect(151+ yield* Effect.flip(152+ accounts.create({153+ email: shouted,154+ handle: Handle.make("bob"),155+ hash: second,156+ })157+ )158+ ).toStrictEqual(new EmailTaken({ email: shouted }));159+ expect(yield* find("bob")).toStrictEqual(Option.none());160+ }).pipe(Effect.provide(layer))161+ );162+163+ it.effect(164+ "sets an account's email, unless another account holds it or no account has the handle",165+ () =>166+ Effect.gen(function* () {167+ const accounts = yield* Accounts;168+169+ const bobEmail = Email.make("bob@mail.example");170+171+ yield* accounts.create({ handle: alice, hash: first });172+ yield* accounts.create({173+ email: bobEmail,174+ handle: Handle.make("bob"),175+ hash: second,176+ });177+178+ yield* accounts.setEmail(Handle.make("ALICE"), aliceEmail);179+180+ expect(yield* find("alice")).toStrictEqual(181+ Option.some({ email: aliceEmail, handle: alice, hash: first })182+ );183+ expect(184+ yield* Effect.flip(accounts.setEmail(alice, bobEmail))185+ ).toStrictEqual(new EmailTaken({ email: bobEmail }));186+ expect(187+ yield* Effect.exit(188+ accounts.setEmail(189+ Handle.make("nobody"),190+ Email.make("n@mail.example")191+ )192+ )193+ ).toStrictEqual(194+ Exit.fail(new EmailTaken({ email: Email.make("n@mail.example") }))195+ );196+ }).pipe(Effect.provide(layer))197+ );198 });199 };200 201 describeAccounts("memory", Layer.fresh(AccountsMemory.layer));3 unmodified lines205 const fs = yield* FileSystem.FileSystem;206 207 const sql = yield* SqlClient;208 209+ for (const migration of ["0002_accounts.sql", "0006_account_email.sql"]) {107- const ddl = yield* fs.readFileString(108- new URL("../migrations/0002_accounts.sql", import.meta.url).pathname109- );210+ const ddl = yield* fs.readFileString(211+ new URL(`../migrations/${migration}`, import.meta.url).pathname212+ );213 214+ // One statement a call; a comment may hold a semicolon, so comments go first.215+ const statements = ddl216+ .split("\n")217+ .filter((line) => !line.startsWith("--"))218+ .join("\n")219+ .split(";")220+ .filter((part) => part.trim() !== "");221+222+ for (const statement of statements) {111- yield* sql.unsafe(ddl);223+ yield* sql.unsafe(statement);224+ }225+ }226 })227 ).pipe(Layer.orDie, Layer.provide(NodeServices.layer));228 229 const database = migrated.pipe(5 unmodified linesmodified:apps/platform/test/bindings.test.ts+6 added
21 unmodified lines22 import type { DoProjects } from "../src/adapters/do-projects.ts";23 import type { LanderSandbox } from "../src/adapters/lander-sandbox.ts";24 import type { WorkerRateLimits } from "../src/adapters/rate-limits.ts";25 import type { SignInAttemptsBinding } from "../src/auth/attempts/binding.ts";26+import type { MailerBinding } from "../src/auth/mailer/binding.ts";27 import type { tokenReader } from "../src/auth/provider.ts";28 import {29 PlatformBindings,30 PlatformSecrets,73 unmodified lines104 durable_objects: Schema.optionalKey(Schema.Struct({ bindings: Named })),105 kv_namespaces: Schema.optionalKey(Bound),106 r2_buckets: Schema.optionalKey(Bound),107 ratelimits: Schema.optionalKey(Named),108+ send_email: Schema.optionalKey(Named),109 services: Schema.optionalKey(Bound),110 worker_loaders: Schema.optionalKey(Bound),111 workflows: Schema.optionalKey(Bound),112 });48 unmodified lines161 ...(block.durable_objects?.bindings ?? []).map(({ name }) => name),162 ...(block.kv_namespaces ?? []).map(({ binding }) => binding),163 ...(block.r2_buckets ?? []).map(({ binding }) => binding),164 ...(block.ratelimits ?? []).map(({ name }) => name),165+ ...(block.send_email ?? []).map(({ name }) => name),166 ...(block.services ?? []).map(({ binding }) => binding),167 ...(block.worker_loaders ?? []).map(({ binding }) => binding),168 ...(block.workflows ?? []).map(({ binding }) => binding),169 ]),267 unmodified lines437 >();438 expectTypeOf<Env["SIGN_IN_LIMIT"]>().toExtend<439 Parameters<typeof SignInAttemptsBinding>[0]440 >();441+ expectTypeOf<Env["EMAIL"]>().toExtend<442+ Parameters<typeof MailerBinding>[0]443+ >();444 expectTypeOf<Env["CODE_CACHE"]>().toExtend<445 Parameters<typeof CodeStoreR2>[0]446 >();447 expectTypeOf<PlatformConfig["CODE_CACHE"]>().toEqualTypeOf<46 unmodified linesmodified:apps/platform/test/fake-env.ts+1 added
126 unmodified lines127 CODE_CACHE: untouchable("CODE_CACHE"),128 COOKIE_KEY: cookieKey,129 DRAFT_LIMIT: untouchable("DRAFT_LIMIT"),130 DRAFT_MODEL: "@cf/moonshotai/kimi-k2.7-code",131+ EMAIL: untouchable("EMAIL"),132 EVIDENCE: untouchable("EVIDENCE"),133 FRONT_PAGE: untouchable("FRONT_PAGE"),134 LANDER_ADAPTER: "container",135 LOADER: untouchable("LOADER"),27 unmodified linesmodified:apps/platform/test/google.fixtures.ts+26 added-3 removed
7 unmodified lines8 import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";9 import { GOOGLE_DISCOVERY } from "../src/auth/google.ts";10 import { Identities } from "../src/auth/identities.ts";11 import { IdentitiesMemory } from "../src/auth/identities/memory.ts";12+import { MailerMemory } from "../src/auth/mailer/memory.ts";13 import { OAuthStore } from "../src/auth/oauth-store.ts";14 import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";15 import { oauthProvider, signInSettings } from "../src/auth/provider.ts";16 import { decodeEnv } from "../src/platform.ts";73 unmodified lines90 91 export interface Claims {92 readonly aud?: string | readonly string[];93 readonly azp?: string | undefined;94+ readonly email?: string | undefined;95+ readonly email_verified?: boolean | undefined;96 readonly exp?: number;97 readonly iss?: string;98+ readonly name?: string | undefined;99 readonly nonce?: string;100 }101 102+// What Google says of a subject unless a consent says otherwise: a verified103+// address and a name, as `openid email profile` gets for a Gmail account.104+export const googleEmailOf = (sub: string) => `person-${sub}@mail.example`;105+106+export const googleNameOf = (sub: string) => `Person ${sub}`;107+108 export interface Consent {109 readonly claims?: Claims;110 readonly kid?: string;111 readonly signWith?: KeyPair;6 unmodified lines118 code_challenge_method: Schema.Literal("S256"),119 nonce: Schema.String,120 redirect_uri: Schema.String,121 response_type: Schema.Literal("code"),112- scope: Schema.Literal("openid"),122+ scope: Schema.Literal("openid email profile"),123 state: Schema.String,124 });125 126 const decodeAuthorizationRequest =53 unmodified lines180 utf8(181 JSON.stringify({182 aud: clientId,183 azp: clientId,184+ email: googleEmailOf(consent.sub),185+ email_verified: true,186 exp: now + 3600,187 iat: now,188 iss: "https://accounts.google.com",189+ name: googleNameOf(consent.sub),190 nonce: grant.request.nonce,191 sub: consent.sub,192 ...consent.claims,193 })50 unmodified lines244 return Response.json({245 access_token: "ya29.a-google-access-token",246 expires_in: 3599,247 id_token: yield* idToken(grant.value),235- scope: "openid",248+ scope: "openid email profile",249 token_type: "Bearer",250 });251 });252 162 unmodified lines415 );416 417 const store = OAuthStoreMemory.make();418 419+ const mailer = yield* MailerMemory.make();420+421 const { dispose, handler } = oauthProvider(422 Layer.mergeAll(423 Layer.succeed(Accounts, accounts),424 Layer.succeed(Identities, identities),425+ mailer.layer,426 Layer.succeed(OAuthStore, store),427 Layer.succeed(Fetch, google.fetch),428 SignInAttemptsMemory.layer,429 signInSettings(config)18 unmodified lines448 Effect.andThen(Effect.sync(() => vi.unstubAllGlobals()))449 )450 );451 436- return { accounts, browser: browserFor(handle), google, identities, store };452+ return {453+ accounts,454+ browser: browserFor(handle),455+ google,456+ identities,457+ mails: mailer.sent,458+ store,459+ };460 });461 462 export type GoogleWorld = Effect.Success<ReturnType<typeof googleWorld>>;modified:apps/platform/test/google.test.ts+218 added-40 removed
14 unmodified lines15 } from "effect";16 import { SqlClient } from "effect/sql/SqlClient";17 18 import { IdentitiesD1 } from "../src/adapters/identities-d1.ts";19+import { Email } from "../src/auth/accounts.ts";20 import {21 GOOGLE_DISCOVERY,22 googleAuthorizeUrl,23 GoogleKeysPerIsolate,23- googleSubject,24+ googlePerson,25 } from "../src/auth/google.ts";26 import type { GoogleKeys } from "../src/auth/google.ts";27 import { Identities, IdentityTaken } from "../src/auth/identities.ts";28 import { IdentitiesMemory } from "../src/auth/identities/memory.ts";6 unmodified lines35 import {36 clientId,37 clientSecret,38 fakeGoogle,39+ googleEmailOf,40 googleEnv,41+ googleNameOf,42 googleWorld,43 jwksUri,44 } from "./google.fixtures.ts";45 import type {188 unmodified lines234 235 const nonce = "nonce-0123456789abcdef";236 237 describe("Google's authorization request", () => {235- it("asks for a code with openid only, PKCE by S256, the state and the nonce", () => {238+ it("asks for a code with openid, email and profile, PKCE by S256, the state and the nonce", () => {239 const url = new URL(240 googleAuthorizeUrl({241 clientId,242 codeChallenge: challenge,14 unmodified lines257 code_challenge_method: "S256",258 nonce: "nonce-0123456789abcdef",259 redirect_uri: "https://platform.test/oauth/google/callback",260 response_type: "code",258- scope: "openid",261+ scope: "openid email profile",262 state: "sealed-state",263 },264 ]);265 });6 unmodified lines272 code_challenge_method: "S256",273 nonce,274 redirect_uri: callbackUri,275 response_type: "code",273- scope: "openid",276+ scope: "openid email profile",277 state: "sealed-state",278 }).toString()}`279 ).toString();280 278-const subjectOf = (281+const personOf = (282 google: FakeGoogle,283 consent: Consent,284 kept: { readonly codeVerifier?: string; readonly nonce?: string } = {}285 ) =>286 Effect.gen(function* () {287 const back = yield* google.consent(authorizationRequest, consent);288 286- return yield* googleSubject({289+ return yield* googlePerson({290 clientId,291 clientSecret: Redacted.make(clientSecret),292 code: back.searchParams.get("code") ?? "",293 codeVerifier: kept.codeVerifier ?? verifier,1 unmodified line295 redirectUri: callbackUri,296 });297 });298 299+const subjectOf = (300+ google: FakeGoogle,301+ consent: Consent,302+ kept: { readonly codeVerifier?: string; readonly nonce?: string } = {}303+) => Effect.map(personOf(google, consent, kept), ({ subject }) => subject);304+305 const withGoogle = <A, E>(306 body: (google: FakeGoogle) => Effect.Effect<A, E, Fetch | GoogleKeys>307 ) =>308 Effect.gen(function* () {8 unmodified lines317 );318 });319 320 describe("the person Google confirms", () => {321+ it.live(322+ "carries the ID token's email only when Google verified it, and its name",323+ () =>324+ withGoogle((google) =>325+ Effect.gen(function* () {326+ const verified = yield* personOf(google, { sub: "1042" });327+328+ const unverified = yield* personOf(google, {329+ claims: { email_verified: false },330+ sub: "1042",331+ });332+333+ const malformed = yield* personOf(google, {334+ claims: { email: "not an address" },335+ sub: "1042",336+ });337+338+ const bare = yield* personOf(google, {339+ claims: { email: undefined, name: undefined },340+ sub: "1042",341+ });342+343+ expect([344+ verified,345+ unverified.email,346+ malformed.email,347+ bare,348+ ]).toStrictEqual([349+ {350+ email: Option.some(googleEmailOf("1042")),351+ name: Option.some(googleNameOf("1042")),352+ subject: "1042",353+ },354+ Option.none(),355+ Option.none(),356+ { email: Option.none(), name: Option.none(), subject: "1042" },357+ ]);358+ })359+ )360+ );361+362 it.live("is the ID token's subject, once its signature and claims hold", () =>363 withGoogle((google) =>364 Effect.gen(function* () {365 expect(yield* subjectOf(google, { sub: "1042" })).toBe("1042");252 unmodified lines618 })619 );620 621 it.live(572- "sends the person to Google for a code, with openid only, PKCE by S256, a sealed state and a nonce",622+ "sends the person to Google for a code, with openid, email and profile, PKCE by S256, a sealed state and a nonce",623 () =>624 Effect.gen(function* () {625 const world = yield* googleWorld();626 20 unmodified lines647 302,648 "https://accounts.google.com/o/oauth2/v2/auth",649 clientId,650 "code",601- "openid",651+ "openid email profile",652 "S256",653 43,654 `${origin}/oauth/google/callback`,655 true,57 unmodified lines713 Effect.flatMap(read)714 );715 });716 667-const chooseHandle = (world: GoogleWorld, page: Page, handle: string) =>717+const chooseHandle = (718+ world: GoogleWorld,719+ page: Page,720+ handle: string,721+ displayName = "Carol Example"722+) =>723 Effect.gen(function* () {724 const form = yield* formIn(page);725 726 return yield* visit(727 world,728 formPost("/oauth/google/handle", {729 csrf: form.csrf,730+ displayName,731 handle,732 request: form.request,733 })734 );20 unmodified lines755 756 return summary?.grant.props;757 });758 703-const isPickHandle = (page: Page) => page.html.includes("Choose your handle");759+const isPickHandle = (page: Page) => page.html.includes("Set up your profile");760 761 describe("coming back from Google", () => {762 it.live(707- "asks a first-time Google account for a handle, then signs it in as that handle",763+ "asks a first-time Google account for a handle and a name, Google's filled in, then signs it in as that handle with Google's email",764 () =>765 Effect.gen(function* () {766 const world = yield* googleWorld();767 2 unmodified lines770 yield* continueWithGoogle(world),771 { sub: "1042" }772 );773 718- expect([page.response.status, isPickHandle(page)]).toStrictEqual([719- 200,720- true,721- ]);774+ expect([775+ page.response.status,776+ isPickHandle(page),777+ page.html.includes(`value="${googleNameOf("1042")}"`),778+ ]).toStrictEqual([200, true, true]);779 780 const signedIn = yield* chooseHandle(world, page, "carol");781 782 expect(signedIn.status).toBe(302);783 expect(yield* propsFor(world, signedIn)).toStrictEqual({784 handle: "carol",785 });786+ expect(yield* world.accounts.find(Handle.make("carol"))).toMatchObject(787+ Option.some({788+ displayName: "Carol Example",789+ email: googleEmailOf("1042"),790+ })791+ );792 expect(730- Option.isSome(yield* world.accounts.find(Handle.make("carol")))731- ).toBeTruthy();732- expect(793 yield* world.identities.handleOf("google", "1042")794 ).toStrictEqual(Option.some(Handle.make("carol")));795 })796 );44 unmodified lines841 842 const second = new Request(843 formPost("/oauth/google/handle", {844 csrf: form.csrf,845+ displayName: "Carol Example",846 handle: "carol",847 request: form.request,848 }),849 {51 unmodified lines901 () =>902 Effect.gen(function* () {903 const world = yield* googleWorld();904 844- yield* world.accounts.create(845- Handle.make("carol"),846- yield* hashPassword(905+ yield* world.accounts.create({906+ handle: Handle.make("carol"),907+ hash: yield* hashPassword(908 Redacted.make(passwordPepper),909 Redacted.make(alicePassword)849- )850- );910+ ),911+ });912 913 const page = yield* backFromGoogle(914 world,915 yield* continueWithGoogle(world),14 unmodified lines930 })931 );932 });933 934+const withAlice = (world: GoogleWorld) =>935+ Effect.gen(function* () {936+ yield* world.accounts.create({937+ handle: Handle.make("alice"),938+ hash: yield* hashPassword(939+ Redacted.make(passwordPepper),940+ Redacted.make(alicePassword)941+ ),942+ });943+ });944+945+describe("Google's email", () => {946+ it.live(947+ "signs straight into the account that proved the same address, and links Google to it",948+ () =>949+ Effect.gen(function* () {950+ const world = yield* googleWorld();951+952+ yield* world.accounts.create({953+ email: Email.make(googleEmailOf("1042").toUpperCase()),954+ handle: Handle.make("alice"),955+ hash: yield* hashPassword(956+ Redacted.make(passwordPepper),957+ Redacted.make(alicePassword)958+ ),959+ });960+961+ const page = yield* backFromGoogle(962+ world,963+ yield* continueWithGoogle(world),964+ { sub: "1042" }965+ );966+967+ expect(page.response.status).toBe(302);968+ expect(yield* propsFor(world, page.response)).toStrictEqual({969+ handle: "alice",970+ });971+ expect(972+ yield* world.identities.handleOf("google", "1042")973+ ).toStrictEqual(Option.some(Handle.make("alice")));974+ })975+ );976+977+ it.live(978+ "makes no account for a Google account whose email Google did not verify",979+ () =>980+ Effect.gen(function* () {981+ const world = yield* googleWorld();982+983+ const page = yield* backFromGoogle(984+ world,985+ yield* continueWithGoogle(world),986+ { claims: { email_verified: false }, sub: "1042" }987+ );988+989+ expect([990+ page.response.status,991+ page.html.includes("did not share a verified email"),992+ isPickHandle(page),993+ Option.isNone(codeOf(page.response)),994+ ]).toStrictEqual([401, true, false, true]);995+ expect(996+ yield* world.identities.handleOf("google", "1042")997+ ).toStrictEqual(Option.none());998+ })999+ );1000+1001+ it.live(1002+ "asks an account linked before emails for one, when another account holds Google's",1003+ () =>1004+ Effect.gen(function* () {1005+ const world = yield* googleWorld();1006+1007+ yield* withAlice(world);1008+ yield* world.identities.link("google", "5150", Handle.make("alice"));1009+ yield* world.accounts.create({1010+ email: Email.make(googleEmailOf("5150")),1011+ handle: Handle.make("bob"),1012+ hash: yield* hashPassword(1013+ Redacted.make(passwordPepper),1014+ Redacted.make(alicePassword)1015+ ),1016+ });1017+1018+ const page = yield* backFromGoogle(1019+ world,1020+ yield* continueWithGoogle(world),1021+ { sub: "5150" }1022+ );1023+1024+ expect([1025+ page.response.status,1026+ page.html.includes("Add your email"),1027+ Option.isNone(codeOf(page.response)),1028+ ]).toStrictEqual([200, true, true]);1029+ })1030+ );1031+1032+ it.live("refuses a display name by sign-up's rule, and asks again", () =>1033+ Effect.gen(function* () {1034+ const world = yield* googleWorld();1035+1036+ const page = yield* backFromGoogle(1037+ world,1038+ yield* continueWithGoogle(world),1039+ { sub: "1042" }1040+ );1041+1042+ const refused = yield* chooseHandle(world, page, "carol", " ").pipe(1043+ Effect.flatMap(read)1044+ );1045+1046+ expect([1047+ refused.response.status,1048+ isPickHandle(refused),1049+ refused.html.includes("display name"),1050+ ]).toStrictEqual([400, true, true]);1051+ })1052+ );1053+});1054+1055 describe("Google not confirming anyone", () => {1056 it.live.each([1057 ["a signature by another key", "impostor"],1058 ["another client's audience", "audience"],114 unmodified lines1173 })1174 );1175 });1176 995-const withAlice = (world: GoogleWorld) =>996- Effect.gen(function* () {997- yield* world.accounts.create(998- Handle.make("alice"),999- yield* hashPassword(1000- Redacted.make(passwordPepper),1001- Redacted.make(alicePassword)1002- )1003- );1004- });1005-1177 const signInAndLink = (world: GoogleWorld, handle: string, password: string) =>1178 Effect.gen(function* () {1179 const form = yield* formIn(yield* openSignIn(world));1180 1181 return yield* visit(1182 world,1183 formPost("/oauth/google/link", {1184 csrf: form.csrf,1014- handle,1185+ login: handle,1186 password,1187 request: form.request,1188 })1189 );19 unmodified lines1209 expect(linked.response.status).toBe(302);1210 expect(yield* propsFor(world, linked.response)).toStrictEqual({1211 handle: "alice",1212 });1042- expect(1043- yield* world.identities.handleOf("google", "5150")1044- ).toStrictEqual(Option.some(Handle.make("alice")));1213+ expect([1214+ yield* world.identities.handleOf("google", "5150"),1215+ Option.flatMap(1216+ yield* world.accounts.find(Handle.make("alice")),1217+ ({ email }) => Option.fromUndefinedOr(email)1218+ ),1219+ ]).toStrictEqual([1220+ Option.some(Handle.make("alice")),1221+ Option.some(googleEmailOf("5150")),1222+ ]);1223 1224 const later = yield* backFromGoogle(1225 world,1226 yield* continueWithGoogle(world),19 unmodified lines1246 ).pipe(Effect.flatMap(read));1247 1248 expect([1249 page.response.status,1072- page.html.includes("The handle or password is wrong."),1250+ page.html.includes("The email, handle or password is wrong."),1251 Option.isNone(locationOf(page.response)),1252 ]).toStrictEqual([401, true, true]);1253 })1254 );44 unmodified lines1299 [1300 `/oauth/google/start?request=${encodeURIComponent(form.request)}`,1301 formPost("/authorize", {1302 csrf: form.csrf,1125- handle: "alice",1303+ login: "alice",1304 password: alicePassword,1305 request: form.request,1306 }),1307 ],15 unmodified linesadded:apps/platform/test/mailer.test.ts+90 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Brand } from "@repo/brand";3+import { Effect } from "effect";4+5+import { Email } from "../src/auth/accounts.ts";6+import { MailFailed, Mailer } from "../src/auth/mailer.ts";7+import { MAIL_FROM, MailerBinding } from "../src/auth/mailer/binding.ts";8+import { MailerMemory } from "../src/auth/mailer/memory.ts";9+10+const mail = {11+ subject: "123456 is your code",12+ text: "Your code is 123456.",13+ to: Email.make("alice@mail.example"),14+};15+16+const sendWith = (binding: SendEmail) =>17+ Mailer.use((mailer) => mailer.send(mail)).pipe(18+ Effect.provide(MailerBinding(binding))19+ );20+21+describe("the mailer over Email Service's binding", () => {22+ it.effect(23+ "sends plain text from the brand's no-reply address, to the one address",24+ () =>25+ Effect.gen(function* () {26+ const sent: unknown[] = [];27+28+ const binding: SendEmail = {29+ send: (message: EmailMessage | EmailMessageBuilder) => {30+ sent.push(message);31+32+ return Promise.resolve({ messageId: "message-1" });33+ },34+ };35+36+ yield* sendWith(binding);37+38+ expect(MAIL_FROM).toStrictEqual({39+ email: `no-reply@${Brand.domain}`,40+ name: Brand.name,41+ });42+ expect(sent).toStrictEqual([43+ {44+ from: MAIL_FROM,45+ subject: mail.subject,46+ text: mail.text,47+ to: mail.to,48+ },49+ ]);50+ })51+ );52+53+ it.effect("fails as MailFailed when the binding refuses", () =>54+ Effect.gen(function* () {55+ const binding: SendEmail = {56+ send: () => Promise.reject(new Error("E_SENDER_NOT_VERIFIED")),57+ };58+59+ expect(yield* Effect.flip(sendWith(binding))).toStrictEqual(60+ new MailFailed()61+ );62+ })63+ );64+});65+66+describe("the mailer in memory", () => {67+ it.effect(68+ "keeps each mail in the order sent, or fails each when told to",69+ () =>70+ Effect.gen(function* () {71+ const kept = yield* MailerMemory.make();72+73+ const failing = yield* MailerMemory.make({ failing: true });74+75+ yield* Mailer.use((mailer) => mailer.send(mail)).pipe(76+ Effect.provide(kept.layer)77+ );78+79+ expect(yield* kept.sent).toStrictEqual([mail]);80+ expect(81+ yield* Effect.flip(82+ Mailer.use((mailer) => mailer.send(mail)).pipe(83+ Effect.provide(failing.layer)84+ )85+ )86+ ).toStrictEqual(new MailFailed());87+ expect(yield* failing.sent).toStrictEqual([]);88+ })89+ );90+});modified:apps/platform/test/oauth.fixtures.ts+61 added-53 removed
6 unmodified lines7 import { AccountsMemory } from "../src/auth/accounts/memory.ts";8 import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";9 import { cliClientId } from "../src/auth/cli-client.ts";10 import { IdentitiesMemory } from "../src/auth/identities/memory.ts";11+import { MailerMemory } from "../src/auth/mailer/memory.ts";12 import { OAuthStore } from "../src/auth/oauth-store.ts";13 import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";14 import { oauthProvider, signInSettings } from "../src/auth/provider.ts";15 import { decodeEnv } from "../src/platform.ts";30 unmodified lines46 const decodeTokenRecord = Schema.decodeUnknownEffect(47 Schema.Record(Schema.String, Schema.Unknown)48 );49 50+export const signInWorld = (options: { readonly mailFails?: boolean } = {}) =>49-export const signInWorld = Effect.gen(function* () {50- const config = yield* decodeEnv(worldEnv()).pipe(Effect.orDie);51+ Effect.gen(function* () {52+ const config = yield* decodeEnv(worldEnv()).pipe(Effect.orDie);53 52- const accounts = yield* Effect.provide(53- Effect.service(Accounts),54- AccountsMemory.layer55- );54+ const accounts = yield* Effect.provide(55+ Effect.service(Accounts),56+ AccountsMemory.layer57+ );58 57- const store = OAuthStoreMemory.make();59+ const store = OAuthStoreMemory.make();60 59- const services = Layer.mergeAll(60- Layer.succeed(Accounts, accounts),61- Layer.succeed(OAuthStore, store),62- IdentitiesMemory.layer,63- Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch")),64- SignInAttemptsMemory.layer,65- signInSettings(config)66- );61+ const mailer = yield* MailerMemory.make({62+ failing: options.mailFails === true,63+ });64 68- const { dispose, handler } = oauthProvider(services, platformFetch);65+ const services = Layer.mergeAll(66+ Layer.succeed(Accounts, accounts),67+ mailer.layer,68+ Layer.succeed(OAuthStore, store),69+ IdentitiesMemory.layer,70+ Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch")),71+ SignInAttemptsMemory.layer,72+ signInSettings(config)73+ );74 70- const send = (request: Request) => handler.fetch(request, fakeEnv(), context);75+ const { dispose, handler } = oauthProvider(services, platformFetch);76 72- yield* Effect.acquireRelease(73- Effect.sync(() => {74- vi.stubGlobal("Cloudflare", {75- compatibilityFlags: { global_fetch_strictly_public: true },76- });77- vi.stubGlobal("fetch", (input: RequestInfo | URL) =>78- send(new Request(input))79- );80- }),81- () =>82- Effect.promise(dispose).pipe(83- Effect.andThen(Effect.sync(() => vi.unstubAllGlobals()))84- )85- );77+ const send = (request: Request) =>78+ handler.fetch(request, fakeEnv(), context);79 87- const fetch = (request: Request) => Effect.promise(() => send(request));88-89- const expireTokens = Effect.gen(function* () {90- const { keys } = yield* Effect.promise(() =>91- store.list({ prefix: "token:" })80+ yield* Effect.acquireRelease(81+ Effect.sync(() => {82+ vi.stubGlobal("Cloudflare", {83+ compatibilityFlags: { global_fetch_strictly_public: true },84+ });85+ vi.stubGlobal("fetch", (input: RequestInfo | URL) =>86+ send(new Request(input))87+ );88+ }),89+ () =>90+ Effect.promise(dispose).pipe(91+ Effect.andThen(Effect.sync(() => vi.unstubAllGlobals()))92+ )93 );94 94- const now = yield* Clock.currentTimeMillis;95+ const fetch = (request: Request) => Effect.promise(() => send(request));96 96- for (const { metadata, name } of keys) {97- const token = yield* Effect.promise(() =>98- store.get(name, { type: "json" })99- ).pipe(Effect.flatMap(decodeTokenRecord), Effect.orDie);100-101- yield* Effect.promise(() =>102- store.put(103- name,104- JSON.stringify({ ...token, expiresAt: Math.floor(now / 1000) - 1 }),105- { metadata }106- )97+ const expireTokens = Effect.gen(function* () {98+ const { keys } = yield* Effect.promise(() =>99+ store.list({ prefix: "token:" })100 );108- }109- });101 111- return { accounts, expireTokens, fetch, store };112-});102+ const now = yield* Clock.currentTimeMillis;103 114-export type World = Effect.Success<typeof signInWorld>;104+ for (const { metadata, name } of keys) {105+ const token = yield* Effect.promise(() =>106+ store.get(name, { type: "json" })107+ ).pipe(Effect.flatMap(decodeTokenRecord), Effect.orDie);108 109+ yield* Effect.promise(() =>110+ store.put(111+ name,112+ JSON.stringify({ ...token, expiresAt: Math.floor(now / 1000) - 1 }),113+ { metadata }114+ )115+ );116+ }117+ });118+119+ return { accounts, expireTokens, fetch, mails: mailer.sent, store };120+ });121+122+export type World = Effect.Success<ReturnType<typeof signInWorld>>;123+124 export interface SignInForm {125 readonly cookie: string;126 readonly csrf: string;127 readonly request: string;79 unmodified linesmodified:apps/platform/test/oauth.test.ts+676 added-32 removed
5 unmodified lines6 import { Effect, Option, Redacted, Schema } from "effect";7 import { TestClock } from "effect/testing";8 9 import { OAuthSessions } from "../src/adapters/sessions-oauth.ts";10+import { Email } from "../src/auth/accounts.ts";11 import { SignInAttempts } from "../src/auth/attempts.ts";12 import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";13 import { cliClientMetadata } from "../src/auth/cli-client.ts";14+import { codeMatches, codeTag, deadTag, freshCode } from "../src/auth/codes.ts";15+import type { CodePurpose } from "../src/auth/codes.ts";16+import { ACCOUNT_PATHS } from "../src/auth/pages.ts";17 import {18 hashPassword,19 hashPasswordWith,20 PasswordHash,287 unmodified lines308 Effect.fromOption(formOf(page.response, page.html, cookie)).pipe(309 Effect.orDie310 );311 308-const signUp = (world: World, handle: string, secret: string) =>312+// A valid address for any handle a test tries, valid or not.313+const emailOf = (handle: string) =>314+ `${handle.toLowerCase().replaceAll(/[^a-z0-9]/gu, "-")}@mail.example`;315+316+// The code in the newest mail to `to`; a mail with no code reads as none.317+const codeMailedTo = (world: World, to: string) =>318+ Effect.map(world.mails, (mails) =>319+ Option.fromNullishOr(320+ mails321+ .findLast((mail) => mail.to === to)322+ ?.subject.match(/^(?<code>\d{6}) /u)?.groups?.code323+ )324+ );325+326+interface Started {327+ readonly cookie: string;328+ readonly page: Page;329+}330+331+const startSignUp = (332+ world: World,333+ fields: {334+ readonly displayName?: string;335+ readonly email: string;336+ readonly handle: string;337+ readonly password: string;338+ }339+) =>340 Effect.gen(function* () {341 const signInForm = yield* formIn(yield* openSignIn(world));342 343 const page = yield* world8 unmodified lines352 .pipe(Effect.flatMap(read));353 354 const form = yield* formIn(page, signInForm.cookie);355 356+ const started = yield* world357+ .fetch(358+ post(359+ "/signup",360+ {361+ csrf: form.csrf,362+ displayName: fields.displayName ?? "Alice Example",363+ email: fields.email,364+ handle: fields.handle,365+ password: fields.password,366+ request: form.request,367+ },368+ form.cookie369+ )370+ )371+ .pipe(Effect.flatMap(read));372+373+ return { cookie: form.cookie, page: started } satisfies Started;374+ });375+376+const enterCode = (377+ world: World,378+ started: Started,379+ path: string,380+ code: string,381+ extra: Readonly<Record<string, string>> = {}382+) =>383+ Effect.gen(function* () {384+ const form = yield* formIn(started.page, started.cookie);385+386 return yield* world.fetch(387 post(327- "/signup",328- { csrf: form.csrf, handle, password: secret, request: form.request },388+ path,389+ { code, csrf: form.csrf, request: form.request, ...extra },390 form.cookie391 )392 );393 });394 395+// The whole sign-up: the form, then the code mailed to the address. A form396+// the platform refuses comes back as it is.334-const signIn = (397+const signUp = (398 world: World,399 handle: string,400 secret: string,401+ email = emailOf(handle)402+) =>403+ Effect.gen(function* () {404+ const started = yield* startSignUp(world, {405+ email,406+ handle,407+ password: secret,408+ });409+410+ // Read already, so handed back afresh.411+ if (started.page.response.status !== 200) {412+ return new Response(started.page.html, started.page.response);413+ }414+415+ const code = yield* Effect.fromOption(416+ yield* codeMailedTo(world, email)417+ ).pipe(Effect.orDie);418+419+ return yield* enterCode(world, started, ACCOUNT_PATHS.signUpVerify, code);420+ });421+422+const signIn = (423+ world: World,424+ login: string,425+ secret: string,426 address?: string427 ) =>428 Effect.gen(function* () {429 const form = yield* formIn(yield* openSignIn(world));430 431 return yield* world.fetch(432 post(433 "/authorize",346- { csrf: form.csrf, handle, password: secret, request: form.request },434+ { csrf: form.csrf, login, password: secret, request: form.request },435 form.cookie,436 address437 )438 );27 unmodified lines466 467 describe("the platform as its own OAuth authorization server", () => {468 it.live("publishes where to authorize and where to get a token", () =>469 Effect.gen(function* () {382- const world = yield* signInWorld;470+ const world = yield* signInWorld();471 472 const response = yield* world.fetch(473 new Request(new URL("/.well-known/oauth-authorization-server", origin))474 );10 unmodified lines485 );486 487 it.live("serves the CLI's client metadata document at its client id", () =>488 Effect.gen(function* () {401- const world = yield* signInWorld;489+ const world = yield* signInWorld();490 491 const response = yield* world.fetch(new Request(cliClient));492 493 expect(response.status).toBe(200);4 unmodified lines498 );499 500 it.live("hands every other path to the rest of the platform", () =>501 Effect.gen(function* () {414- const world = yield* signInWorld;502+ const world = yield* signInWorld();503 504 const page = yield* world505 .fetch(new Request(new URL("/rpc", origin)))506 .pipe(Effect.flatMap(read));8 unmodified lines515 it.live(516 "shows the CLI a small sign-in page that loads nothing and cannot be framed",517 () =>518 Effect.gen(function* () {431- const world = yield* signInWorld;519+ const world = yield* signInWorld();520 521 const page = yield* openSignIn(world);522 523 expect([16 unmodified lines540 it.live(541 "lets the code go back to an IPv6 loopback, which no CSP host can name",542 () =>543 Effect.gen(function* () {456- const world = yield* signInWorld;544+ const world = yield* signInWorld();545 546 const page = yield* world547 .fetch(548 new Request(48 unmodified lines597 it.live(598 "creates the account and signs it in, back to the CLI with a code",599 () =>600 Effect.gen(function* () {513- const world = yield* signInWorld;601+ const world = yield* signInWorld();602 603 const response = yield* signUp(world, "alice", alicePassword);604 605 expect(response.status).toBe(302);2 unmodified lines608 new URL(response.headers.get("location") ?? "").searchParams.get(609 "state"610 )611 ).toBe("state-1");524- expect(525- Option.isSome(yield* world.accounts.find(Handle.make("alice")))526- ).toBeTruthy();612+ expect(yield* world.accounts.find(Handle.make("alice"))).toMatchObject(613+ Option.some({614+ displayName: "Alice Example",615+ email: emailOf("alice"),616+ handle: "alice",617+ })618+ );619 })620 );621 622 it.live("says a handle is taken, in any case", () =>623 Effect.gen(function* () {532- const world = yield* signInWorld;624+ const world = yield* signInWorld();625 626 yield* signUp(world, "alice", alicePassword);627 628 const page = yield* signUp(world, "ALICE", "another long password").pipe(9 unmodified lines638 it.live(639 "says the operator's handle and a named session's are taken, in any case",640 () =>641 Effect.gen(function* () {550- const world = yield* signInWorld;642+ const world = yield* signInWorld();643 644 const pages = yield* Effect.forEach(645 [fakeEnv().OPERATOR_HANDLE.toUpperCase(), namedPerson],646 (handle) =>26 unmodified lines673 ])(674 "refuses the handle %s with a plain reason",675 ([handle = "", reason = ""]) =>676 Effect.gen(function* () {585- const world = yield* signInWorld;677+ const world = yield* signInWorld();678 679 const page = yield* signUp(world, handle, alicePassword).pipe(680 Effect.flatMap(read)681 );5 unmodified lines687 );688 689 it.live("refuses a password under 12 or over 256 characters", () =>690 Effect.gen(function* () {599- const world = yield* signInWorld;691+ const world = yield* signInWorld();692 693 const short = yield* signUp(world, "alice", "elevenchars").pipe(694 Effect.flatMap(read)695 );18 unmodified lines714 it.live(715 "trades a code and its verifier for an access token that names only the person",716 () =>717 Effect.gen(function* () {626- const world = yield* signInWorld;718+ const world = yield* signInWorld();719 720 yield* signUp(world, "Alice", alicePassword);721 722 const { access_token, token_type } = yield* accessTokenFor(15 unmodified lines738 it.live(739 "says only that the handle or password is wrong, and issues no code",740 () =>741 Effect.gen(function* () {650- const world = yield* signInWorld;742+ const world = yield* signInWorld();743 744 yield* signUp(world, "alice", alicePassword);745 746 const wrong = yield* signIn(world, "alice", "not the password").pipe(5 unmodified lines752 );753 754 for (const page of [wrong, nobody]) {755 expect(page.response.status).toBe(401);664- expect(page.html).toContain("The handle or password is wrong.");756+ expect(page.html).toContain(757+ "The email, handle or password is wrong."758+ );759 expect(Option.isNone(codeOf(page.response))).toBeTruthy();760 expect(761 Option.isSome(formOf(page.response, page.html, "cookie"))762 ).toBeTruthy();2 unmodified lines765 );766 767 it.live("refuses a code traded with the wrong verifier", () =>768 Effect.gen(function* () {675- const world = yield* signInWorld;769+ const world = yield* signInWorld();770 771 const code = yield* signUp(world, "alice", alicePassword).pipe(772 Effect.flatMap(codeIn)773 );15 unmodified lines789 it.live(790 "refuses a form it did not seal, or whose CSRF token does not match, and issues no code",791 () =>792 Effect.gen(function* () {699- const world = yield* signInWorld;793+ const world = yield* signInWorld();794 795 yield* signUp(world, "alice", alicePassword);796 797 const form = yield* formIn(yield* openSignIn(world));15 unmodified lines813 post(814 "/authorize",815 {816 csrf: attempt.csrf,723- handle: "alice",817+ login: "alice",818 password: alicePassword,819 request: attempt.request,820 },821 attempt.cookie11 unmodified lines833 it.live(834 "refuses the sixth attempt in a minute for one handle before checking the password",835 () =>836 Effect.gen(function* () {743- const world = yield* signInWorld;837+ const world = yield* signInWorld();838 839 yield* signUp(world, "alice", alicePassword);840 841 const statuses = yield* Effect.forEach([1, 2, 3, 4, 5], (n) =>17 unmodified lines859 );860 861 it.live("refuses the sixth attempt in a minute from one address", () =>862 Effect.gen(function* () {769- const world = yield* signInWorld;863+ const world = yield* signInWorld();864 865 const statuses = yield* Effect.forEach(866 ["bob", "carol", "dave", "erin", "frank", "grace"],867 (handle) =>9 unmodified lines877 it.live(878 "replaces a password hash made with fewer iterations than today's",879 () =>880 Effect.gen(function* () {787- const world = yield* signInWorld;881+ const world = yield* signInWorld();882 883 const alice = Handle.make("alice");884 791- yield* world.accounts.create(792- alice,793- yield* hashPasswordWith(1000)(pepper, Redacted.make(alicePassword))794- );885+ yield* world.accounts.create({886+ email: Email.make(emailOf("alice")),887+ handle: alice,888+ hash: yield* hashPasswordWith(1000)(889+ pepper,890+ Redacted.make(alicePassword)891+ ),892+ });893 894 yield* signIn(world, "alice", alicePassword).pipe(895 Effect.flatMap(codeIn)896 );11 unmodified lines908 it.live(909 "know the person an access token was issued to, and nobody by a changed or expired one",910 () =>911 Effect.gen(function* () {814- const world = yield* signInWorld;912+ const world = yield* signInWorld();913 914 yield* signUp(world, "alice", alicePassword);915 916 const { access_token } = yield* accessTokenFor(18 unmodified lines935 );936 })937 );938 });939+940+describe("confirming a sign-up's email", () => {941+ it.live(942+ "mails the address a code and makes no account until the code comes back",943+ () =>944+ Effect.gen(function* () {945+ const world = yield* signInWorld();946+947+ const started = yield* startSignUp(world, {948+ email: "Alice@Mail.Example",949+ handle: "alice",950+ password: alicePassword,951+ });952+953+ const [mail] = yield* world.mails;954+955+ expect(started.page.response.status).toBe(200);956+ expect(started.page.html).toContain(957+ "We mailed a code to Alice@Mail.Example."958+ );959+ expect(mail?.to).toBe("Alice@Mail.Example");960+ expect(mail?.text).toContain(961+ /^(?<code>\d{6}) is your /u.exec(mail?.subject ?? "")?.groups?.code962+ );963+ expect(yield* world.accounts.find(Handle.make("alice"))).toStrictEqual(964+ Option.none()965+ );966+ })967+ );968+969+ it.live("refuses a wrong code, and makes no account", () =>970+ Effect.gen(function* () {971+ const world = yield* signInWorld();972+973+ const started = yield* startSignUp(world, {974+ email: emailOf("alice"),975+ handle: "alice",976+ password: alicePassword,977+ });978+979+ const code = yield* Effect.fromOption(980+ yield* codeMailedTo(world, emailOf("alice"))981+ ).pipe(Effect.orDie);982+983+ const wrong = code === "000000" ? "000001" : "000000";984+985+ const page = yield* enterCode(986+ world,987+ started,988+ ACCOUNT_PATHS.signUpVerify,989+ wrong990+ ).pipe(Effect.flatMap(read));991+992+ expect(page.response.status).toBe(401);993+ expect(page.html).toContain("That code is wrong or has expired.");994+ expect(Option.isNone(codeOf(page.response))).toBeTruthy();995+ expect(yield* world.accounts.find(Handle.make("alice"))).toStrictEqual(996+ Option.none()997+ );998+ })999+ );1000+1001+ it.live("takes a code with spaces in it", () =>1002+ Effect.gen(function* () {1003+ const world = yield* signInWorld();1004+1005+ const started = yield* startSignUp(world, {1006+ email: emailOf("alice"),1007+ handle: "alice",1008+ password: alicePassword,1009+ });1010+1011+ const code = yield* Effect.fromOption(1012+ yield* codeMailedTo(world, emailOf("alice"))1013+ ).pipe(Effect.orDie);1014+1015+ const response = yield* enterCode(1016+ world,1017+ started,1018+ ACCOUNT_PATHS.signUpVerify,1019+ `${code.slice(0, 3)} ${code.slice(3)}`1020+ );1021+1022+ expect(Option.isSome(codeOf(response))).toBeTruthy();1023+ })1024+ );1025+1026+ it.live("refuses the sixth code tried for one address in a minute", () =>1027+ Effect.gen(function* () {1028+ const world = yield* signInWorld();1029+1030+ const started = yield* startSignUp(world, {1031+ email: emailOf("alice"),1032+ handle: "alice",1033+ password: alicePassword,1034+ });1035+1036+ const code = yield* Effect.fromOption(1037+ yield* codeMailedTo(world, emailOf("alice"))1038+ ).pipe(Effect.orDie);1039+1040+ const wrong = code === "000000" ? "000001" : "000000";1041+1042+ const statuses = yield* Effect.forEach([1, 2, 3, 4, 5], () =>1043+ enterCode(world, started, ACCOUNT_PATHS.signUpVerify, wrong).pipe(1044+ Effect.map(({ status }) => status)1045+ )1046+ );1047+1048+ const sixth = yield* enterCode(1049+ world,1050+ started,1051+ ACCOUNT_PATHS.signUpVerify,1052+ code1053+ );1054+1055+ expect([...statuses, sixth.status]).toStrictEqual([1056+ 401, 401, 401, 401, 401, 429,1057+ ]);1058+ })1059+ );1060+1061+ it.live(1062+ "mails the holder of a taken address a notice in place of a code, and reads the same to the one signing up",1063+ () =>1064+ Effect.gen(function* () {1065+ const world = yield* signInWorld();1066+1067+ yield* signUp(world, "alice", alicePassword);1068+1069+ const started = yield* startSignUp(world, {1070+ email: emailOf("alice").toUpperCase(),1071+ handle: "mallory",1072+ password: "another long password",1073+ });1074+1075+ const mails = yield* world.mails;1076+1077+ expect(started.page.response.status).toBe(200);1078+ expect(started.page.html).toContain("We mailed a code to");1079+ expect(mails.at(-1)?.subject).toContain("You already have");1080+ expect(mails.at(-1)?.text).not.toMatch(/\d{6}/u);1081+1082+ const page = yield* enterCode(1083+ world,1084+ started,1085+ ACCOUNT_PATHS.signUpVerify,1086+ "123456"1087+ );1088+1089+ expect([1090+ page.status,1091+ Option.isNone(yield* world.accounts.find(Handle.make("mallory"))),1092+ ]).toStrictEqual([401, true]);1093+ })1094+ );1095+1096+ it.live(1097+ "says so when someone took the handle while the code was in the mail",1098+ () =>1099+ Effect.gen(function* () {1100+ const world = yield* signInWorld();1101+1102+ const started = yield* startSignUp(world, {1103+ email: emailOf("first"),1104+ handle: "alice",1105+ password: alicePassword,1106+ });1107+1108+ yield* signUp(world, "alice", alicePassword, emailOf("second"));1109+1110+ const code = yield* Effect.fromOption(1111+ yield* codeMailedTo(world, emailOf("first"))1112+ ).pipe(Effect.orDie);1113+1114+ const page = yield* enterCode(1115+ world,1116+ started,1117+ ACCOUNT_PATHS.signUpVerify,1118+ code1119+ ).pipe(Effect.flatMap(read));1120+1121+ expect(page.response.status).toBe(409);1122+ expect(page.html).toContain("Someone took that handle");1123+ expect(page.html).toContain(`value="${emailOf("first")}"`);1124+ })1125+ );1126+1127+ it.live("says the mail could not go, and makes no account", () =>1128+ Effect.gen(function* () {1129+ const world = yield* signInWorld({ mailFails: true });1130+1131+ const started = yield* startSignUp(world, {1132+ email: emailOf("alice"),1133+ handle: "alice",1134+ password: alicePassword,1135+ });1136+1137+ expect(started.page.response.status).toBe(503);1138+ expect(started.page.html).toContain("We could not send the mail");1139+ expect(started.page.html).toContain(`value="${emailOf("alice")}"`);1140+ })1141+ );1142+1143+ it.live.each([1144+ ["not an address", { email: "alice" }, "does not look like an email"],1145+ ["an empty display name", { displayName: " " }, "display name"],1146+ ["a display name of 65", { displayName: "x".repeat(65) }, "display name"],1147+ ] as const)("refuses %s", ([, fields, said]) =>1148+ Effect.gen(function* () {1149+ const world = yield* signInWorld();1150+1151+ const started = yield* startSignUp(world, {1152+ email: emailOf("alice"),1153+ handle: "alice",1154+ password: alicePassword,1155+ ...fields,1156+ });1157+1158+ expect(started.page.response.status).toBe(400);1159+ expect(started.page.html).toContain(said);1160+ expect(yield* world.mails).toStrictEqual([]);1161+ })1162+ );1163+});1164+1165+describe("signing in by email", () => {1166+ it.live("signs in by the account's email, in any case", () =>1167+ Effect.gen(function* () {1168+ const world = yield* signInWorld();1169+1170+ yield* signUp(world, "Alice", alicePassword);1171+1172+ const { access_token } = yield* accessTokenFor(1173+ world,1174+ emailOf("alice").toUpperCase(),1175+ alicePassword1176+ );1177+1178+ const summary = yield* Effect.promise(() =>1179+ tokenReader(world.store).unwrapToken(access_token)1180+ );1181+1182+ expect(summary?.grant.props).toStrictEqual({ handle: "Alice" });1183+ })1184+ );1185+});1186+1187+const legacyAccount = (world: World) =>1188+ Effect.gen(function* () {1189+ yield* world.accounts.create({1190+ handle: Handle.make("alice"),1191+ hash: yield* hashPassword(pepper, Redacted.make(alicePassword)),1192+ });1193+ });1194+1195+describe("an account made before sign-up asked for an email", () => {1196+ it.live(1197+ "adds and confirms one after its password, before any code goes back",1198+ () =>1199+ Effect.gen(function* () {1200+ const world = yield* signInWorld();1201+1202+ yield* legacyAccount(world);1203+1204+ const asked = yield* signIn(world, "alice", alicePassword).pipe(1205+ Effect.flatMap(read)1206+ );1207+1208+ expect(asked.response.status).toBe(200);1209+ expect(asked.html).toContain("Add your email");1210+ expect(Option.isNone(codeOf(asked.response))).toBeTruthy();1211+1212+ const form = yield* formIn(asked);1213+1214+ const sent = yield* world1215+ .fetch(1216+ post(1217+ ACCOUNT_PATHS.addEmail,1218+ {1219+ csrf: form.csrf,1220+ email: emailOf("alice"),1221+ request: form.request,1222+ },1223+ form.cookie1224+ )1225+ )1226+ .pipe(Effect.flatMap(read));1227+1228+ const code = yield* Effect.fromOption(1229+ yield* codeMailedTo(world, emailOf("alice"))1230+ ).pipe(Effect.orDie);1231+1232+ const done = yield* enterCode(1233+ world,1234+ { cookie: form.cookie, page: sent },1235+ ACCOUNT_PATHS.addEmailVerify,1236+ code1237+ );1238+1239+ expect(Option.isSome(codeOf(done))).toBeTruthy();1240+ expect(yield* world.accounts.find(Handle.make("alice"))).toMatchObject(1241+ Option.some({ email: emailOf("alice") })1242+ );1243+ })1244+ );1245+1246+ it.live(1247+ "refuses an address another account holds, once the code proves it",1248+ () =>1249+ Effect.gen(function* () {1250+ const world = yield* signInWorld();1251+1252+ yield* signUp(world, "bob", alicePassword);1253+ yield* legacyAccount(world);1254+1255+ const asked = yield* signIn(world, "alice", alicePassword).pipe(1256+ Effect.flatMap(read)1257+ );1258+1259+ const form = yield* formIn(asked);1260+1261+ const sent = yield* world1262+ .fetch(1263+ post(1264+ ACCOUNT_PATHS.addEmail,1265+ { csrf: form.csrf, email: emailOf("bob"), request: form.request },1266+ form.cookie1267+ )1268+ )1269+ .pipe(Effect.flatMap(read));1270+1271+ const code = yield* Effect.fromOption(1272+ yield* codeMailedTo(world, emailOf("bob"))1273+ ).pipe(Effect.orDie);1274+1275+ const page = yield* enterCode(1276+ world,1277+ { cookie: form.cookie, page: sent },1278+ ACCOUNT_PATHS.addEmailVerify,1279+ code1280+ ).pipe(Effect.flatMap(read));1281+1282+ expect(page.response.status).toBe(409);1283+ expect(page.html).toContain("Another account already uses that email");1284+ expect(Option.isNone(codeOf(page.response))).toBeTruthy();1285+ })1286+ );1287+});1288+1289+const startReset = (world: World, email: string) =>1290+ Effect.gen(function* () {1291+ const signInForm = yield* formIn(yield* openSignIn(world));1292+1293+ const page = yield* world1294+ .fetch(1295+ new Request(1296+ new URL(1297+ `${ACCOUNT_PATHS.reset}?request=${encodeURIComponent(signInForm.request)}`,1298+ origin1299+ )1300+ )1301+ )1302+ .pipe(Effect.flatMap(read));1303+1304+ const form = yield* formIn(page, signInForm.cookie);1305+1306+ const sent = yield* world1307+ .fetch(1308+ post(1309+ ACCOUNT_PATHS.reset,1310+ { csrf: form.csrf, email, request: form.request },1311+ form.cookie1312+ )1313+ )1314+ .pipe(Effect.flatMap(read));1315+1316+ return { cookie: form.cookie, page: sent } satisfies Started;1317+ });1318+1319+describe("resetting a password", () => {1320+ it.live(1321+ "sets a new password by the code mailed to the account, and signs in",1322+ () =>1323+ Effect.gen(function* () {1324+ const world = yield* signInWorld();1325+1326+ yield* signUp(world, "alice", alicePassword);1327+1328+ const started = yield* startReset(world, emailOf("alice"));1329+1330+ const code = yield* Effect.fromOption(1331+ yield* codeMailedTo(world, emailOf("alice"))1332+ ).pipe(Effect.orDie);1333+1334+ const done = yield* enterCode(1335+ world,1336+ started,1337+ ACCOUNT_PATHS.resetVerify,1338+ code,1339+ { password: "a brand new password" }1340+ );1341+1342+ const old = yield* signIn(world, "alice", alicePassword);1343+1344+ const fresh = yield* signIn(world, "alice", "a brand new password");1345+1346+ expect(Option.isSome(codeOf(done))).toBeTruthy();1347+ expect(old.status).toBe(401);1348+ expect(Option.isSome(codeOf(fresh))).toBeTruthy();1349+ })1350+ );1351+1352+ it.live(1353+ "reads the same for an address no account has, and mails it nothing",1354+ () =>1355+ Effect.gen(function* () {1356+ const world = yield* signInWorld();1357+1358+ yield* signUp(world, "alice", alicePassword);1359+1360+ const before = (yield* world.mails).length;1361+1362+ const known = yield* startReset(world, emailOf("alice"));1363+1364+ const unknown = yield* startReset(world, emailOf("nobody"));1365+1366+ const mails = yield* world.mails;1367+1368+ expect([1369+ known.page.response.status,1370+ unknown.page.response.status,1371+ ]).toStrictEqual([200, 200]);1372+ expect(unknown.page.html).toContain(1373+ `If an account uses ${emailOf("nobody")}, we mailed it a code.`1374+ );1375+ expect(mails.slice(before).map(({ to }) => to)).toStrictEqual([1376+ emailOf("alice"),1377+ ]);1378+1379+ const page = yield* enterCode(1380+ world,1381+ unknown,1382+ ACCOUNT_PATHS.resetVerify,1383+ "123456",1384+ { password: "a brand new password" }1385+ );1386+1387+ expect(page.status).toBe(401);1388+ })1389+ );1390+1391+ it.live("keeps the old password when the code is wrong", () =>1392+ Effect.gen(function* () {1393+ const world = yield* signInWorld();1394+1395+ yield* signUp(world, "alice", alicePassword);1396+1397+ const started = yield* startReset(world, emailOf("alice"));1398+1399+ const code = yield* Effect.fromOption(1400+ yield* codeMailedTo(world, emailOf("alice"))1401+ ).pipe(Effect.orDie);1402+1403+ const page = yield* enterCode(1404+ world,1405+ started,1406+ ACCOUNT_PATHS.resetVerify,1407+ code === "000000" ? "000001" : "000000",1408+ { password: "a brand new password" }1409+ );1410+1411+ const old = yield* signIn(world, "alice", alicePassword);1412+1413+ expect(page.status).toBe(401);1414+ expect(Option.isSome(codeOf(old))).toBeTruthy();1415+ })1416+ );1417+});1418+1419+describe("a mailed code", () => {1420+ const email = Email.make("alice@mail.example");1421+1422+ it.effect("is six digits", () =>1423+ Effect.gen(function* () {1424+ const codes = yield* Effect.forEach(1425+ [1, 2, 3, 4, 5, 6, 7, 8],1426+ () => freshCode1427+ );1428+1429+ for (const code of codes) {1430+ expect(code).toMatch(/^\d{6}$/u);1431+ }1432+ })1433+ );1434+1435+ it.effect(1436+ "opens only for the purpose and address it was mailed for, in any case",1437+ () =>1438+ Effect.gen(function* () {1439+ const tag = yield* codeTag(cookieKey, "sign-up", email, "123456");1440+1441+ const opens = (1442+ purpose: CodePurpose,1443+ to: string,1444+ entered: string,1445+ key = cookieKey1446+ ) => codeMatches(key, purpose, Email.make(to), tag, entered);1447+1448+ expect([1449+ yield* opens("sign-up", "alice@mail.example", "123456"),1450+ yield* opens("sign-up", "ALICE@mail.example", "123 456"),1451+ yield* opens("reset", "alice@mail.example", "123456"),1452+ yield* opens("add-email", "alice@mail.example", "123456"),1453+ yield* opens("sign-up", "bob@mail.example", "123456"),1454+ yield* opens("sign-up", "alice@mail.example", "123457"),1455+ yield* opens("sign-up", "alice@mail.example", "12345"),1456+ yield* opens(1457+ "sign-up",1458+ "alice@mail.example",1459+ "123456",1460+ Redacted.make("not-the-cookie-key-0123456789abcdef")1461+ ),1462+ ]).toStrictEqual([1463+ true,1464+ true,1465+ false,1466+ false,1467+ false,1468+ false,1469+ false,1470+ false,1471+ ]);1472+ })1473+ );1474+1475+ it.effect("never opens a dead tag", () =>1476+ Effect.gen(function* () {1477+ const tag = yield* deadTag;1478+1479+ expect(1480+ yield* codeMatches(cookieKey, "reset", email, tag, "123456")1481+ ).toBeFalsy();1482+ })1483+ );1484+});modified:apps/platform/test/pages.test.ts+88 added-5 removed
4 unmodified lines5 import { UnknownProject } from "@repo/protocol/refusal";6 import { Effect, Layer, Option } from "effect";7 8 import {9- pickHandlePage,9+ ACCOUNT_PATHS,10+ addEmailPage,11+ codePage,12 problemPage,13+ profilePage,14+ resetPage,15 signInPage,16 signUpPage,17 } from "../src/auth/pages.ts";18 import type { Asker, PendingForm } from "../src/auth/pages.ts";55 unmodified lines74 )75 );76 77 const PAGES = {74- "Google's handle page": pickHandlePage(78+ "Google's profile page": profilePage(79 local,80 form,81 "/authorize?x=1",82+ { displayName: "Carol Example", handle: "carol" },83 "That handle is taken. Choose another, or sign in."84 ),85+ "adding an email": addEmailPage(86+ claude,87+ form,88+ "/authorize?x=1",89+ "alice@mail.example",90+ "Another account already uses that email. Add a different one."91+ ),92+ "entering a code": codePage(93+ claude,94+ form,95+ {96+ action: ACCOUNT_PATHS.signUpVerify,97+ intro: "We mailed a code to alice@mail.example.",98+ newPassword: false,99+ startOverHref: "/authorize?x=1",100+ },101+ "That code is wrong or has expired."102+ ),103+ "resetting a password": resetPage(104+ local,105+ form,106+ "/authorize?x=1",107+ "alice@mail.example"108+ ),109+ "setting a new password by code": codePage(local, form, {110+ action: ACCOUNT_PATHS.resetVerify,111+ intro: "If an account uses alice@mail.example, we mailed it a code.",112+ newPassword: true,113+ startOverHref: "/authorize?x=1",114+ }),115 "sign-in": signInPage(116 claude,117 form,118 { google: true },84- "The handle or password is wrong."119+ "The email, handle or password is wrong."120 ),121 "sign-up": signUpPage(122 local,123 form,124 "/authorize?x=1",125+ { displayName: "Alice", email: "alice@mail.example", handle: "alice" },126 "A password is 12 to 256 characters."127 ),128 "the problem page": problemPage(129 "This sign-in page expired or was not opened here. Start signing in again from your app."130 ),131 } as const;132 97-const FORMS = new Set(["Google's handle page", "sign-in", "sign-up"]);133+const FORMS = new Set(134+ Object.keys(PAGES).filter((name) => name !== "the problem page")135+);136 137 interface Rule {138 readonly selectors: readonly string[];139 readonly declarations: ReadonlyMap<string, string>;298 unmodified lines438 });439 440 it("draws an error in the refusal's colour, and the problem page's in ink", () => {441 expect(PAGES["sign-in"]).toMatch(404- /<p class="error" role="alert">The handle or password is wrong\.<\/p>/u442+ /<p class="error" role="alert">The email, handle or password is wrong\.<\/p>/u443 );444 expect(PAGES["the problem page"]).not.toContain('class="error"');445 expect(PAGES["the problem page"]).toMatch(/<a href="\/">/u);446 });447 });448+449+describe("a sign-in form shown again", () => {450+ it("escapes every value the person typed", () => {451+ const typed = `"><script>alert(1)</script>`;452+453+ const pages = [454+ signUpPage(local, form, "/authorize", {455+ displayName: typed,456+ email: typed,457+ handle: typed,458+ }),459+ profilePage(local, form, "/authorize", {460+ displayName: typed,461+ handle: typed,462+ }),463+ addEmailPage(local, form, "/authorize", typed),464+ resetPage(local, form, "/authorize", typed),465+ ];466+467+ for (const html of pages) {468+ expect(html).not.toContain("<script>");469+ expect(html).toContain(470+ `value=""><script>alert(1)</script>"`471+ );472+ }473+ });474+475+ it("never fills in a password", () => {476+ expect(477+ signUpPage(local, form, "/authorize", { email: "alice@mail.example" })478+ ).toMatch(/<input type="password" name="password" [^>]*required>/u);479+ });480+});481+482+describe("the sign-in page's ways out", () => {483+ it("links to resetting a password and to signing up, carrying the sealed request", () => {484+ const html = signInPage(claude, form, { google: false });485+486+ expect(html).toContain(487+ `href="${ACCOUNT_PATHS.reset}?request=sealed-request"`488+ );489+ expect(html).toContain('href="/signup?request=sealed-request"');490+ expect(html).toContain("Email or handle");491+ });492+});modified:apps/platform/test/worker-init.test.ts+30 added-2 removed
26 unmodified lines27 import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";28 import { AccountsMemory } from "../src/auth/accounts/memory.ts";29 import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";30 import { IdentitiesMemory } from "../src/auth/identities/memory.ts";31+import { MailerMemory } from "../src/auth/mailer/memory.ts";32 import { OAuthStore } from "../src/auth/oauth-store.ts";33 import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";34+import { ACCOUNT_PATHS } from "../src/auth/pages.ts";35 import { oauthProvider, signInSettings } from "../src/auth/provider.ts";36 import { decodeEnv, PlatformEnv, platformOf } from "../src/platform.ts";37 import { workerPorts } from "../src/ports.ts";38 import { serve } from "../src/surfaces.ts";259 unmodified lines298 const { dispose: disposePlatform, handler: platformFetch } = serve(299 platformOf(config)300 );301 302+ const mailer = yield* MailerMemory.make();303+304 const { dispose, handler } = oauthProvider(305 Layer.mergeAll(306 AccountsMemory.layer,307+ mailer.layer,308 Layer.succeed(OAuthStore, store),309 IdentitiesMemory.layer,310 Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch")),311 SignInAttemptsMemory.layer,40 unmodified lines352 );353 354 const form = yield* formIn(signUpPage, signIn.cookie);355 351- const code = yield* fetch(356+ const mailed = yield* fetch(357 post(358 "/signup",354- { csrf: form.csrf, handle, password, request: form.request },359+ {360+ csrf: form.csrf,361+ displayName: "Alice Example",362+ email: `${handle}@mail.example`,363+ handle,364+ password,365+ request: form.request,366+ },367 form.cookie368 )369+ ).pipe(Effect.flatMap(pageOf));370+371+ const confirm = yield* formIn(mailed, form.cookie);372+373+ const [mail] = yield* mailer.sent;374+375+ const code = yield* fetch(376+ post(377+ ACCOUNT_PATHS.signUpVerify,378+ {379+ code: mail?.subject.slice(0, 6) ?? "",380+ csrf: confirm.csrf,381+ request: confirm.request,382+ },383+ confirm.cookie384+ )385 ).pipe(386 Effect.flatMap((response) => Effect.fromOption(codeOf(response))),387 Effect.orDie388 );69 unmodified linesmodified:apps/platform/.env.schema+4 added-2 removed
17 unmodified lines18 # @optional @sensitive19 SESSION_TOKENS=20 21 # Sign-in: the key a sign-in in progress is sealed into its form22-# with (HMAC-SHA-256), at least 32 characters. Accounts are the platform's23-# own, so every stage signs people in and needs no third party.22+# with (HMAC-SHA-256), and each mailed code's HMAC under it, at least 3223+# characters. Accounts are the platform's own; the only outside service is24+# the `EMAIL` binding (wrangler.jsonc), whose sending domain is onboarded25+# for Email Sending on the account.26 # @required @sensitive @type=string(minLength=32)27 COOKIE_KEY=28 29 # Sign-in: the pepper every password is HMAC'd with before PBKDF2,24 unmodified linesmodified:apps/platform/worker-configuration.d.ts+5 added-1 removed
1 /* eslint-disable */2-// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: a47fb3ac3f72d983df90016b3fc3c8eb)2+// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 5f88662c53523b45be0f8663dff97280)3 interface __BaseEnv_Env {4 OAUTH_KV: KVNamespace;5 EVIDENCE: R2Bucket;6 RELEASES: R2Bucket;7 CODE_CACHE: R2Bucket;8 FRONT_PAGE: D1Database;9+ EMAIL: SendEmail;10 ARTIFACTS: Artifacts;11 ARTIFACTS_PRIVATE: Artifacts;12 CLAIM_LIMIT: RateLimit;13 PROPOSAL_LIMIT: RateLimit;25 unmodified lines39 EVIDENCE: R2Bucket;40 RELEASES: R2Bucket;41 CODE_CACHE: R2Bucket;42 FRONT_PAGE: D1Database;43+ EMAIL: SendEmail;44 ARTIFACTS: Artifacts;45 ARTIFACTS_PRIVATE: Artifacts;46 CLAIM_LIMIT: RateLimit;47 PROPOSAL_LIMIT: RateLimit;20 unmodified lines68 EVIDENCE: R2Bucket;69 RELEASES: R2Bucket;70 CODE_CACHE: R2Bucket;71 FRONT_PAGE: D1Database;72+ EMAIL: SendEmail;73 ARTIFACTS: Artifacts;74 ARTIFACTS_PRIVATE: Artifacts;75 CLAIM_LIMIT: RateLimit;76 PROPOSAL_LIMIT: RateLimit;20 unmodified lines97 EVIDENCE: R2Bucket;98 RELEASES: R2Bucket;99 CODE_CACHE: R2Bucket;100 FRONT_PAGE: D1Database;101+ EMAIL: SendEmail;102 ARTIFACTS: Artifacts;103 ARTIFACTS_PRIVATE: Artifacts;104 CLAIM_LIMIT: RateLimit;105 PROPOSAL_LIMIT: RateLimit;27 unmodified linesmodified:apps/platform/wrangler.jsonc+6 added
86 unmodified lines87 { "binding": "EVIDENCE", "bucket_name": "evidence-local" },88 { "binding": "RELEASES", "bucket_name": "releases-local" },89 { "binding": "CODE_CACHE", "bucket_name": "code-cache-local" },90 ],91+ // Sign-in's mail (Cloudflare Email Service). `wrangler dev` only logs92+ // each mail, code included, so no real mail leaves a local run.93+ "send_email": [{ "name": "EMAIL" }],94 "worker_loaders": [{ "binding": "LOADER" }],95 // Workers AI, for the drafter (no key: the account's own).96 "ai": { "binding": "AI" },97 "services": [{ "binding": "SANDBOX", "service": "sandbox" }],85 unmodified lines183 { "binding": "EVIDENCE", "bucket_name": "evidence-dev-oscabriel" },184 { "binding": "RELEASES", "bucket_name": "releases-dev-oscabriel" },185 { "binding": "CODE_CACHE", "bucket_name": "code-cache-dev-oscabriel" },186 ],187+ "send_email": [{ "name": "EMAIL" }],188 "worker_loaders": [{ "binding": "LOADER" }],189 "ai": { "binding": "AI" },190 "services": [191 { "binding": "SANDBOX", "service": "sandbox-dev-oscabriel" },79 unmodified lines271 { "binding": "EVIDENCE", "bucket_name": "evidence-demo" },272 { "binding": "RELEASES", "bucket_name": "releases-demo" },273 { "binding": "CODE_CACHE", "bucket_name": "code-cache-demo" },274 ],275+ "send_email": [{ "name": "EMAIL" }],276 "worker_loaders": [{ "binding": "LOADER" }],277 "ai": { "binding": "AI" },278 "services": [{ "binding": "SANDBOX", "service": "sandbox-demo" }],279 "ratelimits": [82 unmodified lines362 { "binding": "EVIDENCE", "bucket_name": "evidence-prod" },363 { "binding": "RELEASES", "bucket_name": "releases-prod" },364 { "binding": "CODE_CACHE", "bucket_name": "code-cache-prod" },365 ],366+ "send_email": [{ "name": "EMAIL" }],367 "worker_loaders": [{ "binding": "LOADER" }],368 "ai": { "binding": "AI" },369 "services": [{ "binding": "SANDBOX", "service": "sandbox-prod" }],370 "ratelimits": [35 unmodified linesmodified:AGENTS.md+2 added-2 removed
15 unmodified lines16 | 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; `apps/platform/test/platform.test.ts` (a bad env fails at start, decoded once in `apps/platform/src/platform.ts`); `apps/platform/test/bindings.test.ts` (the decoded bindings, vars and secrets equal each wrangler.jsonc block's, the `AI` binding, `DRAFT_LIMIT`, `DRAFT_MODEL`, `PUBLIC_WEB_URL` and the code store's `CODE_CACHE` among them, and each port's factory takes its binding as the generated Env types it, without a cast); `packages/project/test/code-history.test.ts` (a kept code-history value is decoded with Schema when read, and one that no longer decodes is computed again); `packages/project/test/code.test.ts` (a kept commit that no longer decodes is computed again); `apps/web/test/dev-fixtures.test.ts` (the dev world's fixture record is decoded through the protocol's schemas when the world is built, so every case reads only a record that decodes); `apps/web/test/server-params.test.ts` (a project route's server handler is handed the project's full name once, as Start's params parse it, never parsed again) |17 | 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` and `packages/protocol/test/render.test.ts` (every tag, the code reads' and drafting's `UnknownPath`, `UnknownRevision`, `UnknownProposal`, `ProposalClosed` and `DraftInProgress` included; a limit's refusal names its kind and its wait, and a ref outside `refs/heads/` reads as one the platform writes); `packages/agent-kit/test/full-llms.test.ts` (every tag in the union has a row in `/llms-full.txt`); `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal, `draftAsk`, `showProposal` and a code read's `UnknownPath` included); `apps/platform/test/workflows/draft.test.ts` (past the draft limit, `CapReached`); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit); `packages/protocol/test/exit-code.test.ts` (each tag's CLI exit code is pinned, 75 exactly when it is retryable); `packages/config/test/legacy-projects.test.ts` (the same alias rule for a project's address: the forty projects made before owners keep their keys as aliases of their full names, the two examples and the import plan's, each key and each name once) |18 | 4 | **One schema, many surfaces.** Change `packages/protocol`; every surface derives from it. Projections live only in `apps/*/src/surfaces.ts`. The CLI's command list is `commandDocs` in `@repo/agent-kit`, which the platform's skill, the CLI's MCP prompt and the web's `llms.txt` all read. | `apps/cli/test/commands-doc.test.ts` (the command list against the real CLI's commands, flags and positionals, `policy`, `ask draft` and `proposal` included); `packages/protocol/test/mcp.test.ts` (every MCP tool's schemas, with no JSON Schema leak, the policy and drafting contracts included; the five capped code reads are tools, `showCommit` and `listPaths` are not); `apps/web/test/agents.test.tsx` (every snippet, command, endpoint, limit and refusal on the For agents page is `@repo/agent-kit`'s or the union's); `packages/agent-kit/test/docs.test.ts` and `apps/web/test/docs.test.tsx` (the `/docs` pages name only the CLI's commands with flags each takes and link only to pages that exist, the reference lists every command, refusal, event, MCP tool and imported project from its source, and the web draws each page and its Markdown from that one text); `apps/web/test/llms.test.ts` (`/` and `/<project>` asked for Markdown answer with the `llms.txt` texts, and their HTML names that Markdown as an alternate); `packages/agent-kit/test/full-llms.test.ts` (one `ProjectEvent` line per tag); `apps/platform/test/home.test.ts` (the platform's `/` in Markdown is the web's `llms.txt`, one text from `@repo/agent-kit`); `packages/protocol/test/project-name.test.ts` (`ProjectName` is the one parser of a project's name for every surface: lowercase, a legacy key read as its full name, encoded only in the full form, and a key that reads back to its name); per-package `allowedUnstableApis` with `unstableApiUsage` at error |19 | 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` (`scripts/brand.ts`, tested by `packages/brand/test/leaks.test.ts`) |20-| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `packages/drafting/test/memory.test.ts` (the `Drafter` port's `/memory` adapter, `packages/drafting/src/drafter/memory.ts`) and `packages/drafting/test/binding.test.ts` (its Workers AI adapter over the `AI` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's). No fence: import direction and module-level state |21-| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing at `/` draws only the public project list, each project with the posture its listing gives); `apps/web/test/ledger.test.tsx` (the ledger page adds no path, check name or file name) and `apps/web/test/env.test.tsx` (the env page shows no value and no control to set or read one); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |20+| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `packages/drafting/test/memory.test.ts` (the `Drafter` port's `/memory` adapter, `packages/drafting/src/drafter/memory.ts`) and `packages/drafting/test/binding.test.ts` (its Workers AI adapter over the `AI` binding); `apps/platform/test/mailer.test.ts` (sign-in's `Mailer` port, its `/memory` adapter and its Email Service adapter over the `EMAIL` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's). No fence: import direction and module-level state |21+| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing at `/` draws only the public project list, each project with the posture its listing gives); `apps/web/test/ledger.test.tsx` (the ledger page adds no path, check name or file name) and `apps/web/test/env.test.tsx` (the env page shows no value and no control to set or read one); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |22 | 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`; `apps/platform/test/workflows/draft.test.ts` (a replayed draft round asks the model nothing more, and each round is its own instance); `packages/project/test/code.test.ts` (code reads cached by object id, only once finished, while `main` resolves every time, and a commit's diff kept by its SHA without its landing); `packages/project/test/drafting.model.test.ts` (a settle of a stale round changes nothing); `packages/project/test/import.test.ts` (a retried import adopts the repo it made, and a retried import keeps its source); `packages/project/test/code-history.test.ts` (a why and a path's history are kept by commit, path hash and algorithm version, and the store, a step from a kept ancestor and a whole walk agree); `packages/config/test/smoke-loop.test.ts` (smoke's throwaway project is in the ledger before init makes it, and a taken name stops before anything is made); `apps/web/test/events.test.ts` (the web's fold of a project's events gives the same map when an event is heard twice or out of order, and a replay that already holds a landing stamps nothing); `packages/project/test/standing-posture.test.ts` (a kept posture is read again only for the project whose event the projection applied, or once its instant has come). No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |23 | 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Off limits: `effect/unstable/*`, v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `no-restricted-imports` |24 | 10 | **Escapes need a reason.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries its reason after `--`, and is added only where no idiomatic code does the job. | `check` fails on an unused directive. No fence: the reason |25 | 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`), and refuses every deploy while `infra/.recording` is there (`packages/config/test/recording.test.ts`) |114 unmodified linesmodified:README.md+1 added-1 removed
44 unmodified lines45 The web's `/docs` holds the guides and the full reference; `/llms.txt` and `myr mcp` serve the same to agents.46 47 ## Deploy your own48 49-You need a Cloudflare account on Workers Paid, with Artifacts, and Docker with buildx. Add a `dev-<you>` stage to `infra/stages.ts` and each app's `wrangler.jsonc`, set the credentials `infra/.env.schema` names, then:49+You need a Cloudflare account on Workers Paid, with Artifacts, and Docker with buildx. Sign-in mails codes from `no-reply@myr.technology` through Cloudflare Email Service, so onboard the brand's domain for Email Sending on the account (Compute › Email Service). Add a `dev-<you>` stage to `infra/stages.ts` and each app's `wrangler.jsonc`, set the credentials `infra/.env.schema` names, then:50 51 ```sh52 bun run bootstrap -- --stage dev-<you> # makes the stage's resources; deletes nothing53 bun run deploy -- --stage dev-<you> # runs verify, deploys the three Workers, runs smoke28 unmodified lines