oauth.test.ts
This file
Path
apps/platform/test/oauth.test.ts
1,484 lines · 41.8 KiB · TypeScript
Last changed by
Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Handle } from "@repo/protocol/ids";4import { Person } from "@repo/protocol/principal";5import { untouchable } from "@repo/testkit/untouchable";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,21 verifyPassword,22} from "../src/auth/password.ts";23import { tokenReader } from "../src/auth/provider.ts";24import { openState, sealState, SignInFailed } from "../src/auth/state.ts";25import type { PendingSignIn } from "../src/auth/state.ts";26import worker from "../src/worker.ts";27import {28 cookieKey as cookieKeyText,29 fakeEnv,30 passwordPepper,31} from "./fake-env.ts";32import {33 authorizeUrl,34 cliClient,35 codeOf,36 formOf,37 namedPerson,38 origin,39 port,40 post,41 signInWorld,42 tokenRequest,43} from "./oauth.fixtures.ts";44import type { World } from "./oauth.fixtures.ts";4546const pepper = Redacted.make(passwordPepper);4748const password = Redacted.make("correct horse battery");4950describe("a stored password", () => {51 it.effect("verifies the password it was made from, and no other", () =>52 Effect.gen(function* () {53 const stored = yield* hashPassword(pepper, password);5455 expect(yield* verifyPassword(pepper, password, stored)).toStrictEqual({56 needsRehash: false,57 ok: true,58 });59 expect(60 yield* verifyPassword(pepper, Redacted.make("wrong horse"), stored)61 ).toStrictEqual({ needsRehash: false, ok: false });62 })63 );6465 it.effect("needs the same pepper to verify", () =>66 Effect.gen(function* () {67 const stored = yield* hashPassword(pepper, password);6869 const other = Redacted.make("another-pepper-0123456789abcdef01234567");7071 expect((yield* verifyPassword(other, password, stored)).ok).toBeFalsy();72 })73 );7475 it.effect(76 "records PBKDF2-SHA-256, 100,000 iterations, a 16-byte salt and a 32-byte hash",77 () =>78 Effect.gen(function* () {79 const stored = yield* hashPassword(pepper, password);8081 const [algorithm, iterations, salt, hash] = stored.split("$");8283 expect([algorithm, iterations]).toStrictEqual([84 "pbkdf2-sha256",85 "100000",86 ]);87 // base64url without padding: 16 bytes → 22 characters, 32 → 43.88 expect([salt?.length, hash?.length]).toStrictEqual([22, 43]);89 expect(stored).not.toContain("correct horse");90 })91 );9293 it.effect("salts each hash afresh", () =>94 Effect.gen(function* () {95 const one = yield* hashPassword(pepper, password);9697 const two = yield* hashPassword(pepper, password);9899 expect(one).not.toBe(two);100 })101 );102103 it.effect(104 "made with fewer iterations than today's, still verifies and asks to be rehashed",105 () =>106 Effect.gen(function* () {107 const old = yield* hashPasswordWith(1000)(pepper, password);108109 expect(old.split("$")[1]).toBe("1000");110 expect(yield* verifyPassword(pepper, password, old)).toStrictEqual({111 needsRehash: true,112 ok: true,113 });114 })115 );116117 it("is refused when it is not one this platform writes", () => {118 expect(119 [120 "pbkdf2-sha256$100000$c2FsdA$aGFzaA",121 "bcrypt$10$salt$hash",122 "pbkdf2-sha256$0$c2FsdA$aGFzaA",123 "pbkdf2-sha256$100000$c2FsdA",124 ].map((stored) => Option.isSome(PasswordHash.makeOption(stored)))125 ).toStrictEqual([true, false, false, false]);126 });127});128129const cookieKey = Redacted.make(cookieKeyText);130131const pending: PendingSignIn = {132 csrf: "csrf-0123456789",133 request: {134 clientId: "https://platform.test/oauth/cli",135 codeChallenge: "challenge",136 codeChallengeMethod: "S256",137 redirectUri: "http://127.0.0.1:43123/callback",138 resource: "https://platform.test",139 responseType: "code",140 scope: [],141 state: "state-1",142 },143};144145const tampered = (sealed: string) =>146 `${sealed.startsWith("A") ? "B" : "A"}${sealed.slice(1)}`;147148describe("a sign-in in progress, sealed into the form", () => {149 it.effect("opens to what was sealed", () =>150 Effect.gen(function* () {151 const sealed = yield* sealState(cookieKey, pending);152153 expect(yield* openState(cookieKey, sealed)).toStrictEqual(pending);154 })155 );156157 it.effect("is refused when sealed with another key, or changed", () =>158 Effect.gen(function* () {159 const sealed = yield* sealState(cookieKey, pending);160161 const otherKey = Redacted.make("another-key-0123456789abcdef01234567");162163 const failures = yield* Effect.forEach(164 [165 openState(otherKey, sealed),166 openState(cookieKey, tampered(sealed)),167 openState(cookieKey, "not-a-seal"),168 ],169 Effect.flip170 );171172 expect(173 failures.map((failure) => failure instanceof SignInFailed)174 ).toStrictEqual([true, true, true]);175 })176 );177178 it.effect("is refused once ten minutes have passed", () =>179 Effect.gen(function* () {180 const sealed = yield* sealState(cookieKey, pending);181182 yield* TestClock.adjust("9 minutes");183184 expect(yield* openState(cookieKey, sealed)).toStrictEqual(pending);185186 yield* TestClock.adjust("2 minutes");187188 expect(yield* Effect.flip(openState(cookieKey, sealed))).toBeInstanceOf(189 SignInFailed190 );191 })192 );193});194195describe("the CLI's OAuth client", () => {196 it("is public, signs in with PKCE only, and comes back to a loopback port", () => {197 expect(cliClientMetadata("https://platform.test")).toStrictEqual({198 client_id: "https://platform.test/oauth/cli",199 client_name: `${Brand.name} CLI`,200 grant_types: ["authorization_code", "refresh_token"],201 redirect_uris: ["http://127.0.0.1/callback", "http://[::1]/callback"],202 response_types: ["code"],203 token_endpoint_auth_method: "none",204 });205 });206});207208const issued = (209 props: Readonly<Record<string, string>>,210 expiresAt: number211) => ({212 unwrapToken: (token: string) =>213 Promise.resolve(214 token === "alice:grant:secret"215 ? {216 audience: "https://platform.test",217 createdAt: 0,218 expiresAt,219 grant: { clientId: "cli", props, scope: [] },220 grantId: "grant",221 id: "id",222 scope: [],223 userId: "alice",224 }225 : null226 ),227});228229describe("OAuth sessions", () => {230 it.effect("know a token the provider issued as the handle in its props", () =>231 Effect.gen(function* () {232 const sessions = OAuthSessions(issued({ handle: "alice" }, 3600));233234 expect(yield* sessions.verify("alice:grant:secret")).toStrictEqual(235 Option.some(Person.make({ handle: Handle.make("alice") }))236 );237 })238 );239240 it.effect("know nobody by a token the provider does not know", () =>241 Effect.gen(function* () {242 const sessions = OAuthSessions(issued({ handle: "alice" }, 3600));243244 expect(yield* sessions.verify("alice:grant:other")).toStrictEqual(245 Option.none()246 );247 })248 );249250 it.effect("know nobody by a token past its expiry", () =>251 Effect.gen(function* () {252 const sessions = OAuthSessions(issued({ handle: "alice" }, 3600));253254 yield* TestClock.adjust("1 hour");255256 expect(yield* sessions.verify("alice:grant:secret")).toStrictEqual(257 Option.none()258 );259 })260 );261262 it.effect("know nobody by a token whose props name no handle", () =>263 Effect.gen(function* () {264 const sessions = OAuthSessions(issued({ userId: "alice" }, 3600));265266 expect(yield* sessions.verify("alice:grant:secret")).toStrictEqual(267 Option.none()268 );269 })270 );271});272273describe("sign-in attempts in memory", () => {274 it.effect(275 "admit five a minute under one key, then refuse until the minute is up",276 () =>277 Effect.gen(function* () {278 const attempts = yield* SignInAttempts;279280 const admitted = yield* Effect.forEach([1, 2, 3, 4, 5, 6], () =>281 attempts.admit("handle:alice")282 );283284 expect(admitted).toStrictEqual([true, true, true, true, true, false]);285 expect(yield* attempts.admit("handle:bob")).toBeTruthy();286287 yield* TestClock.adjust("1 minute");288289 expect(yield* attempts.admit("handle:alice")).toBeTruthy();290 }).pipe(Effect.provide(SignInAttemptsMemory.layer))291 );292});293294const read = (response: Response) =>295 Effect.promise(() => response.text()).pipe(296 Effect.map((html) => ({ html, response }))297 );298299interface Page {300 readonly html: string;301 readonly response: Response;302}303304const openSignIn = (world: World, state = "state-1") =>305 world.fetch(new Request(authorizeUrl(state))).pipe(Effect.flatMap(read));306307const formIn = (page: Page, cookie?: string) =>308 Effect.fromOption(formOf(page.response, page.html, cookie)).pipe(309 Effect.orDie310 );311312// 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* world344 .fetch(345 new Request(346 new URL(347 `/signup?request=${encodeURIComponent(signInForm.request)}`,348 origin349 )350 )351 )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(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.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",434 { csrf: form.csrf, login, password: secret, request: form.request },435 form.cookie,436 address437 )438 );439 });440441const TokenResponse = Schema.Struct({442 access_token: Schema.String,443 token_type: Schema.String,444});445446const codeIn = (response: Response) =>447 Effect.fromOption(codeOf(response)).pipe(Effect.orDie);448449const accessTokenFor = (world: World, handle: string, secret: string) =>450 Effect.gen(function* () {451 const code = yield* signIn(world, handle, secret).pipe(452 Effect.flatMap(codeIn)453 );454455 const response = yield* world.fetch(tokenRequest(code));456457 return yield* Effect.promise(() => response.json()).pipe(458 Effect.flatMap(Schema.decodeUnknownEffect(TokenResponse)),459 Effect.orDie460 );461 });462463const alicePassword = "correct horse battery";464465const CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'";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* () {470 const world = yield* signInWorld();471472 const response = yield* world.fetch(473 new Request(new URL("/.well-known/oauth-authorization-server", origin))474 );475476 expect(response.status).toBe(200);477 expect(yield* Effect.promise(() => response.json())).toMatchObject({478 authorization_endpoint: `${origin}/authorize`,479 client_id_metadata_document_supported: true,480 code_challenge_methods_supported: ["S256"],481 issuer: origin,482 token_endpoint: `${origin}/token`,483 });484 })485 );486487 it.live("serves the CLI's client metadata document at its client id", () =>488 Effect.gen(function* () {489 const world = yield* signInWorld();490491 const response = yield* world.fetch(new Request(cliClient));492493 expect(response.status).toBe(200);494 expect(yield* Effect.promise(() => response.json())).toStrictEqual(495 cliClientMetadata(origin)496 );497 })498 );499500 it.live("hands every other path to the rest of the platform", () =>501 Effect.gen(function* () {502 const world = yield* signInWorld();503504 const page = yield* world505 .fetch(new Request(new URL("/rpc", origin)))506 .pipe(Effect.flatMap(read));507508 expect([page.response.status, page.html]).toStrictEqual([509 418,510 "platform: /rpc",511 ]);512 })513 );514515 it.live(516 "shows the CLI a small sign-in page that loads nothing and cannot be framed",517 () =>518 Effect.gen(function* () {519 const world = yield* signInWorld();520521 const page = yield* openSignIn(world);522523 expect([524 page.response.status,525 page.response.headers.get("content-type"),526 page.response.headers.get("content-security-policy"),527 page.response.headers.get("x-frame-options"),528 ]).toStrictEqual([529 200,530 "text/html; charset=utf-8",531 `${CSP} http://127.0.0.1:${port}`,532 "DENY",533 ]);534 expect(page.html).toContain(`${Brand.name} CLI`);535 expect(page.html).not.toMatch(/<script|<link|<img|src=|url\(|@import/u);536 expect(Option.isSome(formOf(page.response, page.html))).toBeTruthy();537 })538 );539540 it.live(541 "lets the code go back to an IPv6 loopback, which no CSP host can name",542 () =>543 Effect.gen(function* () {544 const world = yield* signInWorld();545546 const page = yield* world547 .fetch(548 new Request(549 authorizeUrl("state-1", `http://[::1]:${port}/callback`)550 )551 )552 .pipe(Effect.flatMap(read));553554 expect([555 page.response.status,556 page.response.headers.get("content-security-policy"),557 ]).toStrictEqual([200, `${CSP} http:`]);558 })559 );560});561562const sendToWorker = (path: string) =>563 Effect.promise(() =>564 Promise.resolve(565 worker.fetch(566 new Request(new URL(path, origin)),567 fakeEnv(),568 untouchable<ExecutionContext>("ExecutionContext")569 )570 )571 );572573describe("the Worker's default export", () => {574 it.live(575 "answers OAuth metadata itself and hands everything else to the platform, touching no binding",576 () =>577 Effect.gen(function* () {578 const metadata = yield* sendToWorker(579 "/.well-known/oauth-authorization-server"580 );581582 const health = yield* sendToWorker("/health");583584 expect([metadata.status, health.status]).toStrictEqual([200, 200]);585 expect([586 yield* Effect.promise(() => metadata.json()),587 yield* Effect.promise(() => health.json()),588 ]).toMatchObject([589 { issuer: origin, token_endpoint: `${origin}/token` },590 { ok: true, stage: "local" },591 ]);592 })593 );594});595596describe("signing up", () => {597 it.live(598 "creates the account and signs it in, back to the CLI with a code",599 () =>600 Effect.gen(function* () {601 const world = yield* signInWorld();602603 const response = yield* signUp(world, "alice", alicePassword);604605 expect(response.status).toBe(302);606 expect(Option.isSome(codeOf(response))).toBeTruthy();607 expect(608 new URL(response.headers.get("location") ?? "").searchParams.get(609 "state"610 )611 ).toBe("state-1");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* () {624 const world = yield* signInWorld();625626 yield* signUp(world, "alice", alicePassword);627628 const page = yield* signUp(world, "ALICE", "another long password").pipe(629 Effect.flatMap(read)630 );631632 expect(page.response.status).toBe(409);633 expect(page.html).toContain("taken");634 expect(Option.isNone(codeOf(page.response))).toBeTruthy();635 })636 );637638 it.live(639 "says the operator's handle and a named session's are taken, in any case",640 () =>641 Effect.gen(function* () {642 const world = yield* signInWorld();643644 const pages = yield* Effect.forEach(645 [fakeEnv().OPERATOR_HANDLE.toUpperCase(), namedPerson],646 (handle) =>647 signUp(world, handle, alicePassword).pipe(Effect.flatMap(read))648 );649650 for (const page of pages) {651 expect(page.response.status).toBe(409);652 expect(page.html).toContain("taken");653 expect(Option.isNone(codeOf(page.response))).toBeTruthy();654 }655 })656 );657658 it.live.each([659 ["-alice", "letters, digits and dashes"],660 ["al ice", "letters, digits and dashes"],661 [Brand.slug, "reserved"],662 ["Admin", "reserved"],663 ["platform", "reserved"],664 ["root", "reserved"],665 ["api", "reserved"],666 ["www", "reserved"],667 ["support", "reserved"],668 ["security", "reserved"],669 ["people", "reserved"],670 ["import", "reserved"],671 ["datekit", "reserved"],672 ["Click", "reserved"],673 ])(674 "refuses the handle %s with a plain reason",675 ([handle = "", reason = ""]) =>676 Effect.gen(function* () {677 const world = yield* signInWorld();678679 const page = yield* signUp(world, handle, alicePassword).pipe(680 Effect.flatMap(read)681 );682683 expect(page.response.status).toBe(400);684 expect(page.html).toContain(reason);685 expect(Option.isNone(codeOf(page.response))).toBeTruthy();686 })687 );688689 it.live("refuses a password under 12 or over 256 characters", () =>690 Effect.gen(function* () {691 const world = yield* signInWorld();692693 const short = yield* signUp(world, "alice", "elevenchars").pipe(694 Effect.flatMap(read)695 );696697 const long = yield* signUp(world, "alice", "x".repeat(257)).pipe(698 Effect.flatMap(read)699 );700701 const exact = yield* signUp(world, "alice", "twelve chars");702703 expect([short.response.status, long.response.status]).toStrictEqual([704 400, 400,705 ]);706 expect(short.html).toContain("12 to 256 characters");707 expect(long.html).toContain("12 to 256 characters");708 expect(exact.status).toBe(302);709 })710 );711});712713describe("signing in from the CLI", () => {714 it.live(715 "trades a code and its verifier for an access token that names only the person",716 () =>717 Effect.gen(function* () {718 const world = yield* signInWorld();719720 yield* signUp(world, "Alice", alicePassword);721722 const { access_token, token_type } = yield* accessTokenFor(723 world,724 "alice",725 alicePassword726 );727728 expect(token_type).toBe("bearer");729730 const summary = yield* Effect.promise(() =>731 tokenReader(world.store).unwrapToken(access_token)732 );733734 expect(summary?.grant.props).toStrictEqual({ handle: "Alice" });735 })736 );737738 it.live(739 "says only that the handle or password is wrong, and issues no code",740 () =>741 Effect.gen(function* () {742 const world = yield* signInWorld();743744 yield* signUp(world, "alice", alicePassword);745746 const wrong = yield* signIn(world, "alice", "not the password").pipe(747 Effect.flatMap(read)748 );749750 const nobody = yield* signIn(world, "bob", alicePassword).pipe(751 Effect.flatMap(read)752 );753754 for (const page of [wrong, nobody]) {755 expect(page.response.status).toBe(401);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();763 }764 })765 );766767 it.live("refuses a code traded with the wrong verifier", () =>768 Effect.gen(function* () {769 const world = yield* signInWorld();770771 const code = yield* signUp(world, "alice", alicePassword).pipe(772 Effect.flatMap(codeIn)773 );774775 const response = yield* world.fetch(776 tokenRequest(777 code,778 "a-verifier-of-the-right-length-but-not-the-right-one"779 )780 );781782 expect(response.status).toBe(400);783 expect(yield* Effect.promise(() => response.json())).toMatchObject({784 error: "invalid_grant",785 });786 })787 );788789 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* () {793 const world = yield* signInWorld();794795 yield* signUp(world, "alice", alicePassword);796797 const form = yield* formIn(yield* openSignIn(world));798799 const forged = yield* sealState(800 Redacted.make("not-the-cookie-key-0123456789abcdef"),801 yield* openState(cookieKey, form.request)802 );803804 const attempts = [805 { ...form, request: forged },806 { ...form, csrf: "not-the-csrf-token" },807 { ...form, cookie: "not-the-csrf-token" },808 ];809810 for (const attempt of attempts) {811 const page = yield* world812 .fetch(813 post(814 "/authorize",815 {816 csrf: attempt.csrf,817 login: "alice",818 password: alicePassword,819 request: attempt.request,820 },821 attempt.cookie822 )823 )824 .pipe(Effect.flatMap(read));825826 expect(page.response.status).toBe(400);827 expect(page.html).toContain("Start signing in again");828 expect(Option.isNone(codeOf(page.response))).toBeTruthy();829 }830 })831 );832833 it.live(834 "refuses the sixth attempt in a minute for one handle before checking the password",835 () =>836 Effect.gen(function* () {837 const world = yield* signInWorld();838839 yield* signUp(world, "alice", alicePassword);840841 const statuses = yield* Effect.forEach([1, 2, 3, 4, 5], (n) =>842 signIn(world, "alice", "not the password", `198.51.100.${n}`).pipe(843 Effect.map(({ status }) => status)844 )845 );846847 const sixth = yield* signIn(848 world,849 "ALICE",850 alicePassword,851 "198.51.100.6"852 ).pipe(Effect.flatMap(read));853854 expect(statuses).toStrictEqual([401, 401, 401, 401, 401]);855 expect(sixth.response.status).toBe(429);856 expect(sixth.html).toContain("Too many");857 expect(Option.isNone(codeOf(sixth.response))).toBeTruthy();858 })859 );860861 it.live("refuses the sixth attempt in a minute from one address", () =>862 Effect.gen(function* () {863 const world = yield* signInWorld();864865 const statuses = yield* Effect.forEach(866 ["bob", "carol", "dave", "erin", "frank", "grace"],867 (handle) =>868 signIn(world, handle, alicePassword).pipe(869 Effect.map(({ status }) => status)870 )871 );872873 expect(statuses).toStrictEqual([401, 401, 401, 401, 401, 429]);874 })875 );876877 it.live(878 "replaces a password hash made with fewer iterations than today's",879 () =>880 Effect.gen(function* () {881 const world = yield* signInWorld();882883 const alice = Handle.make("alice");884885 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 );897898 const stored = yield* world.accounts.find(alice);899900 expect(901 Option.map(stored, ({ hash }) => hash.split("$")[1])902 ).toStrictEqual(Option.some("100000"));903 })904 );905});906907describe("OAuth sessions over the provider's tokens", () => {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* () {912 const world = yield* signInWorld();913914 yield* signUp(world, "alice", alicePassword);915916 const { access_token } = yield* accessTokenFor(917 world,918 "alice",919 alicePassword920 );921922 const sessions = OAuthSessions(tokenReader(world.store));923924 const changed = `${access_token.slice(0, -1)}${access_token.endsWith("A") ? "B" : "A"}`;925926 expect(yield* sessions.verify(access_token)).toStrictEqual(927 Option.some(Person.make({ handle: Handle.make("alice") }))928 );929 expect(yield* sessions.verify(changed)).toStrictEqual(Option.none());930931 yield* world.expireTokens;932933 expect(yield* sessions.verify(access_token)).toStrictEqual(934 Option.none()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});