Skip to content
Myr

google.fixtures.ts

This file

Path

apps/platform/test/google.fixtures.ts

462 lines · 12.9 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

1import { Fetch } from "@repo/artifacts/fetch";2import { untouchable } from "@repo/testkit/untouchable";3import { Clock, Effect, Layer, Option, Ref, Schema } from "effect";4import { vi } from "vitest";56import { Accounts } from "../src/auth/accounts.ts";7import { AccountsMemory } from "../src/auth/accounts/memory.ts";8import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";9import { GOOGLE_DISCOVERY } from "../src/auth/google.ts";10import { Identities } from "../src/auth/identities.ts";11import { IdentitiesMemory } from "../src/auth/identities/memory.ts";12import { MailerMemory } from "../src/auth/mailer/memory.ts";13import { OAuthStore } from "../src/auth/oauth-store.ts";14import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";15import { oauthProvider, signInSettings } from "../src/auth/provider.ts";16import { decodeEnv } from "../src/platform.ts";17import { fakeEnv } from "./fake-env.ts";1819export const clientId = "419-test.apps.googleusercontent.com";2021export const clientSecret = "GOCSPX-a-test-client-secret";2223export const tokenEndpoint = "https://oauth2.googleapis.com/token";2425export const jwksUri = "https://www.googleapis.com/oauth2/v3/certs";2627export type GoogleKey = "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET";2829export type GoogleEnv = Env & Readonly<Partial<Record<GoogleKey, string>>>;3031export const googleEnv = (32  keys: readonly GoogleKey[] = ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"]33): GoogleEnv => {34  const halves = {35    GOOGLE_CLIENT_ID: clientId,36    GOOGLE_CLIENT_SECRET: clientSecret,37  } as const;3839  return {40    ...fakeEnv(),41    ...Object.fromEntries(keys.map((key) => [key, halves[key]])),42  };43};4445const utf8 = (text: string) => new TextEncoder().encode(text);4647const base64Url = Schema.encodeSync(Schema.Uint8ArrayFromBase64Url);4849const rsa = { hash: "SHA-256", name: "RSASSA-PKCS1-v1_5" } as const;5051const isKeyPair = (key: CryptoKey | CryptoKeyPair): key is CryptoKeyPair =>52  "privateKey" in key;5354const isJwk = (key: ArrayBuffer | JsonWebKey): key is JsonWebKey =>55  !(key instanceof ArrayBuffer);5657const keyPair = (kid: string) =>58  Effect.gen(function* () {59    const pair = yield* Effect.promise(() =>60      crypto.subtle.generateKey(61        {62          ...rsa,63          modulusLength: 2048,64          publicExponent: new Uint8Array([1, 0, 1]),65        },66        true,67        ["sign", "verify"]68      )69    ).pipe(Effect.filterOrFail(isKeyPair), Effect.orDie);7071    const jwk = yield* Effect.promise(() =>72      crypto.subtle.exportKey("jwk", pair.publicKey)73    ).pipe(Effect.filterOrFail(isJwk), Effect.orDie);7475    return {76      kid,77      privateKey: pair.privateKey,78      publicJwk: {79        alg: "RS256",80        e: jwk.e,81        kid,82        kty: "RSA",83        n: jwk.n,84        use: "sig",85      },86    };87  });8889export type KeyPair = Effect.Success<ReturnType<typeof keyPair>>;9091export interface Claims {92  readonly aud?: string | readonly string[];93  readonly azp?: string | undefined;94  readonly email?: string | undefined;95  readonly email_verified?: boolean | undefined;96  readonly exp?: number;97  readonly iss?: string;98  readonly name?: string | undefined;99  readonly nonce?: string;100}101102// What Google says of a subject unless a consent says otherwise: a verified103// address and a name, as `openid email profile` gets for a Gmail account.104export const googleEmailOf = (sub: string) => `person-${sub}@mail.example`;105106export const googleNameOf = (sub: string) => `Person ${sub}`;107108export interface Consent {109  readonly claims?: Claims;110  readonly kid?: string;111  readonly signWith?: KeyPair;112  readonly sub: string;113}114115const AuthorizationRequest = Schema.Struct({116  client_id: Schema.String,117  code_challenge: Schema.String,118  code_challenge_method: Schema.Literal("S256"),119  nonce: Schema.String,120  redirect_uri: Schema.String,121  response_type: Schema.Literal("code"),122  scope: Schema.Literal("openid email profile"),123  state: Schema.String,124});125126const decodeAuthorizationRequest =127  Schema.decodeUnknownSync(AuthorizationRequest);128129const CodeExchange = Schema.Struct({130  client_id: Schema.String,131  client_secret: Schema.String,132  code: Schema.String,133  code_verifier: Schema.String,134  grant_type: Schema.Literal("authorization_code"),135  redirect_uri: Schema.String,136});137138const decodeCodeExchange = Schema.decodeUnknownOption(CodeExchange);139140interface Grant {141  readonly consent: Consent;142  readonly request: typeof AuthorizationRequest.Type;143}144145const s256 = (verifier: string) =>146  Effect.promise(() => crypto.subtle.digest("SHA-256", utf8(verifier))).pipe(147    Effect.map((digest) => base64Url(new Uint8Array(digest)))148  );149150export const fakeGoogle = Effect.gen(function* () {151  const signing = yield* keyPair("google-key-1");152153  const published = yield* Ref.make<readonly KeyPair[]>([signing]);154155  const grants = yield* Ref.make(new Map<string, Grant>());156157  const fetched = yield* Ref.make<readonly string[]>([]);158159  const exchanges = yield* Ref.make<readonly string[]>([]);160161  const idToken = (grant: Grant) =>162    Effect.gen(function* () {163      const now = Math.floor((yield* Clock.currentTimeMillis) / 1000);164165      const { consent } = grant;166167      const key = consent.signWith ?? signing;168169      const header = base64Url(170        utf8(171          JSON.stringify({172            alg: "RS256",173            kid: consent.kid ?? key.kid,174            typ: "JWT",175          })176        )177      );178179      const claims = base64Url(180        utf8(181          JSON.stringify({182            aud: clientId,183            azp: clientId,184            email: googleEmailOf(consent.sub),185            email_verified: true,186            exp: now + 3600,187            iat: now,188            iss: "https://accounts.google.com",189            name: googleNameOf(consent.sub),190            nonce: grant.request.nonce,191            sub: consent.sub,192            ...consent.claims,193          })194        )195      );196197      const signature = yield* Effect.promise(() =>198        crypto.subtle.sign(rsa, key.privateKey, utf8(`${header}.${claims}`))199      );200201      return `${header}.${claims}.${base64Url(new Uint8Array(signature))}`;202    });203204  const token = (request: Request) =>205    Effect.gen(function* () {206      const form = Object.fromEntries(207        new URLSearchParams(yield* Effect.promise(() => request.text()))208      );209210      yield* Ref.update(exchanges, (all) => [...all, form.code ?? ""]);211212      const exchange = decodeCodeExchange(form);213214      const known = yield* Ref.get(grants);215216      const grant = Option.flatMap(exchange, ({ code }) =>217        Option.fromUndefinedOr(known.get(code))218      );219220      if (Option.isNone(exchange) || Option.isNone(grant)) {221        return Response.json({ error: "invalid_grant" }, { status: 400 });222      }223224      const challenge = yield* s256(exchange.value.code_verifier);225226      const matches =227        exchange.value.client_id === clientId &&228        exchange.value.client_secret === clientSecret &&229        exchange.value.redirect_uri === grant.value.request.redirect_uri &&230        challenge === grant.value.request.code_challenge;231232      if (!matches) {233        return Response.json({ error: "invalid_grant" }, { status: 400 });234      }235236      yield* Ref.update(grants, (all) => {237        const left = new Map(all);238239        left.delete(exchange.value.code);240241        return left;242      });243244      return Response.json({245        access_token: "ya29.a-google-access-token",246        expires_in: 3599,247        id_token: yield* idToken(grant.value),248        scope: "openid email profile",249        token_type: "Bearer",250      });251    });252253  const fetch = Fetch.of({254    fetch: (request) =>255      Effect.gen(function* () {256        yield* Ref.update(fetched, (all) => [...all, request.url]);257258        if (request.url === GOOGLE_DISCOVERY) {259          return Response.json({260            authorization_endpoint:261              "https://accounts.google.com/o/oauth2/v2/auth",262            code_challenge_methods_supported: ["plain", "S256"],263            id_token_signing_alg_values_supported: ["RS256"],264            issuer: "https://accounts.google.com",265            jwks_uri: jwksUri,266            token_endpoint: tokenEndpoint,267          });268        }269270        if (request.url === jwksUri) {271          const keys = yield* Ref.get(published);272273          return Response.json({274            keys: keys.map(({ publicJwk }) => publicJwk),275          });276        }277278        if (request.url === tokenEndpoint && request.method === "POST") {279          return yield* token(request);280        }281282        return new Response("not found", { status: 404 });283      }),284  });285286  const consent = (location: string, given: Consent) =>287    Effect.gen(function* () {288      const request = decodeAuthorizationRequest(289        Object.fromEntries(new URL(location).searchParams)290      );291292      const code = `code-${(yield* Ref.get(grants)).size + 1}-${given.sub}`;293294      yield* Ref.update(grants, (all) =>295        new Map(all).set(code, { consent: given, request })296      );297298      const back = new URL(request.redirect_uri);299300      back.searchParams.set("code", code);301      back.searchParams.set("state", request.state);302303      return back;304    });305306  const rotate = (kid: string) =>307    Effect.gen(function* () {308      const next = yield* keyPair(kid);309310      yield* Ref.update(published, (keys) => [...keys, next]);311312      return next;313    });314315  const timesFetched = (url: string) =>316    Ref.get(fetched).pipe(317      Effect.map((all) => all.filter((each) => each === url).length)318    );319320  return {321    consent,322    exchanges: Ref.get(exchanges),323    fetch,324    keyPair,325    rotate,326    timesFetched,327  };328});329330export type FakeGoogle = Effect.Success<typeof fakeGoogle>;331332export type Site = "cross-site" | "same-site";333334interface Kept {335  readonly strict: boolean;336  readonly value: string;337}338339const browserFor = (handler: (request: Request) => Promise<Response>) => {340  const jar = new Map<string, Kept>();341342  const send = (request: Request, from: Site = "same-site") =>343    Effect.gen(function* () {344      const headers = new Headers(request.headers);345346      const cookies = [...jar].flatMap(([name, kept]) =>347        from === "same-site" || !kept.strict ? [`${name}=${kept.value}`] : []348      );349350      if (cookies.length > 0) {351        headers.set("cookie", cookies.join("; "));352      }353354      const response = yield* Effect.promise(() =>355        handler(new Request(request, { headers, redirect: "manual" }))356      );357358      for (const line of response.headers.getSetCookie()) {359        const [pair = "", ...attributes] = line360          .split(";")361          .map((part) => part.trim());362363        const [name = "", value = ""] = pair.split("=");364365        const lowered = new Set(366          attributes.map((attribute) => attribute.toLowerCase())367        );368369        if (lowered.has("max-age=0")) {370          jar.delete(name);371        } else {372          jar.set(name, { strict: lowered.has("samesite=strict"), value });373        }374      }375376      return response;377    });378379  return {380    cookie: (name: string) => Option.fromUndefinedOr(jar.get(name)?.value),381    send,382  };383};384385const context = untouchable<ExecutionContext>("ExecutionContext");386387const platformFetch = (request: Request) =>388  Promise.resolve(389    new Response(`platform: ${new URL(request.url).pathname}`, { status: 418 })390  );391392export const googleWorld = (393  options: { readonly cookieKey?: string; readonly google?: boolean } = {}394) =>395  Effect.gen(function* () {396    const google = yield* fakeGoogle;397398    const withGoogle = googleEnv(options.google === false ? [] : undefined);399400    const env =401      options.cookieKey === undefined402        ? withGoogle403        : { ...withGoogle, COOKIE_KEY: options.cookieKey };404405    const config = yield* decodeEnv(env).pipe(Effect.orDie);406407    const accounts = yield* Effect.provide(408      Effect.service(Accounts),409      AccountsMemory.layer410    );411412    const identities = yield* Effect.provide(413      Effect.service(Identities),414      IdentitiesMemory.layer415    );416417    const store = OAuthStoreMemory.make();418419    const mailer = yield* MailerMemory.make();420421    const { dispose, handler } = oauthProvider(422      Layer.mergeAll(423        Layer.succeed(Accounts, accounts),424        Layer.succeed(Identities, identities),425        mailer.layer,426        Layer.succeed(OAuthStore, store),427        Layer.succeed(Fetch, google.fetch),428        SignInAttemptsMemory.layer,429        signInSettings(config)430      ),431      platformFetch432    );433434    const handle = (request: Request) =>435      Promise.resolve(handler.fetch(request, fakeEnv(), context));436437    yield* Effect.acquireRelease(438      Effect.sync(() => {439        vi.stubGlobal("Cloudflare", {440          compatibilityFlags: { global_fetch_strictly_public: true },441        });442        vi.stubGlobal("fetch", (input: RequestInfo | URL) =>443          handle(new Request(input))444        );445      }),446      () =>447        Effect.promise(dispose).pipe(448          Effect.andThen(Effect.sync(() => vi.unstubAllGlobals()))449        )450    );451452    return {453      accounts,454      browser: browserFor(handle),455      google,456      identities,457      mails: mailer.sent,458      store,459    };460  });461462export type GoogleWorld = Effect.Success<ReturnType<typeof googleWorld>>;