Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent 78a5062 · Browse files · 28 files+2831 added−375 removed
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

28 files+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.8ALTER TABLE accounts ADD COLUMN email TEXT;9ALTER TABLE accounts ADD COLUMN email_key TEXT;10ALTER TABLE accounts ADD COLUMN display_name TEXT;11CREATE UNIQUE INDEX accounts_by_email ON accounts (email_key);
modified:apps/platform/src/adapters/accounts-d1.ts+96 added-24 removed
modified:apps/platform/src/auth/accounts/memory.ts+84 added-15 removed
added:apps/platform/src/auth/mailer/binding.ts+29 added
added:apps/platform/src/auth/mailer/memory.ts+24 added
1import { Effect, Layer, Ref } from "effect";23import { MailFailed, Mailer } from "../mailer.ts";4import type { Mail } from "../mailer.ts";56// Keeps every mail sent, newest last; `failing` makes each send fail.7export const MailerMemory = {8 make: (options: { readonly failing?: boolean } = {}) =>9 Effect.gen(function* () {10 const sent = yield* Ref.make<readonly Mail[]>([]);1112 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 );2122 return { layer, sent: Ref.get(sent) };23 }),24};
modified:apps/platform/src/auth/accounts.ts+47 added-4 removed
1import type { Handle } from "@repo/protocol/ids";2import { Context, Data } from "effect";2import { Context, Data, Schema } from "effect";3import type { Effect, Option } from "effect";45import type { PasswordHash } from "./password.ts";67// Enough to catch a typo; the mailed code is what proves the address.8export const Email = Schema.String.check(9 Schema.isMaxLength(254),10 Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/u)11).pipe(Schema.brand("Email"));1213export type Email = typeof Email.Type;1415// The rule two spellings of one address are compared by.16export const emailKey = (email: Email) => email.toLowerCase();1718const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });1920export const DisplayName = Schema.String.check(21 Schema.makeFilter((name) => {22 const { length } = [...graphemes.segment(name)];2324 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"));3233export type DisplayName = typeof DisplayName.Type;3435// Sign-up always sets `email` and `displayName`; only accounts made before36// either existed lack them.37export interface Account {38 readonly displayName?: DisplayName;39 readonly email?: Email;40 readonly handle: Handle;41 readonly hash: PasswordHash;42}4344export class HandleTaken extends Data.TaggedError("HandleTaken")<{45 readonly handle: Handle;46}> {}4748export class EmailTaken extends Data.TaggedError("EmailTaken")<{49 readonly email: Email;50}> {}5152// The rule `sameHandle` compares by, so a racing second sign-up fails on the key.53export const handleKey = (handle: Handle) => handle.toLowerCase();5455export 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 lines
added: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.5import { Effect, Option, Redacted, Schema } from "effect";67import { emailKey } from "./accounts.ts";8import type { Email } from "./accounts.ts";910export const CODE_DIGITS = 6;1112const SPACE = 10 ** CODE_DIGITS;1314// The largest multiple of SPACE a Uint32 holds, so every code is as likely.15const FAIR = Math.floor(2 ** 32 / SPACE) * SPACE;1617export const freshCode = Effect.sync(() => {18 const draw = new Uint32Array(1);1920 do {21 crypto.getRandomValues(draw);22 } while ((draw[0] ?? FAIR) >= FAIR);2324 return ((draw[0] ?? 0) % SPACE).toString().padStart(CODE_DIGITS, "0");25});2627export type CodePurpose = "sign-up" | "add-email" | "reset";2829const Tag = Schema.Uint8ArrayFromBase64Url;3031const encodeTag = Schema.encodeEffect(Tag);3233const decodeTag = Schema.decodeEffect(Tag);3435const utf8 = (text: string) => new TextEncoder().encode(text);3637const 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 );4748const bound = (purpose: CodePurpose, email: Email, code: string) =>49 utf8(`code.${purpose}.${emailKey(email)}.${code}`);5051export 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);5960 const signature = yield* Effect.promise(() =>61 crypto.subtle.sign("HMAC", hmac, bound(purpose, email, code))62 );6364 return yield* encodeTag(new Uint8Array(signature)).pipe(Effect.orDie);65 });6667// A tag no code opens, for a form that must look like one that mailed a code.68export const deadTag = Effect.sync(() =>69 crypto.getRandomValues(new Uint8Array(32))70).pipe(Effect.flatMap(encodeTag), Effect.orDie);7172// People paste codes with spaces or dashes in them.73const typed = (entered: string) => entered.replaceAll(/[\s-]/gu, "");7475export 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);8485 if (!new RegExp(`^\\d{${CODE_DIGITS}}$`, "u").test(code)) {86 return false;87 }8889 const expected = yield* decodeTag(tag).pipe(Effect.option);9091 if (Option.isNone(expected)) {92 return false;93 }9495 const hmac = yield* hmacKey(key);9697 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.4import { Fetch } from "@repo/artifacts/fetch";5import { Handle } from "@repo/protocol/ids";6import {7 Array,
9 unmodified lines
17 Schema,18} from "effect";19import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";2019import { Accounts } from "./accounts.ts";21import { Accounts, Email } from "./accounts.ts";22import type { Account } from "./accounts.ts";23import { SignInAttempts } from "./attempts.ts";24import { Identities } from "./identities.ts";25import { Mailer } from "./mailer.ts";26import { OAuthStore } from "./oauth-store.ts";23import { GOOGLE_PATHS, pickHandlePage } from "./pages.ts";27import { GOOGLE_PATHS, profilePage } from "./pages.ts";28import type { ProfileValues } from "./pages.ts";29import { hashPassword } from "./password.ts";30import {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 lines
97 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();104105 return url.toString();
28 unmodified lines
134135const 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});146147export 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}153154const decodeEmail = Schema.decodeUnknownOption(Email);155156const 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});164165const segment = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>166 Schema.decodeEffect(167 Schema.StringFromBase64Url.pipe(168 Schema.decodeTo(Schema.fromJsonString(schema))
132 unmodified lines
301 (audience.length === 1 || claims.azp === clientId)302 );303};304277const verifiedSubject = (305const verifiedPerson = (306 token: string,307 expected: { readonly clientId: string; readonly nonce: string }308) =>309 Effect.gen(function* () {
40 unmodified lines
350 issuedTo(said, expected.clientId) &&351 said.exp * 1000 > now &&352 said.nonce === expected.nonce;353326 return holds ? said.sub : yield* unconfirmed;354 return holds ? personOf(said) : yield* unconfirmed;355 });356357// Google's other tokens in the answer are never read, and nothing of it is kept.330export const googleSubject = (input: {358export 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;368369 const fetch = yield* Fetch;
19 unmodified lines
389 method: "POST",390 })391 );392365 return yield* verifiedSubject(id_token, input);393 return yield* verifiedPerson(id_token, input);394 });395396interface Client {397 readonly id: string;
7 unmodified lines
405406const 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;412413// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.414const GOOGLE_COOKIE = "__Host-google-sign-in";
25 unmodified lines
440const legs = sealing("google-leg", GoogleLeg);441442const PendingHandle = Schema.Struct({443 csrf: Schema.String,444 email: Email,445 name: Schema.optionalKey(Schema.String),446 request: AuthRequest,447 subject: GoogleSubject,448});449450type PendingHandle = typeof PendingHandle.Type;451452const pendingHandles = sealing("google-handle", PendingHandle);453454const encodeBytes = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);455
78 unmodified lines
534 });535536const 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 );541542const 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;550551 const csrf = yield* freshCsrf;552519 const sealed = yield* pendingHandles.seal(cookieKey, {520 csrf,521 request,522 subject,523 });553 const sealed = yield* pendingHandles.seal(cookieKey, { ...pending, csrf });554525 const asker = yield* askerOf(request);555 const asker = yield* askerOf(pending.request);556557 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 line
572 Effect.orDie573 );574 });575545const 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.579const completedWithEmail = (580 account: Account,581 person: GooglePerson,582 request: AuthRequest583) =>584 Effect.gen(function* () {585 const accounts = yield* Accounts;586587 if (account.email !== undefined) {588 return yield* completed(account.handle, request);589 }590591 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 });599600 return yield* set601 ? completed(account.handle, request)602 : addEmailPageFor(account.handle, request, 200);603 });604605const linkedTo = (person: GooglePerson, handle: Handle, request: AuthRequest) =>606 Effect.gen(function* () {607 const identities = yield* Identities;608609 const accounts = yield* Accounts;610551 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 );617553 if (Option.isNone(linked)) {554 return yield* pickHandle(subject, request, 200);618 if (!linked) {619 return yield* signInPageFor(request, 409, GoogleSays.linkedElsewhere);620 }621557 const account = yield* accounts.find(linked.value);622 const account = yield* accounts.find(handle);623624 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 });629565const linkedTo = (566 subject: GoogleSubject,567 handle: Handle,568 request: AuthRequest569) =>630const signedInAs = (person: GooglePerson, request: AuthRequest) =>631 Effect.gen(function* () {632 const identities = yield* Identities;633573 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;635578 return linked579 ? yield* completed(handle, request)580 : yield* signInPageFor(request, 409, GoogleSays.linkedElsewhere);636 const linked = yield* identities.handleOf("google", person.subject);637638 if (Option.isSome(linked)) {639 const account = yield* accounts.find(linked.value);640641 return yield* Option.match(account, {642 onNone: () => signInPageFor(request, 401, unconfirmed.reason),643 onSome: (found) => completedWithEmail(found, person, request),644 });645 }646647 if (Option.isNone(person.email)) {648 return yield* signInPageFor(request, 401, GoogleSays.noEmail);649 }650651 // Both Google and the account proved the address, so they are one person.652 const holder = yield* accounts.findByEmail(person.email.value);653654 if (Option.isSome(holder)) {655 return yield* linkedTo(person, holder.value.handle, request);656 }657658 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 });675676const CallbackQuery = Schema.Struct({677 code: Schema.optionalKey(Schema.String),
24 unmodified lines
702 {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 lines
729730 return yield* legDone(answered);731 });732640const PostedHandle = Schema.Struct({733const PostedProfile = Schema.Struct({734 csrf: Schema.String,735 displayName: Schema.String,736 handle: Schema.String,737 request: Schema.String,738});739646// 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.742const handleChosen = (request: HttpServerRequest.HttpServerRequest) =>743 Effect.gen(function* () {744 const { cookieKey, pepper } = yield* SignInKeys;745
5 unmodified lines
751752 const { handles: held } = yield* HeldHandles;753754 const form = yield* HttpServerRequest.schemaBodyUrlParams(660 PostedHandle755 PostedProfile756 ).pipe(Effect.mapError(() => startAgain));757758 const pending = yield* pendingHandles.open(cookieKey, form.request);759
3 unmodified lines
763 ) {764 return yield* startAgain;765 }766672 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 };772773 const again = (status: number, message: string) =>774 pickHandle(775 pending,776 { displayName: form.displayName, handle: form.handle },777 status,778 message779 );780781 if (!(yield* attempts.admit(`sign-up:${addressOf(request)}`))) {782 return yield* again(429, Says.tooManySignUps);783 }784785 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 }788685 const checked = chosenHandle(form.handle, held);789 const checked = Result.all({790 displayName: chosenDisplayName(form.displayName),791 handle: chosenHandle(form.handle, held),792 });793794 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 }797798 const hash = yield* hashPassword(pepper, Redacted.make(yield* freshSecret));799698 const created = yield* accounts.create(checked.success, hash).pipe(699 Effect.as(true),700 Effect.catchTag("HandleTaken", () => Effect.succeed(false))701 );702703 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 }711712 return yield* linkedTo(pending.subject, checked.success, pending.request);817 });818819export type GoogleServices = Fetch | GoogleClient | Identities | SignInServices;820
9 unmodified lines
830 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 lines
added: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.3import { Context, Data } from "effect";4import type { Effect } from "effect";56import type { Email } from "./accounts.ts";78export interface Mail {9 readonly subject: string;10 readonly text: string;11 readonly to: Email;12}1314export class MailFailed extends Data.TaggedError("MailFailed") {}1516export 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 lines
16export interface Offers {17 readonly google: boolean;18}1920// Under `/oauth/`, which the platform already keeps for sign-in.21export 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;2829export const GOOGLE_PATHS = {30 callback: "/oauth/google/callback",31 handle: "/oauth/google/handle",32 link: "/oauth/google/link",
103 unmodified lines
136 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: "" };143144const valueOf = (value?: string) =>145 value === undefined ? "" : ` value="${escapeHtml(value)}"`;146147const withRequest = (path: string, form: PendingForm) =>148 `${path}?request=${encodeURIComponent(form.request)}`;149150export const signInPage = (151 asker: Asker,152 form: PendingForm,153 offers: Offers,
8 unmodified lines
162${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};177178export interface ProfileValues {179 readonly displayName?: string;180 readonly handle?: string;181}182183const 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>`;185186const DISPLAY_NAME_FIELD = (value?: string) =>187 `<label>Display name <input name="displayName" autocomplete="name" maxlength="64" required${valueOf(value)}></label>`;188162export const pickHandlePage = (189export 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 );210211export interface SignUpValues extends ProfileValues {212 readonly email?: string;213}214215export const signUpPage = (216 asker: Asker,217 form: PendingForm,218 signInHref: string,219 values: SignUpValues,220 message?: string221) =>222 page(223 "Sign up",
1 unmodified line
225${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 );238239export 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}247248export 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 );268269export 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 );289290export 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 );310311export const problemPage = (message: string) =>312 page(313 "Sign-in problem",314 `<h1>Signing in did not work</h1>
3 unmodified lines
modified:apps/platform/src/auth/provider.ts+2 added
10 unmodified lines
11import { buildHandler } from "../router-build.ts";12import { SignInAttemptsBinding } from "./attempts/binding.ts";13import { GOOGLE_ACCOUNTS, GoogleClient, googleRoutes } from "./google.ts";14import type { GoogleServices } from "./google.ts";15import { MailerBinding } from "./mailer/binding.ts";16import { OAuthStore } from "./oauth-store.ts";17import { GOOGLE_PATHS } from "./pages.ts";18import {19 Authorization,
129 unmodified lines
149 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 lines
19 Schema,20} from "effect";21import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";2223import { Accounts, handleKey } from "./accounts.ts";23import {24 Accounts,25 DisplayName,26 Email,27 emailKey,28 handleKey,29} from "./accounts.ts";30import type { Account } from "./accounts.ts";31import { SignInAttempts } from "./attempts.ts";32import { CLI_CLIENT_PATH, cliClientMetadata } from "./cli-client.ts";33import { codeMatches, codeTag, deadTag, freshCode } from "./codes.ts";34import type { CodePurpose } from "./codes.ts";35import { Mailer } from "./mailer.ts";36import { OAuthStore } from "./oauth-store.ts";27import { problemPage, signInPage, signUpPage } from "./pages.ts";28import type { Asker, PendingForm } from "./pages.ts";37import {38 ACCOUNT_PATHS,39 addEmailPage,40 codePage,41 problemPage,42 resetPage,43 signInPage,44 signUpPage,45} from "./pages.ts";46import type { Asker, CodeForm, PendingForm, SignUpValues } from "./pages.ts";47import {48 hashPassword,49 PasswordHash,50 PasswordPolicy,51 verifyPassword,52} from "./password.ts";53import {54 AuthRequest,55 openState,56 sealing,57 sealState,58 SIGN_IN_LIFETIME,59 SignInFailed,60 startAgain,61} from "./state.ts";42import type { AuthRequest, PendingSignIn } from "./state.ts";62import type { PendingSignIn } from "./state.ts";6364export class SignInKeys extends Context.Service<65 SignInKeys,66 {
34 unmodified lines
101export const SIGN_IN_PATHS = [102 "/authorize",103 "/signup",104 CLI_CLIENT_PATH,105 ...Object.values(ACCOUNT_PATHS),106] as const;107108// 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.109const RESERVED_HANDLES: ReadonlySet<string> = new Set([
15 unmodified lines
125126const PasswordLength = { max: 256, min: 12 } as const;127128export 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;156157// Verified against when no account has the handle, so timing names nobody.158const STAND_IN_HASH = PasswordHash.make(
165 unmodified lines
324export const freshCsrf = Effect.sync(() =>325 crypto.getRandomValues(new Uint8Array(32))326).pipe(Effect.flatMap(encodeToken), Effect.orDie);327292const PostedForm = Schema.Struct({293 csrf: Schema.String,294 handle: Schema.String,295 password: Schema.String,296 request: Schema.String,297});328const decodeEmail = Schema.decodeUnknownOption(Email);329299type PostedForm = typeof PostedForm.Type;330const decodeDisplayName = Schema.decodeUnknownOption(DisplayName);331301const postedSignIn = (request: HttpServerRequest.HttpServerRequest) =>302 Effect.gen(function* () {303 const { cookieKey } = yield* SignInKeys;304305 const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedForm).pipe(306 Effect.mapError(() => startAgain)307 );308309 const pending = yield* openState(cookieKey, form.request);310311 const cookie = request.cookies[CSRF_COOKIE];312313 if (pending.csrf !== form.csrf || cookie !== form.csrf) {314 return yield* startAgain;315 }316317 return { form, pending };318 });319332export const addressOf = (request: HttpServerRequest.HttpServerRequest) =>333 request.headers["cf-connecting-ip"] ?? "unknown";334335const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });
3 unmodified lines
339const passwordFits = (password: string) =>340 lengthOf(password) >= PasswordLength.min &&341 lengthOf(password) <= PasswordLength.max;342343const 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 );352353// A form's own CSRF token, the one sealed into it and the cookie's agree, or the form was not opened here.354const sameCsrf = (355 request: HttpServerRequest.HttpServerRequest,356 posted: string,357 sealed: string358) =>359 sealed === posted && request.cookies[CSRF_COOKIE] === posted360 ? Effect.void361 : Effect.fail(startAgain);362363// 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.366export const completed = (handle: Handle, request: AuthRequest) =>367 Effect.gen(function* () {368 const api = yield* oauthApi;369
50 unmodified lines
420 const { cookieKey } = yield* SignInKeys;421422 const csrf = yield* freshCsrf;423390 const pending: PendingSignIn = { csrf, request };424 const sealed = yield* sealState(cookieKey, { csrf, request });425392 const sealed = yield* sealState(cookieKey, pending);393426 const page = yield* offeredSignIn(427 request,428 { csrf, request: sealed },429 status,430 message431 );432401 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 });435436const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>437 Effect.gen(function* () {
5 unmodified lines
443444 return yield* signInPageFor(parsed, 200);445 });446421const signInAgain = (422 pending: PendingSignIn,423 form: PendingForm,447// Mailing448449const 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};457458// SIGN_IN_LIMIT's few mails a minute to one address, of any kind, so the forms are no way to flood an inbox.459const mailAdmitted = (email: Email) =>460 Effect.flatMap(SignInAttempts, (attempts) =>461 attempts.admit(`mail:${emailKey(email)}`)462 );463464const mailCode = (purpose: CodePurpose, email: Email) =>465 Effect.gen(function* () {466 const { cookieKey } = yield* SignInKeys;467468 const mailer = yield* Mailer;469470 const code = yield* freshCode;471472 yield* mailer.send({473 subject: `${code} is your ${Brand.name} code`,474 text: MAIL_TEXT[purpose](code),475 to: email,476 });477478 return yield* codeTag(cookieKey, purpose, email, code);479 });480481// Sent in place of a code when the address already has an account, so the page reads the same either way.482const mailAlreadyHeld = (email: Email) =>483 Effect.gen(function* () {484 const mailer = yield* Mailer;485486 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 });491492 return yield* deadTag;493 });494495const codeTried = (email: Email) =>496 Effect.flatMap(SignInAttempts, (attempts) =>497 attempts.admit(`code:${emailKey(email)}`)498 );499500interface CodeStep {501 readonly csrf: string;502 readonly request: AuthRequest;503 readonly sealed: string;504}505506const 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 );519520const codeSentTo = (email: Email) => `We mailed a code to ${email}.`;521522// Signing in523524const PostedSignIn = Schema.Struct({525 csrf: Schema.String,526 login: Schema.String,527 password: Schema.String,528 request: Schema.String,529});530531// An `@` makes it an email; anything else is read as a handle.532const accountNamed = (login: string) =>533 Effect.gen(function* () {534 const accounts = yield* Accounts;535536 const named = login.trim();537538 if (named.includes("@")) {539 return yield* Option.match(decodeEmail(named), {540 onNone: () => Effect.succeedNone,541 onSome: accounts.findByEmail,542 });543 }544545 return yield* Option.match(decodeHandle(named), {546 onNone: () => Effect.succeedNone,547 onSome: accounts.find,548 });549 });550428// A wrong handle and a wrong password read the same.551// A wrong login and a wrong password read the same.552export 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;561562 const accounts = yield* Accounts;563564 const attempts = yield* SignInAttempts;565443 const { form, pending } = yield* postedSignIn(request);566 const form = yield* HttpServerRequest.schemaBodyUrlParams(567 PostedSignIn568 ).pipe(Effect.mapError(() => startAgain));569570 const pending = yield* openState(cookieKey, form.request);571572 yield* sameCsrf(request, form.csrf, pending.csrf);573574 const shown: PendingForm = { csrf: form.csrf, request: form.request };575447 const handle = decodeHandle(form.handle);576 const again = (status: number, message: string) =>577 offeredSignIn(pending.request, shown, status, message);578579 const fits = passwordFits(form.password);580581 const account = fits ? yield* accountNamed(form.login) : Option.none();582583 // 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 ]);594595 if (!admitted.every(Boolean)) {458 return yield* signInAgain(pending, shown, 429, Says.tooManySignIns);596 return yield* again(429, Says.tooManySignIns);597 }598599 const password = Redacted.make(form.password);600463 const account = passwordFits(form.password)464 ? yield* Option.match(handle, {465 onNone: () => Effect.succeedNone,466 onSome: accounts.find,467 })468 : Option.none();469601 const { needsRehash, ok } = yield* verifyPassword(602 pepper,603 password,604 Option.match(account, {
2 unmodified lines
607 })608 );609610 if (Option.isNone(account) || !ok) {480 return yield* signInAgain(pending, shown, 401, Says.wrong);611 return yield* again(401, Says.wrong);612 }613614 if (needsRehash) {615 yield* accounts.setPasswordHash(
1 unmodified line
617 yield* hashPassword(pepper, password)618 );619 }620490 return yield* signedIn(account.value.handle, pending);621 return yield* signedIn(account.value, pending);622 });623624// Adding an email: an account made before sign-up asked for one625626const NeedsEmail = Schema.Struct({627 csrf: Schema.String,628 handle: Handle,629 request: AuthRequest,630});631632const needingEmail = sealing("needs-email", NeedsEmail);633634const PendingEmail = Schema.Struct({635 csrf: Schema.String,636 email: Email,637 handle: Handle,638 request: AuthRequest,639 tag: Schema.String,640});641642const pendingEmails = sealing("email-code", PendingEmail);643644// The person proved their password, or Google proved who they are: only an email stands between them and the grant.645export 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;654655 const csrf = yield* freshCsrf;656657 const sealed = yield* needingEmail.seal(cookieKey, {658 csrf,659 handle,660 request,661 });662663 const asker = yield* askerOf(request);664665 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 });679680// A signed-in account with no email adds one before its grant.681export const signedInWithEmail = (account: Account, request: AuthRequest) =>682 account.email === undefined683 ? addEmailPageFor(account.handle, request, 200)684 : completed(account.handle, request);685686const signIn = (request: HttpServerRequest.HttpServerRequest) =>494 byPassword(request, (handle, pending) => completed(handle, pending.request));687 byPassword(request, (account, pending) =>688 signedInWithEmail(account, pending.request)689 );690691const addEmailCode = (request: AuthRequest, email: Email): CodeForm => ({692 action: ACCOUNT_PATHS.addEmailVerify,693 intro: codeSentTo(email),694 newPassword: false,695 startOverHref: authorizeHref(request),696});697698const PostedEmail = Schema.Struct({699 csrf: Schema.String,700 email: Schema.String,701 request: Schema.String,702});703704const addEmail = (request: HttpServerRequest.HttpServerRequest) =>705 Effect.gen(function* () {706 const { cookieKey } = yield* SignInKeys;707708 const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedEmail).pipe(709 Effect.mapError(() => startAgain)710 );711712 const pending = yield* needingEmail.open(cookieKey, form.request);713714 yield* sameCsrf(request, form.csrf, pending.csrf);715716 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 );730731 const email = decodeEmail(form.email.trim());732733 if (Option.isNone(email)) {734 return yield* again(400, Says.emailSpelling);735 }736737 if (!(yield* mailAdmitted(email.value))) {738 return yield* again(429, Says.tooManyMails);739 }740741 // 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);744745 if (Option.isNone(tag)) {746 return yield* again(503, Says.mailFailed);747 }748749 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 });756757 return yield* codePageFor(758 { csrf: form.csrf, request: pending.request, sealed },759 addEmailCode(pending.request, email.value),760 200761 );762 });763764const PostedCode = Schema.Struct({765 code: Schema.String,766 csrf: Schema.String,767 request: Schema.String,768});769770const addEmailVerified = (request: HttpServerRequest.HttpServerRequest) =>771 Effect.gen(function* () {772 const { cookieKey } = yield* SignInKeys;773774 const accounts = yield* Accounts;775776 const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedCode).pipe(777 Effect.mapError(() => startAgain)778 );779780 const pending = yield* pendingEmails.open(cookieKey, form.request);781782 yield* sameCsrf(request, form.csrf, pending.csrf);783784 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 );795796 if (!(yield* codeTried(pending.email))) {797 return yield* again(429, Says.tooManyCodes);798 }799800 const right = yield* codeMatches(801 cookieKey,802 "add-email",803 pending.email,804 pending.tag,805 form.code806 );807808 if (!right) {809 return yield* again(401, Says.codeWrong);810 }811812 const set = yield* accounts.setEmail(pending.handle, pending.email).pipe(813 Effect.as(true),814 Effect.catchTag("EmailTaken", () => Effect.succeed(false))815 );816817 return yield* set818 ? completed(pending.handle, pending.request)819 : addEmailPageFor(pending.handle, pending.request, 409, Says.emailHeld);820 });821822// Signing up: the account is written only once the mailed code comes back823824const 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});834835const pendingSignUps = sealing("sign-up-code", PendingSignUp);836837const showSignUp = Effect.gen(function* () {838 const { cookieKey } = yield* SignInKeys;839840 const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(
7 unmodified lines
848 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 lines
865export 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 lines
880 return Result.succeed(chosen);881 },882 });883884export 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 });891892const 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});900901type PostedSignUp = typeof PostedSignUp.Type;902903interface SignUpChoice {904 readonly displayName: DisplayName;905 readonly email: Email;906 readonly handle: Handle;907}908542const signUpHandle = (543 form: PostedForm,909const 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 );928929const 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 );943944const signUpCode = (request: AuthRequest, email: Email): CodeForm => ({945 action: ACCOUNT_PATHS.signUpVerify,946 intro: codeSentTo(email),947 newPassword: false,948 startOverHref: authorizeHref(request),949});950951const signUp = (request: HttpServerRequest.HttpServerRequest) =>952 Effect.gen(function* () {554 const { pepper } = yield* SignInKeys;953 const { cookieKey, pepper } = yield* SignInKeys;954955 const accounts = yield* Accounts;956957 const attempts = yield* SignInAttempts;958959 const { handles: held } = yield* HeldHandles;960562 const { form, pending } = yield* postedSignIn(request);961 const form = yield* HttpServerRequest.schemaBodyUrlParams(962 PostedSignUp963 ).pipe(Effect.mapError(() => startAgain));964965 const pending = yield* openState(cookieKey, form.request);966967 yield* sameCsrf(request, form.csrf, pending.csrf);968969 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 );981982 if (!(yield* attempts.admit(`sign-up:${addressOf(request)}`))) {983 return yield* again(429, Says.tooManySignUps);984 }985584 const checked = signUpHandle(form, held);986 const checked = signUpChoice(form, held);987988 if (Result.isFailure(checked)) {989 return yield* again(checked.failure.status, checked.failure.message);990 }991590 const hash = yield* hashPassword(pepper, Redacted.make(form.password));992 const { displayName, email, handle } = checked.success;993592 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 }997998 if (!(yield* mailAdmitted(email))) {999 return yield* again(429, Says.tooManyMails);1000 }10011002 const holder = yield* accounts.findByEmail(email);10031004 const tag = yield* (1005 Option.isSome(holder)1006 ? mailAlreadyHeld(email)1007 : mailCode("sign-up", email)1008 ).pipe(Effect.option);10091010 if (Option.isNone(tag)) {1011 return yield* again(503, Says.mailFailed);1012 }10131014 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 });10231024 return yield* codePageFor(1025 { csrf: form.csrf, request: pending.request, sealed },1026 signUpCode(pending.request, email),1027 2001028 );1029 });1030597 if (!created) {598 return yield* again(409, Says.handleTaken);1031const signUpVerified = (request: HttpServerRequest.HttpServerRequest) =>1032 Effect.gen(function* () {1033 const { cookieKey } = yield* SignInKeys;10341035 const accounts = yield* Accounts;10361037 const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedCode).pipe(1038 Effect.mapError(() => startAgain)1039 );10401041 const pending = yield* pendingSignUps.open(cookieKey, form.request);10421043 yield* sameCsrf(request, form.csrf, pending.csrf);10441045 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 );10521053 if (!(yield* codeTried(pending.email))) {1054 return yield* again(429, Says.tooManyCodes);1055 }1056601 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 );10641065 if (!right) {1066 return yield* again(401, Says.codeWrong);1067 }10681069 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;10841085 const sealed = yield* sealState(cookieKey, {1086 csrf,1087 request: pending.request,1088 });10891090 const page = yield* signUpPageFor(1091 pending.request,1092 { csrf, request: sealed },1093 { displayName: pending.displayName, email: pending.email },1094 409,1095 Says.handleTakenSince1096 );10971098 return yield* withCsrfCookie(csrf)(page);1099 }),1100 })1101 );1102 });11031104// Resetting a password by a code mailed to the account's address11051106const PendingReset = Schema.Struct({1107 csrf: Schema.String,1108 email: Email,1109 request: AuthRequest,1110 tag: Schema.String,1111});11121113const pendingResets = sealing("reset-code", PendingReset);11141115const showReset = Effect.gen(function* () {1116 const { cookieKey } = yield* SignInKeys;11171118 const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(1119 Schema.Struct({ request: Schema.String })1120 ).pipe(Effect.mapError(() => startAgain));11211122 const pending = yield* openState(cookieKey, sealed);11231124 const asker = yield* askerOf(pending.request);11251126 return htmlPage(1127 resetPage(1128 asker,1129 { csrf: pending.csrf, request: sealed },1130 authorizeHref(pending.request)1131 ),1132 200,1133 pending.request.redirectUri1134 );1135});11361137const 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});11431144// Says the same whether or not an account has the address; only one that has gets a mail.1145const reset = (request: HttpServerRequest.HttpServerRequest) =>1146 Effect.gen(function* () {1147 const { cookieKey } = yield* SignInKeys;11481149 const accounts = yield* Accounts;11501151 const attempts = yield* SignInAttempts;11521153 const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedEmail).pipe(1154 Effect.mapError(() => startAgain)1155 );11561157 const pending = yield* openState(cookieKey, form.request);11581159 yield* sameCsrf(request, form.csrf, pending.csrf);11601161 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 );11751176 const email = decodeEmail(form.email.trim());11771178 if (Option.isNone(email)) {1179 return yield* again(400, Says.emailSpelling);1180 }11811182 const admitted = yield* Effect.all([1183 attempts.admit(`reset:${addressOf(request)}`),1184 mailAdmitted(email.value),1185 ]);11861187 if (!admitted.every(Boolean)) {1188 return yield* again(429, Says.tooManyMails);1189 }11901191 const account = yield* accounts.findByEmail(email.value);11921193 const tag = yield* (1194 Option.isSome(account) ? mailCode("reset", email.value) : deadTag1195 ).pipe(Effect.option);11961197 if (Option.isNone(tag)) {1198 return yield* again(503, Says.mailFailed);1199 }12001201 const sealed = yield* pendingResets.seal(cookieKey, {1202 csrf: form.csrf,1203 email: email.value,1204 request: pending.request,1205 tag: tag.value,1206 });12071208 return yield* codePageFor(1209 { csrf: form.csrf, request: pending.request, sealed },1210 resetCode(pending.request, email.value),1211 2001212 );1213 });12141215const PostedReset = Schema.Struct({1216 code: Schema.String,1217 csrf: Schema.String,1218 password: Schema.String,1219 request: Schema.String,1220});12211222const resetVerified = (request: HttpServerRequest.HttpServerRequest) =>1223 Effect.gen(function* () {1224 const { cookieKey, pepper } = yield* SignInKeys;12251226 const accounts = yield* Accounts;12271228 const form = yield* HttpServerRequest.schemaBodyUrlParams(PostedReset).pipe(1229 Effect.mapError(() => startAgain)1230 );12311232 const pending = yield* pendingResets.open(cookieKey, form.request);12331234 yield* sameCsrf(request, form.csrf, pending.csrf);12351236 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 );12431244 if (!passwordFits(form.password)) {1245 return yield* again(400, Says.passwordLength);1246 }12471248 if (!(yield* codeTried(pending.email))) {1249 return yield* again(429, Says.tooManyCodes);1250 }12511252 const right = yield* codeMatches(1253 cookieKey,1254 "reset",1255 pending.email,1256 pending.tag,1257 form.code1258 );12591260 const account = right1261 ? yield* accounts.findByEmail(pending.email)1262 : Option.none();12631264 if (Option.isNone(account)) {1265 return yield* again(401, Says.codeWrong);1266 }12671268 yield* accounts.setPasswordHash(1269 account.value.handle,1270 yield* hashPassword(pepper, Redacted.make(form.password))1271 );12721273 return yield* completed(account.value.handle, pending.request);1274 });12751276const cliClient = Effect.gen(function* () {1277 const { origin } = yield* Authorization;12781279 return HttpServerResponse.jsonUnsafe(cliClientMetadata(origin), {
28 unmodified lines
13081309export type SignInServices =1310 | Accounts1311 | HeldHandles1312 | Mailer1313 | OAuthStore1314 | SignInAttempts1315 | SignInKeys1316 | SignInOffers;
1 unmodified line
1318export 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 lines
1343 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);13541355 for (const path of AUTHORIZATION_SERVER_PATHS) {1356 yield* add("*", path, authorizationServer);
3 unmodified lines
modified:apps/platform/src/platform.ts+1 added
57 unmodified lines
58 ),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 lines
modified:apps/platform/test/accounts.test.ts+125 added-11 removed
4 unmodified lines
5import { Effect, Exit, FileSystem, Layer, Option } from "effect";6import { SqlClient } from "effect/sql/SqlClient";78import { AccountsD1 } from "../src/adapters/accounts-d1.ts";9import { Accounts, HandleTaken } from "../src/auth/accounts.ts";9import {10 Accounts,11 DisplayName,12 Email,13 EmailTaken,14 HandleTaken,15} from "../src/auth/accounts.ts";16import { AccountsMemory } from "../src/auth/accounts/memory.ts";17import { PasswordHash } from "../src/auth/password.ts";1819const alice = Handle.make("alice");
1 unmodified line
21const first = PasswordHash.make("pbkdf2-sha256$100000$Zmlyc3Q$Zmlyc3Q");2223const second = PasswordHash.make("pbkdf2-sha256$100000$c2Vjb25k$c2Vjb25k");2425const aliceEmail = Email.make("alice@mail.example");2627const aliceName = DisplayName.make("Alice Example");2829const find = (handle: string) =>30 Accounts.use((accounts) => accounts.find(Handle.make(handle)));3132const describeAccounts = (adapter: string, layer: Layer.Layer<Accounts>) => {
1 unmodified line
34 it.effect("finds an account by its handle, in any case", () =>35 Effect.gen(function* () {36 const accounts = yield* Accounts;3728 yield* accounts.create(Handle.make("Alice"), first);38 yield* accounts.create({ handle: Handle.make("Alice"), hash: first });3940 const found = Option.some({41 handle: Handle.make("Alice"),42 hash: first,
16 unmodified lines
59 () =>60 Effect.gen(function* () {61 const accounts = yield* Accounts;6253 yield* accounts.create(alice, first);63 yield* accounts.create({ handle: alice, hash: first });6465 const taken = yield* Effect.flip(56 accounts.create(Handle.make("ALICE"), second)66 accounts.create({ handle: Handle.make("ALICE"), hash: second })67 );6869 expect(taken).toStrictEqual(70 new HandleTaken({ handle: Handle.make("ALICE") })
9 unmodified lines
80 const accounts = yield* Accounts;8182 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 lines
96 it.effect("replaces an account's password hash", () =>97 Effect.gen(function* () {98 const accounts = yield* Accounts;9988 yield* accounts.create(alice, first);100 yield* accounts.create({ handle: alice, hash: first });101 yield* accounts.setPasswordHash(Handle.make("ALICE"), second);102103 expect(yield* find("alice")).toStrictEqual(104 Option.some({ handle: alice, hash: second })105 );106 }).pipe(Effect.provide(layer))107 );108109 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;114115 const account = {116 displayName: aliceName,117 email: aliceEmail,118 handle: alice,119 hash: first,120 };121122 yield* accounts.create(account);123124 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 );133134 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;139140 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 });147148 const shouted = Email.make("ALICE@mail.example");149150 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 );162163 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;168169 const bobEmail = Email.make("bob@mail.example");170171 yield* accounts.create({ handle: alice, hash: first });172 yield* accounts.create({173 email: bobEmail,174 handle: Handle.make("bob"),175 hash: second,176 });177178 yield* accounts.setEmail(Handle.make("ALICE"), aliceEmail);179180 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};200201describeAccounts("memory", Layer.fresh(AccountsMemory.layer));
3 unmodified lines
205 const fs = yield* FileSystem.FileSystem;206207 const sql = yield* SqlClient;208209 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 );213214 // 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() !== "");221222 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));228229const database = migrated.pipe(
5 unmodified lines
modified:apps/platform/test/bindings.test.ts+6 added
21 unmodified lines
22import type { DoProjects } from "../src/adapters/do-projects.ts";23import type { LanderSandbox } from "../src/adapters/lander-sandbox.ts";24import type { WorkerRateLimits } from "../src/adapters/rate-limits.ts";25import type { SignInAttemptsBinding } from "../src/auth/attempts/binding.ts";26import type { MailerBinding } from "../src/auth/mailer/binding.ts";27import type { tokenReader } from "../src/auth/provider.ts";28import {29 PlatformBindings,30 PlatformSecrets,
73 unmodified lines
104 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 lines
161 ...(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 lines
437 >();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 lines
modified:apps/platform/test/fake-env.ts+1 added
126 unmodified lines
127 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 lines
modified:apps/platform/test/google.fixtures.ts+26 added-3 removed
7 unmodified lines
8import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";9import { GOOGLE_DISCOVERY } from "../src/auth/google.ts";10import { Identities } from "../src/auth/identities.ts";11import { IdentitiesMemory } from "../src/auth/identities/memory.ts";12import { MailerMemory } from "../src/auth/mailer/memory.ts";13import { OAuthStore } from "../src/auth/oauth-store.ts";14import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";15import { oauthProvider, signInSettings } from "../src/auth/provider.ts";16import { decodeEnv } from "../src/platform.ts";
73 unmodified lines
9091export 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}101102// 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.104export const googleEmailOf = (sub: string) => `person-${sub}@mail.example`;105106export const googleNameOf = (sub: string) => `Person ${sub}`;107108export interface Consent {109 readonly claims?: Claims;110 readonly kid?: string;111 readonly signWith?: KeyPair;
6 unmodified lines
118 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});125126const decodeAuthorizationRequest =
53 unmodified lines
180 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 lines
244 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 lines
415 );416417 const store = OAuthStoreMemory.make();418419 const mailer = yield* MailerMemory.make();420421 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 lines
448 Effect.andThen(Effect.sync(() => vi.unstubAllGlobals()))449 )450 );451436 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 });461462export type GoogleWorld = Effect.Success<ReturnType<typeof googleWorld>>;
modified:apps/platform/test/google.test.ts+218 added-40 removed
14 unmodified lines
15} from "effect";16import { SqlClient } from "effect/sql/SqlClient";1718import { IdentitiesD1 } from "../src/adapters/identities-d1.ts";19import { Email } from "../src/auth/accounts.ts";20import {21 GOOGLE_DISCOVERY,22 googleAuthorizeUrl,23 GoogleKeysPerIsolate,23 googleSubject,24 googlePerson,25} from "../src/auth/google.ts";26import type { GoogleKeys } from "../src/auth/google.ts";27import { Identities, IdentityTaken } from "../src/auth/identities.ts";28import { IdentitiesMemory } from "../src/auth/identities/memory.ts";
6 unmodified lines
35import {36 clientId,37 clientSecret,38 fakeGoogle,39 googleEmailOf,40 googleEnv,41 googleNameOf,42 googleWorld,43 jwksUri,44} from "./google.fixtures.ts";45import type {
188 unmodified lines
234235const nonce = "nonce-0123456789abcdef";236237describe("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 lines
257 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 lines
272 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();280278const subjectOf = (281const 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);288286 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 line
295 redirectUri: callbackUri,296 });297 });298299const subjectOf = (300 google: FakeGoogle,301 consent: Consent,302 kept: { readonly codeVerifier?: string; readonly nonce?: string } = {}303) => Effect.map(personOf(google, consent, kept), ({ subject }) => subject);304305const withGoogle = <A, E>(306 body: (google: FakeGoogle) => Effect.Effect<A, E, Fetch | GoogleKeys>307) =>308 Effect.gen(function* () {
8 unmodified lines
317 );318 });319320describe("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" });327328 const unverified = yield* personOf(google, {329 claims: { email_verified: false },330 sub: "1042",331 });332333 const malformed = yield* personOf(google, {334 claims: { email: "not an address" },335 sub: "1042",336 });337338 const bare = yield* personOf(google, {339 claims: { email: undefined, name: undefined },340 sub: "1042",341 });342343 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 );361362 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 lines
618 })619 );620621 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 lines
647 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 lines
713 Effect.flatMap(read)714 );715 });716667const chooseHandle = (world: GoogleWorld, page: Page, handle: string) =>717const 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);725726 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 lines
755756 return summary?.grant.props;757 });758703const isPickHandle = (page: Page) => page.html.includes("Choose your handle");759const isPickHandle = (page: Page) => page.html.includes("Set up your profile");760761describe("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 lines
770 yield* continueWithGoogle(world),771 { sub: "1042" }772 );773718 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]);779780 const signedIn = yield* chooseHandle(world, page, "carol");781782 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 lines
841842 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 lines
901 () =>902 Effect.gen(function* () {903 const world = yield* googleWorld();904844 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 });912913 const page = yield* backFromGoogle(914 world,915 yield* continueWithGoogle(world),
14 unmodified lines
930 })931 );932});933934const 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 });944945describe("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();951952 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 });960961 const page = yield* backFromGoogle(962 world,963 yield* continueWithGoogle(world),964 { sub: "1042" }965 );966967 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 );976977 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();982983 const page = yield* backFromGoogle(984 world,985 yield* continueWithGoogle(world),986 { claims: { email_verified: false }, sub: "1042" }987 );988989 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 );10001001 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();10061007 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 });10171018 const page = yield* backFromGoogle(1019 world,1020 yield* continueWithGoogle(world),1021 { sub: "5150" }1022 );10231024 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 );10311032 it.live("refuses a display name by sign-up's rule, and asks again", () =>1033 Effect.gen(function* () {1034 const world = yield* googleWorld();10351036 const page = yield* backFromGoogle(1037 world,1038 yield* continueWithGoogle(world),1039 { sub: "1042" }1040 );10411042 const refused = yield* chooseHandle(world, page, "carol", " ").pipe(1043 Effect.flatMap(read)1044 );10451046 expect([1047 refused.response.status,1048 isPickHandle(refused),1049 refused.html.includes("display name"),1050 ]).toStrictEqual([400, true, true]);1051 })1052 );1053});10541055describe("Google not confirming anyone", () => {1056 it.live.each([1057 ["a signature by another key", "impostor"],1058 ["another client's audience", "audience"],
114 unmodified lines
1173 })1174 );1175});1176995const 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 });10051177const signInAndLink = (world: GoogleWorld, handle: string, password: string) =>1178 Effect.gen(function* () {1179 const form = yield* formIn(yield* openSignIn(world));11801181 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 lines
1209 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 ]);12231224 const later = yield* backFromGoogle(1225 world,1226 yield* continueWithGoogle(world),
19 unmodified lines
1246 ).pipe(Effect.flatMap(read));12471248 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 lines
1299 [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 lines
added:apps/platform/test/mailer.test.ts+90 added
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Effect } from "effect";45import { Email } from "../src/auth/accounts.ts";6import { MailFailed, Mailer } from "../src/auth/mailer.ts";7import { MAIL_FROM, MailerBinding } from "../src/auth/mailer/binding.ts";8import { MailerMemory } from "../src/auth/mailer/memory.ts";910const mail = {11 subject: "123456 is your code",12 text: "Your code is 123456.",13 to: Email.make("alice@mail.example"),14};1516const sendWith = (binding: SendEmail) =>17 Mailer.use((mailer) => mailer.send(mail)).pipe(18 Effect.provide(MailerBinding(binding))19 );2021describe("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[] = [];2728 const binding: SendEmail = {29 send: (message: EmailMessage | EmailMessageBuilder) => {30 sent.push(message);3132 return Promise.resolve({ messageId: "message-1" });33 },34 };3536 yield* sendWith(binding);3738 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 );5253 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 };5859 expect(yield* Effect.flip(sendWith(binding))).toStrictEqual(60 new MailFailed()61 );62 })63 );64});6566describe("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();7273 const failing = yield* MailerMemory.make({ failing: true });7475 yield* Mailer.use((mailer) => mailer.send(mail)).pipe(76 Effect.provide(kept.layer)77 );7879 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 lines
7import { AccountsMemory } from "../src/auth/accounts/memory.ts";8import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";9import { cliClientId } from "../src/auth/cli-client.ts";10import { IdentitiesMemory } from "../src/auth/identities/memory.ts";11import { MailerMemory } from "../src/auth/mailer/memory.ts";12import { OAuthStore } from "../src/auth/oauth-store.ts";13import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";14import { oauthProvider, signInSettings } from "../src/auth/provider.ts";15import { decodeEnv } from "../src/platform.ts";
30 unmodified lines
46const decodeTokenRecord = Schema.decodeUnknownEffect(47 Schema.Record(Schema.String, Schema.Unknown)48);4950export const signInWorld = (options: { readonly mailFails?: boolean } = {}) =>49export 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);5352 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 );5857 const store = OAuthStoreMemory.make();59 const store = OAuthStoreMemory.make();6059 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 });6468 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 );7470 const send = (request: Request) => handler.fetch(request, fakeEnv(), context);75 const { dispose, handler } = oauthProvider(services, platformFetch);7672 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);7987 const fetch = (request: Request) => Effect.promise(() => send(request));8889 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 );9494 const now = yield* Clock.currentTimeMillis;95 const fetch = (request: Request) => Effect.promise(() => send(request));9696 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);100101 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 });101111 return { accounts, expireTokens, fetch, store };112});102 const now = yield* Clock.currentTimeMillis;103114export 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);108109 yield* Effect.promise(() =>110 store.put(111 name,112 JSON.stringify({ ...token, expiresAt: Math.floor(now / 1000) - 1 }),113 { metadata }114 )115 );116 }117 });118119 return { accounts, expireTokens, fetch, mails: mailer.sent, store };120 });121122export type World = Effect.Success<ReturnType<typeof signInWorld>>;123124export interface SignInForm {125 readonly cookie: string;126 readonly csrf: string;127 readonly request: string;
79 unmodified lines
modified:apps/platform/test/oauth.test.ts+676 added-32 removed
5 unmodified lines
6import { Effect, Option, Redacted, Schema } from "effect";7import { TestClock } from "effect/testing";89import { OAuthSessions } from "../src/adapters/sessions-oauth.ts";10import { Email } from "../src/auth/accounts.ts";11import { SignInAttempts } from "../src/auth/attempts.ts";12import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";13import { cliClientMetadata } from "../src/auth/cli-client.ts";14import { codeMatches, codeTag, deadTag, freshCode } from "../src/auth/codes.ts";15import type { CodePurpose } from "../src/auth/codes.ts";16import { ACCOUNT_PATHS } from "../src/auth/pages.ts";17import {18 hashPassword,19 hashPasswordWith,20 PasswordHash,
287 unmodified lines
308 Effect.fromOption(formOf(page.response, page.html, cookie)).pipe(309 Effect.orDie310 );311308const signUp = (world: World, handle: string, secret: string) =>312// A valid address for any handle a test tries, valid or not.313const emailOf = (handle: string) =>314 `${handle.toLowerCase().replaceAll(/[^a-z0-9]/gu, "-")}@mail.example`;315316// The code in the newest mail to `to`; a mail with no code reads as none.317const 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 );325326interface Started {327 readonly cookie: string;328 readonly page: Page;329}330331const 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));342343 const page = yield* world
8 unmodified lines
352 .pipe(Effect.flatMap(read));353354 const form = yield* formIn(page, signInForm.cookie);355356 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));372373 return { cookie: form.cookie, page: started } satisfies Started;374 });375376const 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);385386 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 });394395// The whole sign-up: the form, then the code mailed to the address. A form396// the platform refuses comes back as it is.334const signIn = (397const 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 });409410 // Read already, so handed back afresh.411 if (started.page.response.status !== 200) {412 return new Response(started.page.html, started.page.response);413 }414415 const code = yield* Effect.fromOption(416 yield* codeMailedTo(world, email)417 ).pipe(Effect.orDie);418419 return yield* enterCode(world, started, ACCOUNT_PATHS.signUpVerify, code);420 });421422const 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));430431 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 lines
466467describe("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();471472 const response = yield* world.fetch(473 new Request(new URL("/.well-known/oauth-authorization-server", origin))474 );
10 unmodified lines
485 );486487 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();490491 const response = yield* world.fetch(new Request(cliClient));492493 expect(response.status).toBe(200);
4 unmodified lines
498 );499500 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();503504 const page = yield* world505 .fetch(new Request(new URL("/rpc", origin)))506 .pipe(Effect.flatMap(read));
8 unmodified lines
515 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();520521 const page = yield* openSignIn(world);522523 expect([
16 unmodified lines
540 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();545546 const page = yield* world547 .fetch(548 new Request(
48 unmodified lines
597 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();602603 const response = yield* signUp(world, "alice", alicePassword);604605 expect(response.status).toBe(302);
2 unmodified lines
608 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 );621622 it.live("says a handle is taken, in any case", () =>623 Effect.gen(function* () {532 const world = yield* signInWorld;624 const world = yield* signInWorld();625626 yield* signUp(world, "alice", alicePassword);627628 const page = yield* signUp(world, "ALICE", "another long password").pipe(
9 unmodified lines
638 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();643644 const pages = yield* Effect.forEach(645 [fakeEnv().OPERATOR_HANDLE.toUpperCase(), namedPerson],646 (handle) =>
26 unmodified lines
673 ])(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();678679 const page = yield* signUp(world, handle, alicePassword).pipe(680 Effect.flatMap(read)681 );
5 unmodified lines
687 );688689 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();692693 const short = yield* signUp(world, "alice", "elevenchars").pipe(694 Effect.flatMap(read)695 );
18 unmodified lines
714 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();719720 yield* signUp(world, "Alice", alicePassword);721722 const { access_token, token_type } = yield* accessTokenFor(
15 unmodified lines
738 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();743744 yield* signUp(world, "alice", alicePassword);745746 const wrong = yield* signIn(world, "alice", "not the password").pipe(
5 unmodified lines
752 );753754 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 lines
765 );766767 it.live("refuses a code traded with the wrong verifier", () =>768 Effect.gen(function* () {675 const world = yield* signInWorld;769 const world = yield* signInWorld();770771 const code = yield* signUp(world, "alice", alicePassword).pipe(772 Effect.flatMap(codeIn)773 );
15 unmodified lines
789 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();794795 yield* signUp(world, "alice", alicePassword);796797 const form = yield* formIn(yield* openSignIn(world));
15 unmodified lines
813 post(814 "/authorize",815 {816 csrf: attempt.csrf,723 handle: "alice",817 login: "alice",818 password: alicePassword,819 request: attempt.request,820 },821 attempt.cookie
11 unmodified lines
833 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();838839 yield* signUp(world, "alice", alicePassword);840841 const statuses = yield* Effect.forEach([1, 2, 3, 4, 5], (n) =>
17 unmodified lines
859 );860861 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();864865 const statuses = yield* Effect.forEach(866 ["bob", "carol", "dave", "erin", "frank", "grace"],867 (handle) =>
9 unmodified lines
877 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();882883 const alice = Handle.make("alice");884791 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 });893894 yield* signIn(world, "alice", alicePassword).pipe(895 Effect.flatMap(codeIn)896 );
11 unmodified lines
908 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();913914 yield* signUp(world, "alice", alicePassword);915916 const { access_token } = yield* accessTokenFor(
18 unmodified lines
935 );936 })937 );938});939940describe("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();946947 const started = yield* startSignUp(world, {948 email: "Alice@Mail.Example",949 handle: "alice",950 password: alicePassword,951 });952953 const [mail] = yield* world.mails;954955 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 );968969 it.live("refuses a wrong code, and makes no account", () =>970 Effect.gen(function* () {971 const world = yield* signInWorld();972973 const started = yield* startSignUp(world, {974 email: emailOf("alice"),975 handle: "alice",976 password: alicePassword,977 });978979 const code = yield* Effect.fromOption(980 yield* codeMailedTo(world, emailOf("alice"))981 ).pipe(Effect.orDie);982983 const wrong = code === "000000" ? "000001" : "000000";984985 const page = yield* enterCode(986 world,987 started,988 ACCOUNT_PATHS.signUpVerify,989 wrong990 ).pipe(Effect.flatMap(read));991992 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 );10001001 it.live("takes a code with spaces in it", () =>1002 Effect.gen(function* () {1003 const world = yield* signInWorld();10041005 const started = yield* startSignUp(world, {1006 email: emailOf("alice"),1007 handle: "alice",1008 password: alicePassword,1009 });10101011 const code = yield* Effect.fromOption(1012 yield* codeMailedTo(world, emailOf("alice"))1013 ).pipe(Effect.orDie);10141015 const response = yield* enterCode(1016 world,1017 started,1018 ACCOUNT_PATHS.signUpVerify,1019 `${code.slice(0, 3)} ${code.slice(3)}`1020 );10211022 expect(Option.isSome(codeOf(response))).toBeTruthy();1023 })1024 );10251026 it.live("refuses the sixth code tried for one address in a minute", () =>1027 Effect.gen(function* () {1028 const world = yield* signInWorld();10291030 const started = yield* startSignUp(world, {1031 email: emailOf("alice"),1032 handle: "alice",1033 password: alicePassword,1034 });10351036 const code = yield* Effect.fromOption(1037 yield* codeMailedTo(world, emailOf("alice"))1038 ).pipe(Effect.orDie);10391040 const wrong = code === "000000" ? "000001" : "000000";10411042 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 );10471048 const sixth = yield* enterCode(1049 world,1050 started,1051 ACCOUNT_PATHS.signUpVerify,1052 code1053 );10541055 expect([...statuses, sixth.status]).toStrictEqual([1056 401, 401, 401, 401, 401, 429,1057 ]);1058 })1059 );10601061 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();10661067 yield* signUp(world, "alice", alicePassword);10681069 const started = yield* startSignUp(world, {1070 email: emailOf("alice").toUpperCase(),1071 handle: "mallory",1072 password: "another long password",1073 });10741075 const mails = yield* world.mails;10761077 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);10811082 const page = yield* enterCode(1083 world,1084 started,1085 ACCOUNT_PATHS.signUpVerify,1086 "123456"1087 );10881089 expect([1090 page.status,1091 Option.isNone(yield* world.accounts.find(Handle.make("mallory"))),1092 ]).toStrictEqual([401, true]);1093 })1094 );10951096 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();11011102 const started = yield* startSignUp(world, {1103 email: emailOf("first"),1104 handle: "alice",1105 password: alicePassword,1106 });11071108 yield* signUp(world, "alice", alicePassword, emailOf("second"));11091110 const code = yield* Effect.fromOption(1111 yield* codeMailedTo(world, emailOf("first"))1112 ).pipe(Effect.orDie);11131114 const page = yield* enterCode(1115 world,1116 started,1117 ACCOUNT_PATHS.signUpVerify,1118 code1119 ).pipe(Effect.flatMap(read));11201121 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 );11261127 it.live("says the mail could not go, and makes no account", () =>1128 Effect.gen(function* () {1129 const world = yield* signInWorld({ mailFails: true });11301131 const started = yield* startSignUp(world, {1132 email: emailOf("alice"),1133 handle: "alice",1134 password: alicePassword,1135 });11361137 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 );11421143 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();11501151 const started = yield* startSignUp(world, {1152 email: emailOf("alice"),1153 handle: "alice",1154 password: alicePassword,1155 ...fields,1156 });11571158 expect(started.page.response.status).toBe(400);1159 expect(started.page.html).toContain(said);1160 expect(yield* world.mails).toStrictEqual([]);1161 })1162 );1163});11641165describe("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();11691170 yield* signUp(world, "Alice", alicePassword);11711172 const { access_token } = yield* accessTokenFor(1173 world,1174 emailOf("alice").toUpperCase(),1175 alicePassword1176 );11771178 const summary = yield* Effect.promise(() =>1179 tokenReader(world.store).unwrapToken(access_token)1180 );11811182 expect(summary?.grant.props).toStrictEqual({ handle: "Alice" });1183 })1184 );1185});11861187const 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 });11941195describe("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();12011202 yield* legacyAccount(world);12031204 const asked = yield* signIn(world, "alice", alicePassword).pipe(1205 Effect.flatMap(read)1206 );12071208 expect(asked.response.status).toBe(200);1209 expect(asked.html).toContain("Add your email");1210 expect(Option.isNone(codeOf(asked.response))).toBeTruthy();12111212 const form = yield* formIn(asked);12131214 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));12271228 const code = yield* Effect.fromOption(1229 yield* codeMailedTo(world, emailOf("alice"))1230 ).pipe(Effect.orDie);12311232 const done = yield* enterCode(1233 world,1234 { cookie: form.cookie, page: sent },1235 ACCOUNT_PATHS.addEmailVerify,1236 code1237 );12381239 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 );12451246 it.live(1247 "refuses an address another account holds, once the code proves it",1248 () =>1249 Effect.gen(function* () {1250 const world = yield* signInWorld();12511252 yield* signUp(world, "bob", alicePassword);1253 yield* legacyAccount(world);12541255 const asked = yield* signIn(world, "alice", alicePassword).pipe(1256 Effect.flatMap(read)1257 );12581259 const form = yield* formIn(asked);12601261 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));12701271 const code = yield* Effect.fromOption(1272 yield* codeMailedTo(world, emailOf("bob"))1273 ).pipe(Effect.orDie);12741275 const page = yield* enterCode(1276 world,1277 { cookie: form.cookie, page: sent },1278 ACCOUNT_PATHS.addEmailVerify,1279 code1280 ).pipe(Effect.flatMap(read));12811282 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});12881289const startReset = (world: World, email: string) =>1290 Effect.gen(function* () {1291 const signInForm = yield* formIn(yield* openSignIn(world));12921293 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));13031304 const form = yield* formIn(page, signInForm.cookie);13051306 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));13151316 return { cookie: form.cookie, page: sent } satisfies Started;1317 });13181319describe("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();13251326 yield* signUp(world, "alice", alicePassword);13271328 const started = yield* startReset(world, emailOf("alice"));13291330 const code = yield* Effect.fromOption(1331 yield* codeMailedTo(world, emailOf("alice"))1332 ).pipe(Effect.orDie);13331334 const done = yield* enterCode(1335 world,1336 started,1337 ACCOUNT_PATHS.resetVerify,1338 code,1339 { password: "a brand new password" }1340 );13411342 const old = yield* signIn(world, "alice", alicePassword);13431344 const fresh = yield* signIn(world, "alice", "a brand new password");13451346 expect(Option.isSome(codeOf(done))).toBeTruthy();1347 expect(old.status).toBe(401);1348 expect(Option.isSome(codeOf(fresh))).toBeTruthy();1349 })1350 );13511352 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();13571358 yield* signUp(world, "alice", alicePassword);13591360 const before = (yield* world.mails).length;13611362 const known = yield* startReset(world, emailOf("alice"));13631364 const unknown = yield* startReset(world, emailOf("nobody"));13651366 const mails = yield* world.mails;13671368 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 ]);13781379 const page = yield* enterCode(1380 world,1381 unknown,1382 ACCOUNT_PATHS.resetVerify,1383 "123456",1384 { password: "a brand new password" }1385 );13861387 expect(page.status).toBe(401);1388 })1389 );13901391 it.live("keeps the old password when the code is wrong", () =>1392 Effect.gen(function* () {1393 const world = yield* signInWorld();13941395 yield* signUp(world, "alice", alicePassword);13961397 const started = yield* startReset(world, emailOf("alice"));13981399 const code = yield* Effect.fromOption(1400 yield* codeMailedTo(world, emailOf("alice"))1401 ).pipe(Effect.orDie);14021403 const page = yield* enterCode(1404 world,1405 started,1406 ACCOUNT_PATHS.resetVerify,1407 code === "000000" ? "000001" : "000000",1408 { password: "a brand new password" }1409 );14101411 const old = yield* signIn(world, "alice", alicePassword);14121413 expect(page.status).toBe(401);1414 expect(Option.isSome(codeOf(old))).toBeTruthy();1415 })1416 );1417});14181419describe("a mailed code", () => {1420 const email = Email.make("alice@mail.example");14211422 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 );14281429 for (const code of codes) {1430 expect(code).toMatch(/^\d{6}$/u);1431 }1432 })1433 );14341435 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");14401441 const opens = (1442 purpose: CodePurpose,1443 to: string,1444 entered: string,1445 key = cookieKey1446 ) => codeMatches(key, purpose, Email.make(to), tag, entered);14471448 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 );14741475 it.effect("never opens a dead tag", () =>1476 Effect.gen(function* () {1477 const tag = yield* deadTag;14781479 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 lines
5import { UnknownProject } from "@repo/protocol/refusal";6import { Effect, Layer, Option } from "effect";78import {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";18import type { Asker, PendingForm } from "../src/auth/pages.ts";
55 unmodified lines
74 )75);7677const 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;13297const FORMS = new Set(["Google's handle page", "sign-in", "sign-up"]);133const FORMS = new Set(134 Object.keys(PAGES).filter((name) => name !== "the problem page")135);136137interface Rule {138 readonly selectors: readonly string[];139 readonly declarations: ReadonlyMap<string, string>;
298 unmodified lines
438 });439440 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});448449describe("a sign-in form shown again", () => {450 it("escapes every value the person typed", () => {451 const typed = `"><script>alert(1)</script>`;452453 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 ];466467 for (const html of pages) {468 expect(html).not.toContain("<script>");469 expect(html).toContain(470 `value="&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;"`471 );472 }473 });474475 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});481482describe("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 });485486 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 lines
27import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";28import { AccountsMemory } from "../src/auth/accounts/memory.ts";29import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";30import { IdentitiesMemory } from "../src/auth/identities/memory.ts";31import { MailerMemory } from "../src/auth/mailer/memory.ts";32import { OAuthStore } from "../src/auth/oauth-store.ts";33import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";34import { ACCOUNT_PATHS } from "../src/auth/pages.ts";35import { oauthProvider, signInSettings } from "../src/auth/provider.ts";36import { decodeEnv, PlatformEnv, platformOf } from "../src/platform.ts";37import { workerPorts } from "../src/ports.ts";38import { serve } from "../src/surfaces.ts";
259 unmodified lines
298 const { dispose: disposePlatform, handler: platformFetch } = serve(299 platformOf(config)300 );301302 const mailer = yield* MailerMemory.make();303304 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 lines
352 );353354 const form = yield* formIn(signUpPage, signIn.cookie);355351 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));370371 const confirm = yield* formIn(mailed, form.cookie);372373 const [mail] = yield* mailer.sent;374375 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 lines
modified:apps/platform/.env.schema+4 added-2 removed
17 unmodified lines
18# @optional @sensitive19SESSION_TOKENS=2021# 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)27COOKIE_KEY=2829# Sign-in: the pepper every password is HMAC'd with before PBKDF2,
24 unmodified lines
modified: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)3interface __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 lines
39 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 lines
68 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 lines
97 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 lines
modified:apps/platform/wrangler.jsonc+6 added
86 unmodified lines
87 { "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 lines
183 { "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 lines
271 { "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 lines
362 { "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 lines
modified:AGENTS.md+2 added-2 removed
15 unmodified lines
16| 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 lines
modified:README.md+1 added-1 removed
44 unmodified lines
45The web's `/docs` holds the guides and the full reference; `/llms.txt` and `myr mcp` serve the same to agents.4647## Deploy your own4849You 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:49You 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:5051```sh52bun run bootstrap -- --stage dev-<you> # makes the stage's resources; deletes nothing53bun run deploy -- --stage dev-<you> # runs verify, deploys the three Workers, runs smoke
28 unmodified lines