Skip to content
Myr

google.test.ts

This file

Path

apps/platform/test/google.test.ts

1,322 lines · 38.0 KiB · TypeScript

Last changed by

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–18why, one step back
1import { NodeServices } from "@effect/platform-node";
2import { SqliteClient } from "@effect/sql-sqlite-node";3import { describe, expect, it } from "@effect/vitest";4import { Fetch } from "@repo/artifacts/fetch";5import { Handle } from "@repo/protocol/ids";6import { untouchable } from "@repo/testkit/untouchable";7import {8 Effect,9 Exit,10 FileSystem,11 Layer,12 Option,13 Redacted,14 Schema,15} from "effect";16import { SqlClient } from "effect/sql/SqlClient";1718import { IdentitiesD1 } from "../src/adapters/identities-d1.ts";

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 19why, one step back
19import { Email } from "../src/auth/accounts.ts";

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 20–23why, one step back
20import {
21 GOOGLE_DISCOVERY,22 googleAuthorizeUrl,23 GoogleKeysPerIsolate,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 24why, one step back
24 googlePerson,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 25–38why, one step back
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";29import { hashPassword } from "../src/auth/password.ts";30import { tokenReader } from "../src/auth/provider.ts";31import { SignInFailed } from "../src/auth/state.ts";32import { decodeEnv, InvalidEnv } from "../src/platform.ts";33import worker from "../src/worker.ts";34import { fakeEnv, passwordPepper } from "./fake-env.ts";35import {36 clientId,37 clientSecret,38 fakeGoogle,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 39why, one step back
39 googleEmailOf,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 40why, one step back
40 googleEnv,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 41why, one step back
41 googleNameOf,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 42–237why, one step back
42 googleWorld,
43 jwksUri,44} from "./google.fixtures.ts";45import type {46 Consent,47 FakeGoogle,48 GoogleWorld,49 Site,50} from "./google.fixtures.ts";51import {52 authorizeUrl,53 codeOf,54 formOf,55 origin,56 tokenRequest,57} from "./oauth.fixtures.ts";5859const alicePassword = "correct horse battery";6061describe("the Worker's env, for Google sign-in", () => {62 it.effect(63 "decodes Google's client id and its secret, redacted, as a pair",64 () =>65 Effect.gen(function* () {66 const config = yield* decodeEnv(googleEnv());6768 expect([69 config.GOOGLE_CLIENT_ID,70 Option.map(71 Option.fromUndefinedOr(config.GOOGLE_CLIENT_SECRET),72 Redacted.value73 ),74 ]).toStrictEqual([clientId, Option.some(clientSecret)]);75 })76 );7778 it.effect("leaves Google sign-in off when neither is set", () =>79 Effect.gen(function* () {80 const config = yield* decodeEnv(googleEnv([]));8182 expect([83 config.GOOGLE_CLIENT_ID,84 config.GOOGLE_CLIENT_SECRET,85 ]).toStrictEqual([undefined, undefined]);86 })87 );8889 it.effect(90 "is invalid with one of the pair and not the other, naming the missing one",91 () =>92 Effect.gen(function* () {93 const failures = yield* Effect.forEach(94 [["GOOGLE_CLIENT_ID"], ["GOOGLE_CLIENT_SECRET"]] as const,95 (keys) => Effect.flip(decodeEnv(googleEnv(keys)))96 );9798 expect(failures).toStrictEqual([99 new InvalidEnv({ keys: ["GOOGLE_CLIENT_SECRET"] }),100 new InvalidEnv({ keys: ["GOOGLE_CLIENT_ID"] }),101 ]);102 })103 );104});105106const alice = Handle.make("alice");107108const handleOf = (subject: string) =>109 Identities.use((identities) => identities.handleOf("google", subject));110111const describeIdentities = (112 adapter: string,113 layer: Layer.Layer<Identities>114) => {115 describe(`Identities over ${adapter}`, () => {116 it.effect("knows nobody by a subject no one linked", () =>117 Effect.gen(function* () {118 expect(yield* handleOf("1042")).toStrictEqual(Option.none());119 }).pipe(Effect.provide(layer))120 );121122 it.effect(123 "names the handle a subject was linked to, by its key (lowercased)",124 () =>125 Effect.gen(function* () {126 const identities = yield* Identities;127128 yield* identities.link("google", "1042", Handle.make("Alice"));129130 expect(yield* handleOf("1042")).toStrictEqual(Option.some(alice));131 expect(yield* handleOf("1043")).toStrictEqual(Option.none());132 }).pipe(Effect.provide(layer))133 );134135 it.effect(136 "links a subject to its own handle again, in any case, without change",137 () =>138 Effect.gen(function* () {139 const identities = yield* Identities;140141 yield* identities.link("google", "1042", alice);142 yield* identities.link("google", "1042", Handle.make("ALICE"));143144 expect(yield* handleOf("1042")).toStrictEqual(Option.some(alice));145 }).pipe(Effect.provide(layer))146 );147148 it.effect(149 "refuses to link a subject to a second handle, and keeps the first",150 () =>151 Effect.gen(function* () {152 const identities = yield* Identities;153154 yield* identities.link("google", "1042", alice);155156 const taken = yield* Effect.flip(157 identities.link("google", "1042", Handle.make("bob"))158 );159160 expect(taken).toStrictEqual(161 new IdentityTaken({ provider: "google", subject: "1042" })162 );163 expect(yield* handleOf("1042")).toStrictEqual(Option.some(alice));164 }).pipe(Effect.provide(layer))165 );166167 it.effect("lets one handle hold two subjects", () =>168 Effect.gen(function* () {169 const identities = yield* Identities;170171 yield* identities.link("google", "1042", alice);172 yield* identities.link("google", "2084", alice);173174 expect([175 yield* handleOf("1042"),176 yield* handleOf("2084"),177 ]).toStrictEqual([Option.some(alice), Option.some(alice)]);178 }).pipe(Effect.provide(layer))179 );180181 it.effect(182 "lets exactly one of two racing links to different handles have a subject",183 () =>184 Effect.gen(function* () {185 const identities = yield* Identities;186187 const exits = yield* Effect.all(188 [189 Effect.exit(identities.link("google", "1042", alice)),190 Effect.exit(191 identities.link("google", "1042", Handle.make("bob"))192 ),193 ],194 { concurrency: "unbounded" }195 );196197 expect(exits.filter(Exit.isSuccess)).toHaveLength(1);198 }).pipe(Effect.provide(layer))199 );200 });201};202203describeIdentities("memory", Layer.fresh(IdentitiesMemory.layer));204205const migrated = Layer.effectDiscard(206 Effect.gen(function* () {207 const fs = yield* FileSystem.FileSystem;208209 const sql = yield* SqlClient;210211 const ddl = yield* fs.readFileString(212 new URL("../migrations/0003_identities.sql", import.meta.url).pathname213 );214215 yield* sql.unsafe(ddl);216 })217).pipe(Layer.orDie, Layer.provide(NodeServices.layer));218219const database = migrated.pipe(220 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),221 Layer.orDie222);223224describeIdentities(225 "D1 (sqlite-node)",226 IdentitiesD1.pipe(Layer.provide(database))227);228229const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";230231const challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";232233const callbackUri = "https://platform.test/oauth/google/callback";234235const nonce = "nonce-0123456789abcdef";236237describe("Google's authorization request", () => {

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 238why, one step back
238 it("asks for a code with openid, email and profile, PKCE by S256, the state and the nonce", () => {

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 239–260why, one step back
239 const url = new URL(
240 googleAuthorizeUrl({241 clientId,242 codeChallenge: challenge,243 nonce,244 redirectUri: callbackUri,245 state: "sealed-state",246 })247 );248249 expect([250 `${url.origin}${url.pathname}`,251 Object.fromEntries(url.searchParams),252 ]).toStrictEqual([253 "https://accounts.google.com/o/oauth2/v2/auth",254 {255 client_id: "419-test.apps.googleusercontent.com",256 code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",257 code_challenge_method: "S256",258 nonce: "nonce-0123456789abcdef",259 redirect_uri: "https://platform.test/oauth/google/callback",260 response_type: "code",

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 261why, one step back
261 scope: "openid email profile",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 262–275why, one step back
262 state: "sealed-state",
263 },264 ]);265 });266});267268const authorizationRequest = new URL(269 `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({270 client_id: clientId,271 code_challenge: challenge,272 code_challenge_method: "S256",273 nonce,274 redirect_uri: callbackUri,275 response_type: "code",

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 276why, one step back
276 scope: "openid email profile",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 277–280why, one step back
277 state: "sealed-state",
278 }).toString()}`279).toString();280

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 281why, one step back
281const personOf = (

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 282–288why, one step back
282 google: FakeGoogle,
283 consent: Consent,284 kept: { readonly codeVerifier?: string; readonly nonce?: string } = {}285) =>286 Effect.gen(function* () {287 const back = yield* google.consent(authorizationRequest, consent);288

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 289why, one step back
289 return yield* googlePerson({

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 290–298why, one step back
290 clientId,
291 clientSecret: Redacted.make(clientSecret),292 code: back.searchParams.get("code") ?? "",293 codeVerifier: kept.codeVerifier ?? verifier,294 nonce: kept.nonce ?? nonce,295 redirectUri: callbackUri,296 });297 });298

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 299–304why, one step back
299const subjectOf = (
300 google: FakeGoogle,301 consent: Consent,302 kept: { readonly codeVerifier?: string; readonly nonce?: string } = {}303) => Effect.map(personOf(google, consent, kept), ({ subject }) => subject);304

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 305–320why, one step back
305const withGoogle = <A, E>(
306 body: (google: FakeGoogle) => Effect.Effect<A, E, Fetch | GoogleKeys>307) =>308 Effect.gen(function* () {309 const google = yield* fakeGoogle;310311 return yield* body(google).pipe(312 Effect.provide(313 GoogleKeysPerIsolate.pipe(314 Layer.provideMerge(Layer.succeed(Fetch, google.fetch))315 )316 )317 );318 });319320describe("the person Google confirms", () => {

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 321–361why, one step back
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 );361

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 362–621why, one step back
362 it.live("is the ID token's subject, once its signature and claims hold", () =>
363 withGoogle((google) =>364 Effect.gen(function* () {365 expect(yield* subjectOf(google, { sub: "1042" })).toBe("1042");366 })367 )368 );369370 it.live("may come from either spelling of Google's issuer", () =>371 withGoogle((google) =>372 Effect.gen(function* () {373 expect(374 yield* subjectOf(google, {375 claims: { iss: "accounts.google.com" },376 sub: "1042",377 })378 ).toBe("1042");379 })380 )381 );382383 it.live(384 "is nobody when the signature, issuer, audience, expiry or nonce is wrong, or the code's verifier is",385 () =>386 withGoogle((google) =>387 Effect.gen(function* () {388 const impostor = yield* google.keyPair("google-key-1");389390 const refusals = yield* Effect.forEach(391 [392 subjectOf(google, { signWith: impostor, sub: "1042" }),393 subjectOf(google, {394 claims: { iss: "https://accounts.example" },395 sub: "1042",396 }),397 subjectOf(google, {398 claims: { aud: "someone-else.apps.googleusercontent.com" },399 sub: "1042",400 }),401 subjectOf(google, {402 claims: { exp: 1_700_000_000 },403 sub: "1042",404 }),405 subjectOf(google, { sub: "1042" }, { nonce: "another-nonce" }),406 subjectOf(407 google,408 { sub: "1042" },409 {410 codeVerifier:411 "a-verifier-of-the-right-length-but-not-the-right-one",412 }413 ),414 ],415 (attempt) => Effect.flip(attempt)416 );417418 expect(419 refusals.map((refusal) => refusal instanceof SignInFailed)420 ).toStrictEqual([true, true, true, true, true, true]);421 })422 )423 );424425 it.live(426 "is nobody when the token names another party, or several audiences without naming this client its party",427 () =>428 withGoogle((google) =>429 Effect.gen(function* () {430 const audiences = [clientId, "another.apps.googleusercontent.com"];431432 const named = yield* subjectOf(google, {433 claims: { aud: audiences, azp: clientId },434 sub: "1042",435 });436437 const refusals = yield* Effect.forEach(438 [439 subjectOf(google, {440 claims: { aud: audiences, azp: undefined },441 sub: "1042",442 }),443 subjectOf(google, {444 claims: { azp: "another.apps.googleusercontent.com" },445 sub: "1042",446 }),447 ],448 (attempt) => Effect.flip(attempt)449 );450451 expect([452 named,453 ...refusals.map((refusal) => refusal instanceof SignInFailed),454 ]).toStrictEqual(["1042", true, true]);455 })456 )457 );458459 it.live(460 "is checked against keys fetched once per isolate, and fetched again once for a key not kept",461 () =>462 withGoogle((google) =>463 Effect.gen(function* () {464 yield* subjectOf(google, { sub: "1042" });465 yield* subjectOf(google, { sub: "2084" });466467 const once = yield* google.timesFetched(jwksUri);468469 const rotated = yield* google.rotate("google-key-2");470471 expect(472 yield* subjectOf(google, { signWith: rotated, sub: "1042" })473 ).toBe("1042");474475 const afterRotation = yield* google.timesFetched(jwksUri);476477 const unknown = yield* Effect.flip(478 subjectOf(google, { kid: "google-key-9", sub: "1042" })479 );480481 yield* subjectOf(google, { signWith: rotated, sub: "2084" });482483 expect([484 once,485 afterRotation,486 yield* google.timesFetched(jwksUri),487 yield* google.timesFetched(GOOGLE_DISCOVERY),488 unknown instanceof SignInFailed,489 ]).toStrictEqual([1, 2, 3, 1, true]);490 })491 )492 );493});494495interface Page {496 readonly html: string;497 readonly response: Response;498}499500const read = (response: Response) =>501 Effect.promise(() => response.text()).pipe(502 Effect.map((html): Page => ({ html, response }))503 );504505const visit = (world: GoogleWorld, path: Request | string, from?: Site) =>506 world.browser.send(507 path instanceof Request ? path : new Request(new URL(path, origin)),508 from509 );510511const openSignIn = (world: GoogleWorld) =>512 visit(world, new Request(authorizeUrl())).pipe(Effect.flatMap(read));513514const googleLinkIn = (page: Page) =>515 Option.fromNullishOr(516 /<a href="(?<href>\/oauth\/google\/start\?[^"]*)"/u.exec(page.html)?.groups517 ?.href518 ).pipe(Option.map((href) => href.replaceAll("&amp;", "&")));519520const continueWithGoogle = (world: GoogleWorld) =>521 Effect.gen(function* () {522 const page = yield* openSignIn(world);523524 const href = yield* Effect.fromOption(googleLinkIn(page)).pipe(525 Effect.orDie526 );527528 return yield* visit(world, href);529 });530531const locationOf = (response: Response) =>532 Option.fromNullishOr(response.headers.get("location")).pipe(533 Option.flatMap((location) => Option.fromNullishOr(URL.parse(location)))534 );535536const sendToWorker = (method: "GET" | "POST", path: string) =>537 Effect.promise(() =>538 Promise.resolve(539 worker.fetch(540 method === "POST"541 ? new Request(new URL(path, origin), {542 body: new URLSearchParams(),543 method: "POST",544 })545 : new Request(new URL(path, origin)),546 fakeEnv(),547 untouchable<ExecutionContext>("ExecutionContext")548 )549 )550 );551552describe("Google sign-in, without a Google OAuth client", () => {553 it.live("offers no Google button on the sign-in page", () =>554 Effect.gen(function* () {555 const world = yield* googleWorld({ google: false });556557 const page = yield* openSignIn(world);558559 expect(page.response.status).toBe(200);560 expect(Option.isSome(formOf(page.response, page.html))).toBeTruthy();561 expect(page.html).not.toContain("Google");562 expect(563 page.response.headers.get("content-security-policy")564 ).not.toContain("accounts.google.com");565 })566 );567568 it.live(569 "answers Google's paths with 404, in the Worker as worker.ts builds it",570 () =>571 Effect.gen(function* () {572 const world = yield* googleWorld({ google: false });573574 const form = yield* Effect.fromOption(575 Option.flatMap(Option.some(yield* openSignIn(world)), (page) =>576 formOf(page.response, page.html)577 )578 ).pipe(Effect.orDie);579580 const started = yield* visit(581 world,582 `/oauth/google/start?request=${encodeURIComponent(form.request)}`583 );584585 const statuses = yield* Effect.forEach(586 [587 ["GET", "/oauth/google/start?request=x"],588 ["GET", "/oauth/google/callback?code=x&state=y"],589 ["POST", "/oauth/google/link"],590 ["POST", "/oauth/google/handle"],591 ] as const,592 ([method, path]) =>593 Effect.map(sendToWorker(method, path), ({ status }) => status)594 );595596 expect([started.status, ...statuses]).toStrictEqual([597 404, 404, 404, 404, 404,598 ]);599 })600 );601});602603describe("Google sign-in, with a Google OAuth client", () => {604 it.live(605 'offers "Continue with Google" and "Sign in and link Google" on the sign-in page',606 () =>607 Effect.gen(function* () {608 const world = yield* googleWorld();609610 const page = yield* openSignIn(world);611612 expect(Option.isSome(googleLinkIn(page))).toBeTruthy();613 expect(page.html).toContain("Continue with Google");614 expect(page.html).toContain('formaction="/oauth/google/link"');615 expect(page.response.headers.get("content-security-policy")).toContain(616 "https://accounts.google.com"617 );618 })619 );620621 it.live(

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 622why, one step back
622 "sends the person to Google for a code, with openid, email and profile, PKCE by S256, a sealed state and a nonce",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 623–650why, one step back
623 () =>
624 Effect.gen(function* () {625 const world = yield* googleWorld();626627 const response = yield* continueWithGoogle(world);628629 const location = yield* Effect.fromOption(locationOf(response)).pipe(630 Effect.orDie631 );632633 const query = Object.fromEntries(location.searchParams);634635 expect([636 response.status,637 `${location.origin}${location.pathname}`,638 query.client_id,639 query.response_type,640 query.scope,641 query.code_challenge_method,642 query.code_challenge?.length,643 query.redirect_uri,644 (query.nonce ?? "").length >= 22,645 (query.state ?? "").length > 0,646 ]).toStrictEqual([647 302,648 "https://accounts.google.com/o/oauth2/v2/auth",649 clientId,650 "code",

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 651why, one step back
651 "openid email profile",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 652–716why, one step back
652 "S256",
653 43,654 `${origin}/oauth/google/callback`,655 true,656 true,657 ]);658 expect(659 Option.isSome(world.browser.cookie("__Host-google-sign-in"))660 ).toBeTruthy();661 })662 );663664 it.live(665 "refuses to start from a sign-in page this browser did not open",666 () =>667 Effect.gen(function* () {668 const world = yield* googleWorld();669670 const elsewhere = yield* googleWorld();671672 const href = yield* Effect.fromOption(673 googleLinkIn(yield* openSignIn(elsewhere))674 ).pipe(Effect.orDie);675676 const page = yield* visit(world, href).pipe(Effect.flatMap(read));677678 expect(page.response.status).toBe(400);679 expect(page.html).toContain("Start signing in again");680 expect(Option.isNone(locationOf(page.response))).toBeTruthy();681 })682 );683});684685const formPost = (path: string, fields: Readonly<Record<string, string>>) =>686 new Request(new URL(path, origin), {687 body: new URLSearchParams(fields),688 headers: {689 "cf-connecting-ip": "198.51.100.7",690 "content-type": "application/x-www-form-urlencoded",691 },692 method: "POST",693 });694695const formIn = (page: Page) =>696 Effect.fromOption(formOf(page.response, page.html, "kept")).pipe(697 Effect.orDie698 );699700const backFromGoogle = (701 world: GoogleWorld,702 response: Response,703 consent: Consent704) =>705 Effect.gen(function* () {706 const location = yield* Effect.fromOption(locationOf(response)).pipe(707 Effect.orDie708 );709710 const back = yield* world.google.consent(location.toString(), consent);711712 return yield* visit(world, back.toString(), "cross-site").pipe(713 Effect.flatMap(read)714 );715 });716

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 717–722why, one step back
717const chooseHandle = (
718 world: GoogleWorld,719 page: Page,720 handle: string,721 displayName = "Carol Example"722) =>

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 723–729why, one step back
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,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 730why, one step back
730 displayName,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 731–758why, one step back
731 handle,
732 request: form.request,733 })734 );735 });736737const AccessToken = Schema.fromJsonString(738 Schema.Struct({ access_token: Schema.String })739);740741const propsFor = (world: GoogleWorld, response: Response) =>742 Effect.gen(function* () {743 const code = yield* Effect.fromOption(codeOf(response)).pipe(Effect.orDie);744745 const answer = yield* visit(world, tokenRequest(code));746747 const { access_token } = yield* Effect.promise(() => answer.text()).pipe(748 Effect.flatMap(Schema.decodeEffect(AccessToken)),749 Effect.orDie750 );751752 const summary = yield* Effect.promise(() =>753 tokenReader(world.store).unwrapToken(access_token)754 );755756 return summary?.grant.props;757 });758

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 759why, one step back
759const isPickHandle = (page: Page) => page.html.includes("Set up your profile");

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 760–762why, one step back
760
761describe("coming back from Google", () => {762 it.live(

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 763why, one step back
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",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 764–773why, one step back
764 () =>
765 Effect.gen(function* () {766 const world = yield* googleWorld();767768 const page = yield* backFromGoogle(769 world,770 yield* continueWithGoogle(world),771 { sub: "1042" }772 );773

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 774–778why, one step back
774 expect([
775 page.response.status,776 isPickHandle(page),777 page.html.includes(`value="${googleNameOf("1042")}"`),778 ]).toStrictEqual([200, true, true]);

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 779–785why, one step back
779
780 const signedIn = yield* chooseHandle(world, page, "carol");781782 expect(signedIn.status).toBe(302);783 expect(yield* propsFor(world, signedIn)).toStrictEqual({784 handle: "carol",785 });

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 786–791why, one step back
786 expect(yield* world.accounts.find(Handle.make("carol"))).toMatchObject(
787 Option.some({788 displayName: "Carol Example",789 email: googleEmailOf("1042"),790 })791 );

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 792–844why, one step back
792 expect(
793 yield* world.identities.handleOf("google", "1042")794 ).toStrictEqual(Option.some(Handle.make("carol")));795 })796 );797798 it.live(799 "signs a known Google account straight in as its handle, with Google's keys fetched once",800 () =>801 Effect.gen(function* () {802 const world = yield* googleWorld();803804 const first = yield* backFromGoogle(805 world,806 yield* continueWithGoogle(world),807 { sub: "1042" }808 );809810 yield* chooseHandle(world, first, "Carol");811812 const again = yield* backFromGoogle(813 world,814 yield* continueWithGoogle(world),815 { sub: "1042" }816 );817818 expect(again.response.status).toBe(302);819 expect(yield* propsFor(world, again.response)).toStrictEqual({820 handle: "Carol",821 });822 expect(yield* world.google.timesFetched(jwksUri)).toBe(1);823 })824 );825826 it.live(827 "signs a double-clicked handle form in as the handle both times, not as taken",828 () =>829 Effect.gen(function* () {830 const world = yield* googleWorld();831832 const page = yield* backFromGoogle(833 world,834 yield* continueWithGoogle(world),835 { sub: "1042" }836 );837838 const form = yield* formIn(page);839840 const first = yield* chooseHandle(world, page, "carol");841842 const second = new Request(843 formPost("/oauth/google/handle", {844 csrf: form.csrf,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 845why, one step back
845 displayName: "Carol Example",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 846–904why, one step back
846 handle: "carol",
847 request: form.request,848 }),849 {850 headers: {851 "cf-connecting-ip": "198.51.100.7",852 "content-type": "application/x-www-form-urlencoded",853 cookie: `__Host-sign-in=${form.csrf}`,854 },855 }856 );857858 const again = yield* visit(world, second);859860 expect([first.status, again.status]).toStrictEqual([302, 302]);861 expect(yield* propsFor(world, again)).toStrictEqual({862 handle: "carol",863 });864 })865 );866867 it.live.each([868 { handle: "admin", reason: "reserved", status: 400 },869 { handle: "-carol", reason: "letters, digits and dashes", status: 400 },870 { handle: "OSCABRIEL", reason: "taken", status: 409 },871 ])(872 "refuses the handle $handle by sign-up's rules, and asks again",873 ({ handle, reason, status }) =>874 Effect.gen(function* () {875 const world = yield* googleWorld();876877 const page = yield* backFromGoogle(878 world,879 yield* continueWithGoogle(world),880 { sub: "1042" }881 );882883 const refused = yield* chooseHandle(world, page, handle).pipe(884 Effect.flatMap(read)885 );886887 expect([888 refused.response.status,889 isPickHandle(refused),890 refused.html.includes(reason),891 Option.isNone(codeOf(refused.response)),892 ]).toStrictEqual([status, true, true, true]);893 expect(894 yield* world.identities.handleOf("google", "1042")895 ).toStrictEqual(Option.none());896 })897 );898899 it.live(900 "says a handle an account holds is taken, and keeps that account's",901 () =>902 Effect.gen(function* () {903 const world = yield* googleWorld();904

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 905–907why, one step back
905 yield* world.accounts.create({
906 handle: Handle.make("carol"),907 hash: yield* hashPassword(

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 908–909why, one step back
908 Redacted.make(passwordPepper),
909 Redacted.make(alicePassword)

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 910–911why, one step back
910 ),
911 });

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 912–933why, one step back
912
913 const page = yield* backFromGoogle(914 world,915 yield* continueWithGoogle(world),916 { sub: "1042" }917 );918919 const refused = yield* chooseHandle(world, page, "CAROL").pipe(920 Effect.flatMap(read)921 );922923 expect([924 refused.response.status,925 refused.html.includes("taken"),926 ]).toStrictEqual([409, true]);927 expect(928 yield* world.identities.handleOf("google", "1042")929 ).toStrictEqual(Option.none());930 })931 );932});933

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 934–1054why, one step back
934const 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});1054

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1055–1184why, one step back
1055describe("Google not confirming anyone", () => {
1056 it.live.each([1057 ["a signature by another key", "impostor"],1058 ["another client's audience", "audience"],1059 ["an expired token", "expired"],1060 ["another sign-in's nonce", "nonce"],1061 ] as const)(1062 "refuses %s with the sign-in page and a plain message, and makes no account",1063 ([, wrong]) =>1064 Effect.gen(function* () {1065 const world = yield* googleWorld();10661067 const impostor = yield* world.google.keyPair("google-key-1");10681069 const consents = {1070 audience: { claims: { aud: "another.apps.googleusercontent.com" } },1071 expired: { claims: { exp: 1_700_000_000 } },1072 impostor: { signWith: impostor },1073 nonce: { claims: { nonce: "another-sign-in-s-nonce" } },1074 } as const;10751076 const page = yield* backFromGoogle(1077 world,1078 yield* continueWithGoogle(world),1079 { ...consents[wrong], sub: "1042" }1080 );10811082 expect([1083 page.response.status,1084 Option.isSome(formOf(page.response, page.html, "kept")),1085 page.html.includes("Google did not confirm who you are"),1086 isPickHandle(page),1087 Option.isNone(codeOf(page.response)),1088 ]).toStrictEqual([401, true, true, false, true]);1089 expect(1090 yield* world.identities.handleOf("google", "1042")1091 ).toStrictEqual(Option.none());1092 })1093 );10941095 it.live(1096 "shows the sign-in page again when the person declines at Google",1097 () =>1098 Effect.gen(function* () {1099 const world = yield* googleWorld();11001101 const location = yield* Effect.fromOption(1102 locationOf(yield* continueWithGoogle(world))1103 ).pipe(Effect.orDie);11041105 const page = yield* visit(1106 world,1107 `/oauth/google/callback?error=access_denied&state=${encodeURIComponent(location.searchParams.get("state") ?? "")}`,1108 "cross-site"1109 ).pipe(Effect.flatMap(read));11101111 expect([1112 page.response.status,1113 page.html.includes("Google did not confirm who you are"),1114 Option.isSome(formOf(page.response, page.html, "kept")),1115 ]).toStrictEqual([401, true, true]);1116 })1117 );11181119 it.live(1120 "refuses a state another platform sealed, a changed one, or one this browser did not start, and asks Google nothing",1121 () =>1122 Effect.gen(function* () {1123 const world = yield* googleWorld();11241125 const otherKey = yield* googleWorld({1126 cookieKey: "another-cookie-key-0123456789abcdef",1127 });11281129 const otherBrowser = yield* googleWorld();11301131 const own = yield* Effect.fromOption(1132 locationOf(yield* continueWithGoogle(world))1133 ).pipe(Effect.orDie);11341135 const foreign = yield* Effect.fromOption(1136 locationOf(yield* continueWithGoogle(otherKey))1137 ).pipe(Effect.orDie);11381139 const state = own.searchParams.get("state") ?? "";11401141 const changed = new URL(own);11421143 changed.searchParams.set(1144 "state",1145 `${state.startsWith("A") ? "B" : "A"}${state.slice(1)}`1146 );11471148 const attempts = [1149 { location: foreign, world },1150 { location: changed, world },1151 { location: own, world: otherBrowser },1152 ];11531154 for (const attempt of attempts) {1155 const back = yield* attempt.world.google.consent(1156 attempt.location.toString(),1157 { sub: "1042" }1158 );11591160 const page = yield* visit(1161 attempt.world,1162 back.toString(),1163 "cross-site"1164 ).pipe(Effect.flatMap(read));11651166 expect([1167 page.response.status,1168 page.html.includes("Start signing in again"),1169 Option.isNone(codeOf(page.response)),1170 ]).toStrictEqual([400, true, true]);1171 expect(yield* attempt.world.google.exchanges).toStrictEqual([]);1172 }1173 })1174 );1175});11761177const 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,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 1185why, one step back
1185 login: handle,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1186–1212why, one step back
1186 password,
1187 request: form.request,1188 })1189 );1190 });11911192describe("linking Google to an account signed in by password", () => {1193 it.live(1194 "stores the Google account's subject against the handle, then signs in as it, now and by Google later",1195 () =>1196 Effect.gen(function* () {1197 const world = yield* googleWorld();11981199 yield* withAlice(world);12001201 const toGoogle = yield* signInAndLink(world, "alice", alicePassword);12021203 expect(1204 Option.map(locationOf(toGoogle), (url) => url.origin)1205 ).toStrictEqual(Option.some("https://accounts.google.com"));12061207 const linked = yield* backFromGoogle(world, toGoogle, { sub: "5150" });12081209 expect(linked.response.status).toBe(302);1210 expect(yield* propsFor(world, linked.response)).toStrictEqual({1211 handle: "alice",1212 });

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

lines 1213–1222why, one step back
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 ]);

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1223–1249why, one step back
1223
1224 const later = yield* backFromGoogle(1225 world,1226 yield* continueWithGoogle(world),1227 { sub: "5150" }1228 );12291230 expect(yield* propsFor(world, later.response)).toStrictEqual({1231 handle: "alice",1232 });1233 })1234 );12351236 it.live("goes nowhere near Google with the wrong password", () =>1237 Effect.gen(function* () {1238 const world = yield* googleWorld();12391240 yield* withAlice(world);12411242 const page = yield* signInAndLink(1243 world,1244 "alice",1245 "not the password"1246 ).pipe(Effect.flatMap(read));12471248 expect([1249 page.response.status,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 1250why, one step back
1250 page.html.includes("The email, handle or password is wrong."),

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1251–1302why, one step back
1251 Option.isNone(locationOf(page.response)),
1252 ]).toStrictEqual([401, true, true]);1253 })1254 );12551256 it.live("refuses a Google account already linked to another handle", () =>1257 Effect.gen(function* () {1258 const world = yield* googleWorld();12591260 yield* withAlice(world);1261 yield* world.identities.link("google", "5150", Handle.make("bob"));12621263 const page = yield* backFromGoogle(1264 world,1265 yield* signInAndLink(world, "alice", alicePassword),1266 { sub: "5150" }1267 );12681269 expect([1270 page.response.status,1271 page.html.includes("linked to another handle"),1272 Option.isNone(codeOf(page.response)),1273 ]).toStrictEqual([409, true, true]);1274 expect(yield* world.identities.handleOf("google", "5150")).toStrictEqual(1275 Option.some(Handle.make("bob"))1276 );1277 })1278 );1279});12801281describe("a sealed form, opened only where it was made", () => {1282 it.live(1283 "refuses a pick-a-handle form's seal as a password sign-in, or to start Google's",1284 () =>1285 Effect.gen(function* () {1286 const world = yield* googleWorld();12871288 yield* withAlice(world);12891290 const page = yield* backFromGoogle(1291 world,1292 yield* continueWithGoogle(world),1293 { sub: "1042" }1294 );12951296 const form = yield* formIn(page);12971298 const answers = yield* Effect.forEach(1299 [1300 `/oauth/google/start?request=${encodeURIComponent(form.request)}`,1301 formPost("/authorize", {1302 csrf: form.csrf,

Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c

line 1303why, one step back
1303 login: "alice",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1304–1322why, one step back
1304 password: alicePassword,
1305 request: form.request,1306 }),1307 ],1308 (request) => visit(world, request).pipe(Effect.flatMap(read))1309 );13101311 expect(1312 answers.map(({ html, response }) => [1313 response.status,1314 html.includes("Start signing in again"),1315 ])1316 ).toStrictEqual([1317 [400, true],1318 [400, true],1319 ]);1320 })1321 );1322});