google.ts
This file
Path
apps/platform/src/auth/google.ts
860 lines · 23.1 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
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 1–3why, one step back1// 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.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 4–20why, one step back4import { Fetch } from "@repo/artifacts/fetch";5import { Handle } from "@repo/protocol/ids";6import {7 Array,8 Clock,9 Context,10 Effect,11 Layer,12 Option,13 Predicate,14 Redacted,15 Ref,16 Result,17 Schema,18} from "effect";19import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";20Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 21–22why, one step back21import { Accounts, Email } from "./accounts.ts";22import type { Account } from "./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 23–24why, one step back23import { SignInAttempts } from "./attempts.ts";24import { Identities } from "./identities.ts";Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 25why, one step back25import { Mailer } from "./mailer.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
line 26why, one step back26import { OAuthStore } from "./oauth-store.ts";Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 27–28why, one step back27import { GOOGLE_PATHS, profilePage } from "./pages.ts";28import type { ProfileValues } from "./pages.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 29–30why, one step back29import { hashPassword } from "./password.ts";30import {Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 31why, one step back31 addEmailPageFor,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 32–36why, one step back32 addressOf,33 askerOf,34 Authorization,35 authorizeHref,36 byPassword,Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 37why, one step back37 chosenDisplayName,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 38–78why, one step back38 chosenHandle,39 completed,40 CSRF_COOKIE,41 csrfCookie,42 failedPage,43 freshCsrf,44 HeldHandles,45 htmlPage,46 Says,47 SignInKeys,48 SignInOffers,49 signInPageFor,50} from "./sign-in.ts";51import type { SignInServices } from "./sign-in.ts";52import {53 AuthRequest,54 openState,55 sealing,56 SIGN_IN_LIFETIME,57 SignInFailed,58 startAgain,59} from "./state.ts";6061export const GOOGLE_ACCOUNTS = "https://accounts.google.com";6263export const GOOGLE_DISCOVERY = `${GOOGLE_ACCOUNTS}/.well-known/openid-configuration`;6465const AUTHORIZE_ENDPOINT = `${GOOGLE_ACCOUNTS}/o/oauth2/v2/auth`;6667const ISSUERS: ReadonlySet<string> = new Set([68 GOOGLE_ACCOUNTS,69 "accounts.google.com",70]);7172export const GoogleSubject = Schema.String.check(73 Schema.isNonEmpty(),74 Schema.isMaxLength(255)75).pipe(Schema.brand("GoogleSubject"));7677export type GoogleSubject = typeof GoogleSubject.Type;78Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 79why, one step back79// Said the same way whatever the cause.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 80–100why, one step back80const unconfirmed = new SignInFailed({81 reason:82 "Google did not confirm who you are. Try again, or sign in with your password.",83});8485export const googleAuthorizeUrl = (input: {86 readonly clientId: string;87 readonly codeChallenge: string;88 readonly nonce: string;89 readonly redirectUri: string;90 readonly state: string;91}) => {92 const url = new URL(AUTHORIZE_ENDPOINT);9394 url.search = new URLSearchParams({95 client_id: input.clientId,96 code_challenge: input.codeChallenge,97 code_challenge_method: "S256",98 nonce: input.nonce,99 redirect_uri: input.redirectUri,100 response_type: "code",Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 101why, one step back101 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 102–137why, one step back102 state: input.state,103 }).toString();104105 return url.toString();106};107108const Discovery = Schema.Struct({109 jwks_uri: Schema.String,110 token_endpoint: Schema.String,111});112113type Discovery = typeof Discovery.Type;114115const SigningKey = Schema.Struct({116 alg: Schema.optionalKey(Schema.Literal("RS256")),117 e: Schema.String,118 kid: Schema.String,119 kty: Schema.Literal("RSA"),120 n: Schema.String,121 use: Schema.optionalKey(Schema.Literal("sig")),122});123124const decodeSigningKey = Schema.decodeUnknownOption(SigningKey);125126const KeySet = Schema.Struct({ keys: Schema.Array(Schema.Unknown) });127128const TokenResponse = Schema.Struct({ id_token: Schema.String });129130const Header = Schema.Struct({131 alg: Schema.Literal("RS256"),132 kid: Schema.String,133});134135const Claims = Schema.Struct({136 aud: Schema.Union([Schema.String, Schema.Array(Schema.String)]),137 azp: Schema.optionalKey(Schema.String),Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 138–139why, one step back138 email: Schema.optionalKey(Schema.String),139 email_verified: Schema.optionalKey(Schema.Boolean),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 140–141why, one step back140 exp: Schema.Finite,141 iss: Schema.String,Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 142why, one step back142 name: Schema.optionalKey(Schema.String),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 143–146why, one step back143 nonce: Schema.optionalKey(Schema.String),144 sub: GoogleSubject,145});146Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 147–164why, one step back147export 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});164Merge 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 165–219why, one step back165const segment = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>166 Schema.decodeEffect(167 Schema.StringFromBase64Url.pipe(168 Schema.decodeTo(Schema.fromJsonString(schema))169 )170 );171172const decodeHeader = segment(Header);173174const decodeClaims = segment(Claims);175176const decodeSignature = Schema.decodeEffect(Schema.Uint8ArrayFromBase64Url);177178const RSA = { hash: "SHA-256", name: "RSASSA-PKCS1-v1_5" } as const;179180const utf8 = (text: string) => new TextEncoder().encode(text);181182const answerOf = <A>(183 fetch: Fetch["Service"],184 schema: Schema.Codec<A, unknown>,185 request: Request186) =>187 Effect.gen(function* () {188 const response = yield* fetch189 .fetch(request)190 .pipe(Effect.mapError(() => unconfirmed));191192 const text = yield* Effect.tryPromise({193 catch: () => unconfirmed,194 try: () => response.text(),195 });196197 if (!response.ok) {198 return yield* unconfirmed;199 }200201 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(text).pipe(202 Effect.mapError(() => unconfirmed)203 );204 });205206const imported = (key: typeof SigningKey.Type) =>207 Effect.tryPromise(() =>208 crypto.subtle.importKey(209 "jwk",210 { alg: "RS256", e: key.e, ext: true, kty: "RSA", n: key.n },211 RSA,212 false,213 ["verify"]214 )215 ).pipe(216 Effect.map((verifier) => Option.some([key.kid, verifier] as const)),217 Effect.orElseSucceed(() => Option.none())218 );219Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 220why, one step back220// Keys are read again when an ID token names one not kept (Google rotates them); only a success is kept.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 221–304why, one step back221export class GoogleKeys extends Context.Service<222 GoogleKeys,223 {224 readonly discovery: Effect.Effect<Discovery, SignInFailed>;225 readonly key: (kid: string) => Effect.Effect<CryptoKey, SignInFailed>;226 }227>()("platform/GoogleKeys") {}228229export const GoogleKeysPerIsolate = Layer.effect(230 GoogleKeys,231 Effect.gen(function* () {232 const fetch = yield* Fetch;233234 const kept = yield* Ref.make(Option.none<Discovery>());235236 const keys = yield* Ref.make<ReadonlyMap<string, CryptoKey>>(new Map());237238 const discovery = Effect.gen(function* () {239 const known = yield* Ref.get(kept);240241 if (Option.isSome(known)) {242 return known.value;243 }244245 const read = yield* answerOf(246 fetch,247 Discovery,248 new Request(GOOGLE_DISCOVERY)249 );250251 yield* Ref.set(kept, Option.some(read));252253 return read;254 });255256 const fetchKeys = Effect.gen(function* () {257 const { jwks_uri } = yield* discovery;258259 const set = yield* answerOf(fetch, KeySet, new Request(jwks_uri));260261 const fresh = new Map(262 Array.getSomes(263 yield* Effect.forEach(264 Array.getSomes(set.keys.map((key) => decodeSigningKey(key))),265 imported266 )267 )268 );269270 yield* Ref.set(keys, fresh);271272 return fresh;273 });274275 return GoogleKeys.of({276 discovery,277 key: (kid) =>278 Effect.gen(function* () {279 const known = (yield* Ref.get(keys)).get(kid);280281 if (known !== undefined) {282 return known;283 }284285 const fresh = yield* fetchKeys;286287 return yield* Effect.fromNullishOr(fresh.get(kid)).pipe(288 Effect.mapError(() => unconfirmed)289 );290 }),291 });292 })293);294295const issuedTo = (claims: typeof Claims.Type, clientId: string) => {296 const audience = Predicate.isString(claims.aud) ? [claims.aud] : claims.aud;297298 return (299 audience.includes(clientId) &&300 (claims.azp ?? clientId) === clientId &&301 (audience.length === 1 || claims.azp === clientId)302 );303};304Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 305why, one step back305const verifiedPerson = (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 306–353why, one step back306 token: string,307 expected: { readonly clientId: string; readonly nonce: string }308) =>309 Effect.gen(function* () {310 const keys = yield* GoogleKeys;311312 const [header = "", claims = "", signature = "", ...rest] =313 token.split(".");314315 if (rest.length > 0) {316 return yield* unconfirmed;317 }318319 const { kid } = yield* decodeHeader(header).pipe(320 Effect.mapError(() => unconfirmed)321 );322323 const key = yield* keys.key(kid);324325 const signed = yield* decodeSignature(signature).pipe(326 Effect.mapError(() => unconfirmed)327 );328329 const genuine = yield* Effect.promise(() =>330 crypto.subtle.verify(331 RSA,332 key,333 new Uint8Array(signed),334 utf8(`${header}.${claims}`)335 )336 );337338 if (!genuine) {339 return yield* unconfirmed;340 }341342 const said = yield* decodeClaims(claims).pipe(343 Effect.mapError(() => unconfirmed)344 );345346 const now = yield* Clock.currentTimeMillis;347348 const holds =349 ISSUERS.has(said.iss) &&350 issuedTo(said, expected.clientId) &&351 said.exp * 1000 > now &&352 said.nonce === expected.nonce;353Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 354why, one step back354 return holds ? personOf(said) : yield* unconfirmed;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 355–356why, one step back355 });356Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 357why, one step back357// Google's other tokens in the answer are never read, and nothing of it is kept.Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 358why, one step back358export const googlePerson = (input: {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 359–364why, one step back359 readonly clientId: string;360 readonly clientSecret: Redacted.Redacted;361 readonly code: string;362 readonly codeVerifier: string;363 readonly nonce: string;364 readonly redirectUri: string;Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 365why, one step back365}): Effect.Effect<GooglePerson, SignInFailed, Fetch | GoogleKeys> =>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 366–392why, one step back366 Effect.gen(function* () {367 const keys = yield* GoogleKeys;368369 const fetch = yield* Fetch;370371 const { token_endpoint } = yield* keys.discovery;372373 const { id_token } = yield* answerOf(374 fetch,375 TokenResponse,376 new Request(token_endpoint, {377 body: new URLSearchParams({378 client_id: input.clientId,379 client_secret: Redacted.value(input.clientSecret),380 code: input.code,381 code_verifier: input.codeVerifier,382 grant_type: "authorization_code",383 redirect_uri: input.redirectUri,384 }),385 headers: {386 accept: "application/json",387 "content-type": "application/x-www-form-urlencoded",388 },389 method: "POST",390 })391 );392Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 393why, one step back393 return yield* verifiedPerson(id_token, input);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 394–408why, one step back394 });395396interface Client {397 readonly id: string;398 readonly secret: Redacted.Redacted;399}400401export class GoogleClient extends Context.Service<402 GoogleClient,403 { readonly client: Option.Option<Client> }404>()("platform/GoogleClient") {}405406const GoogleSays = {407 linkedElsewhere:408 "That Google account is linked to another handle. Sign in with that handle, or use another Google account.",Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 409–410why, one step back409 noEmail:410 "Google did not share a verified email for that account. Sign up with an email and password instead.",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 411–412why, one step back411} as const;412Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 413why, one step back413// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.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 414–431why, one step back414const GOOGLE_COOKIE = "__Host-google-sign-in";415416const googleCookie = {417 httpOnly: true,418 path: "/",419 sameSite: "lax",420 secure: true,421} as const;422423const legDone = (response: HttpServerResponse.HttpServerResponse) =>424 response.pipe(425 HttpServerResponse.setCookie(GOOGLE_COOKIE, "", {426 ...googleCookie,427 maxAge: 0,428 }),429 Effect.orDie430 );431Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 432why, one step back432// Carries the challenge of the verifier in this browser's cookie, so only this browser finishes the leg.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 433–443why, one step back433const GoogleLeg = Schema.Struct({434 challenge: Schema.String,435 link: Schema.optionalKey(Handle),436 nonce: Schema.String,437 request: AuthRequest,438});439440const legs = sealing("google-leg", GoogleLeg);441442const PendingHandle = Schema.Struct({443 csrf: Schema.String,Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 444–445why, one step back444 email: Email,445 name: Schema.optionalKey(Schema.String),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 446–449why, one step back446 request: AuthRequest,447 subject: GoogleSubject,448});449Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 450–451why, one step back450type PendingHandle = typeof PendingHandle.Type;451Merge 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 452–537why, one step back452const pendingHandles = sealing("google-handle", PendingHandle);453454const encodeBytes = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);455456const freshSecret = Effect.sync(() =>457 crypto.getRandomValues(new Uint8Array(32))458).pipe(Effect.flatMap(encodeBytes), Effect.orDie);459460const challengeOf = (verifier: string) =>461 Effect.promise(() => crypto.subtle.digest("SHA-256", utf8(verifier))).pipe(462 Effect.flatMap((digest) => encodeBytes(new Uint8Array(digest))),463 Effect.orDie464 );465466const callbackUri = (origin: string) => `${origin}${GOOGLE_PATHS.callback}`;467468const toGoogle = (469 client: Client,470 request: AuthRequest,471 link: Option.Option<Handle>472) =>473 Effect.gen(function* () {474 const { cookieKey } = yield* SignInKeys;475476 const { origin } = yield* Authorization;477478 const verifier = yield* freshSecret;479480 const nonce = yield* freshSecret;481482 const challenge = yield* challengeOf(verifier);483484 const leg = { challenge, nonce, request };485486 const state = yield* legs.seal(487 cookieKey,488 Option.match(link, {489 onNone: () => leg,490 onSome: (handle) => ({ ...leg, link: handle }),491 })492 );493494 return yield* HttpServerResponse.redirect(495 googleAuthorizeUrl({496 clientId: client.id,497 codeChallenge: challenge,498 nonce,499 redirectUri: callbackUri(origin),500 state,501 }),502 {503 headers: {504 "cache-control": "no-store",505 "referrer-policy": "no-referrer",506 },507 status: 302,508 }509 ).pipe(510 HttpServerResponse.setCookie(GOOGLE_COOKIE, verifier, {511 ...googleCookie,512 maxAge: SIGN_IN_LIFETIME,513 }),514 Effect.orDie515 );516 });517518const start =519 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>520 Effect.gen(function* () {521 const { cookieKey } = yield* SignInKeys;522523 const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(524 Schema.Struct({ request: Schema.String })525 ).pipe(Effect.mapError(() => startAgain));526527 const pending = yield* openState(cookieKey, sealed);528529 if (request.cookies[CSRF_COOKIE] !== pending.csrf) {530 return yield* startAgain;531 }532533 return yield* toGoogle(client, pending.request, Option.none());534 });535536const link =537 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 538–539why, one step back538 byPassword(request, (account, pending) =>539 toGoogle(client, pending.request, Option.some(account.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 540–542why, one step back540 );541542const pickHandle = (Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 543–544why, one step back543 pending: Omit<PendingHandle, "csrf">,544 values: ProfileValues,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 545–552why, one step back545 status: number,546 message?: string547) =>548 Effect.gen(function* () {549 const { cookieKey } = yield* SignInKeys;550551 const csrf = yield* freshCsrf;552Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 553why, one step back553 const sealed = yield* pendingHandles.seal(cookieKey, { ...pending, csrf });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 554why, one step back554Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 555why, one step back555 const asker = yield* askerOf(pending.request);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 556–557why, one step back556557 return yield* htmlPage(Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 558why, one step back558 profilePage(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 559–560why, one step back559 asker,560 { csrf, request: sealed },Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 561–562why, one step back561 authorizeHref(pending.request),562 values,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 563–565why, one step back563 message564 ),565 status,Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 566why, one step back566 pending.request.redirectUriMerge 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 567–575why, one step back567 ).pipe(568 HttpServerResponse.setCookie(CSRF_COOKIE, csrf, {569 ...csrfCookie,570 maxAge: SIGN_IN_LIFETIME,571 }),572 Effect.orDie573 );574 });575Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 576–583why, one step back576// 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) =>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 584why, one step back584 Effect.gen(function* () {Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 585–606why, one step back585 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* () {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 607–610why, one step back607 const identities = yield* Identities;608609 const accounts = yield* Accounts;610Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 611–616why, one step back611 const linked = yield* identities612 .link("google", person.subject, handle)613 .pipe(614 Effect.as(true),615 Effect.catchTag("IdentityTaken", () => Effect.succeed(false))616 );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 617why, one step back617Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 618–619why, one step back618 if (!linked) {619 return yield* signInPageFor(request, 409, GoogleSays.linkedElsewhere);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 620–621why, one step back620 }621Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 622why, one step back622 const account = yield* accounts.find(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 623–625why, one step back623624 return yield* Option.match(account, {625 onNone: () => signInPageFor(request, 401, unconfirmed.reason),Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 626why, one step back626 onSome: (found) => completedWithEmail(found, person, request),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 627–629why, one step back627 });628 });629Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 630why, one step back630const signedInAs = (person: GooglePerson, request: AuthRequest) =>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 631–633why, one step back631 Effect.gen(function* () {632 const identities = yield* Identities;633Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 634why, one step back634 const accounts = yield* Accounts;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 635why, one step back635Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 636–673why, one step back636 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 );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 674–705why, one step back674 });675676const CallbackQuery = Schema.Struct({677 code: Schema.optionalKey(Schema.String),678 state: Schema.String,679});680681const cameBack =682 (client: Client) => (request: HttpServerRequest.HttpServerRequest) =>683 Effect.gen(function* () {684 const { cookieKey } = yield* SignInKeys;685686 const { origin } = yield* Authorization;687688 const query = yield* HttpServerRequest.schemaSearchParams(689 CallbackQuery690 ).pipe(Effect.mapError(() => startAgain));691692 const leg = yield* legs.open(cookieKey, query.state);693694 const verifier = request.cookies[GOOGLE_COOKIE] ?? "";695696 if ((yield* challengeOf(verifier)) !== leg.challenge) {697 return yield* startAgain;698 }699700 const confirmed = yield* Option.match(701 Option.fromUndefinedOr(query.code),702 {703 // Google sends `error` and no code when the person declines.704 onNone: () => Effect.fail(unconfirmed),705 onSome: (code) =>Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 706why, one step back706 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 707–732why, one step back707 clientId: client.id,708 clientSecret: client.secret,709 code,710 codeVerifier: verifier,711 nonce: leg.nonce,712 redirectUri: callbackUri(origin),713 }),714 }715 ).pipe(Effect.result);716717 if (Result.isFailure(confirmed)) {718 return yield* signInPageFor(719 leg.request,720 401,721 confirmed.failure.reason722 ).pipe(Effect.flatMap(legDone));723 }724725 const answered = yield* Option.match(Option.fromUndefinedOr(leg.link), {726 onNone: () => signedInAs(confirmed.success, leg.request),727 onSome: (handle) => linkedTo(confirmed.success, handle, leg.request),728 });729730 return yield* legDone(answered);731 });732Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 733why, one step back733const PostedProfile = Schema.Struct({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 734why, one step back734 csrf: Schema.String,Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 735why, one step back735 displayName: Schema.String,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 736–739why, one step back736 handle: Schema.String,737 request: Schema.String,738});739Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 740–741why, one step back740// The account's password is one nobody is told: Google signs it in, and a741// reset by its email sets a real one.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 742–754why, one step back742const handleChosen = (request: HttpServerRequest.HttpServerRequest) =>743 Effect.gen(function* () {744 const { cookieKey, pepper } = yield* SignInKeys;745746 const accounts = yield* Accounts;747748 const identities = yield* Identities;749750 const attempts = yield* SignInAttempts;751752 const { handles: held } = yield* HeldHandles;753754 const form = yield* HttpServerRequest.schemaBodyUrlParams(Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 755why, one step back755 PostedProfileMerge 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 756–766why, one step back756 ).pipe(Effect.mapError(() => startAgain));757758 const pending = yield* pendingHandles.open(cookieKey, form.request);759760 if (761 pending.csrf !== form.csrf ||762 request.cookies[CSRF_COOKIE] !== form.csrf763 ) {764 return yield* startAgain;765 }766Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 767–778why, one step back767 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 messageMerge 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 779why, one step back779 );Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 780–782why, one step back780781 if (!(yield* attempts.admit(`sign-up:${addressOf(request)}`))) {782 return yield* again(429, Says.tooManySignUps);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 783–785why, one step back783 }784785 if (Option.isSome(yield* identities.handleOf("google", pending.subject))) {Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 786why, one step back786 return yield* signedInAs(person, pending.request);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 787–788why, one step back787 }788Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 789–792why, one step back789 const checked = Result.all({790 displayName: chosenDisplayName(form.displayName),791 handle: chosenHandle(form.handle, held),792 });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 793–794why, one step back793794 if (Result.isFailure(checked)) {Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 795why, one step back795 return yield* again(checked.failure.status, checked.failure.message);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 796–799why, one step back796 }797798 const hash = yield* hashPassword(pepper, Redacted.make(yield* freshSecret));799Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
lines 800–815why, one step back800 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 })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 816–833why, one step back816 );817 });818819export type GoogleServices = Fetch | GoogleClient | Identities | SignInServices;820821export const googleRoutes = HttpRouter.use((router) =>822 Effect.gen(function* () {823 const { client } = yield* GoogleClient;824825 if (Option.isNone(client)) {826 return;827 }828829 const services = Context.make(Accounts, yield* Accounts).pipe(830 Context.add(Fetch, yield* Fetch),831 Context.add(GoogleKeys, yield* GoogleKeys),832 Context.add(HeldHandles, yield* HeldHandles),833 Context.add(Identities, yield* Identities),Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 834why, one step back834 Context.add(Mailer, yield* Mailer),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 835–860why, one step back835 Context.add(OAuthStore, yield* OAuthStore),836 Context.add(SignInAttempts, yield* SignInAttempts),837 Context.add(SignInKeys, yield* SignInKeys),838 Context.add(SignInOffers, yield* SignInOffers)839 );840841 const add = <R>(842 method: "GET" | "POST",843 path: HttpRouter.PathInput,844 handler: (845 request: HttpServerRequest.HttpServerRequest846 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, SignInFailed, R>847 ) =>848 router.add(method, path, (request) =>849 handler(request).pipe(850 Effect.catchTag("SignInFailed", failedPage),851 Effect.provide(services)852 )853 );854855 yield* add("GET", GOOGLE_PATHS.start, start(client.value));856 yield* add("POST", GOOGLE_PATHS.link, link(client.value));857 yield* add("GET", GOOGLE_PATHS.callback, cameBack(client.value));858 yield* add("POST", GOOGLE_PATHS.handle, handleChosen);859 })860).pipe(Layer.provide(GoogleKeysPerIsolate));