The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { BetterAuth, Memory } from "@alchemy.run/better-auth"; |
| 2 | import * as Domain from "@alchemy.run/domain"; |
| 3 | import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; |
| 4 | import { describe, expect, it } from "@effect/vitest"; |
| 5 | import { RuntimeContext } from "alchemy"; |
| 6 | import { genericOAuth } from "better-auth/plugins/generic-oauth"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Cookies from "effect/http/Cookies"; |
| 9 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 10 | import * as HttpClient from "effect/http/HttpClient"; |
| 11 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 12 | import * as HttpServer from "effect/http/HttpServer"; |
| 13 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 14 | import * as Layer from "effect/Layer"; |
| 15 | import { OAuth2Server } from "oauth2-mock-server"; |
| 16 | import { Auth } from "../src/Auth.ts"; |
| 17 | import { NotesModel } from "../src/Notes.model.ts"; |
| 18 | import { NotesApi } from "../src/NotesApi.api.ts"; |
| 19 | import { SessionLive } from "../src/Session.ts"; |
| 20 | import { UserId } from "../src/User.id.ts"; |
| 21 | |
| 22 | // A local OpenID Connect provider stands in for GitHub and Google, which a test can't sign in to. |
| 23 | // `signingInAs` picks who the next sign-in is. |
| 24 | let signingInAs = { sub: "u-sam", name: "Sam", email: "sam@example.com" }; |
| 25 | const Provider = Effect.acquireRelease( |
| 26 | Effect.promise(async () => { |
| 27 | const server = new OAuth2Server(); |
| 28 | await server.issuer.keys.generate("RS256"); |
| 29 | server.service.on("beforeTokenSigning", (token) => Object.assign(token.payload, signingInAs)); |
| 30 | server.service.on("beforeUserinfo", (userinfo) => { |
| 31 | userinfo.body = { ...signingInAs, email_verified: true }; |
| 32 | }); |
| 33 | await server.start(0, "127.0.0.1"); |
| 34 | return server; |
| 35 | }), |
| 36 | (server) => Effect.promise(() => server.stop()), |
| 37 | ); |
| 38 | |
| 39 | // The same better-auth the Worker runs, plus the local provider, over an in-memory database. |
| 40 | const AuthTest = Layer.effect( |
| 41 | Auth, |
| 42 | Effect.gen(function* () { |
| 43 | const provider = yield* Provider; |
| 44 | const { address } = yield* HttpServer.HttpServer; |
| 45 | return yield* BetterAuth({ |
| 46 | basePath: "/api/auth", |
| 47 | baseURL: `http://127.0.0.1:${(address as { port: number }).port}`, |
| 48 | secret: "a-test-secret-a-test-secret-a-test-secret", |
| 49 | socialProviders: { |
| 50 | github: { clientId: "github-client", clientSecret: "github-secret" }, |
| 51 | google: { clientId: "google-client", clientSecret: "google-secret" }, |
| 52 | }, |
| 53 | plugins: [ |
| 54 | genericOAuth({ |
| 55 | config: [ |
| 56 | { |
| 57 | providerId: "local", |
| 58 | discoveryUrl: `${provider.issuer.url}/.well-known/openid-configuration`, |
| 59 | clientId: "notes", |
| 60 | clientSecret: "notes-secret", |
| 61 | pkce: true, |
| 62 | }, |
| 63 | ], |
| 64 | }), |
| 65 | ], |
| 66 | }); |
| 67 | }).pipe(Effect.provide(Memory()), Effect.provide(RuntimeContext.phantom)), |
| 68 | ); |
| 69 | |
| 70 | // The Worker's routes on a real HTTP server: better-auth under /api/auth, the NotesApi under /api. |
| 71 | const Served = Layer.unwrap( |
| 72 | Effect.gen(function* () { |
| 73 | const auth = yield* Auth; |
| 74 | const api = yield* NotesApi; |
| 75 | return HttpServer.serve()( |
| 76 | Effect.gen(function* () { |
| 77 | const request = yield* HttpServerRequest; |
| 78 | if (request.url.startsWith("/api/auth/")) return yield* auth.fetch; |
| 79 | return yield* api.fetch; |
| 80 | }).pipe(Effect.provide(RuntimeContext.phantom)), |
| 81 | ); |
| 82 | }), |
| 83 | ).pipe( |
| 84 | Layer.provideMerge( |
| 85 | SessionLive.pipe( |
| 86 | Layer.provideMerge(AuthTest), |
| 87 | Layer.provideMerge(NotesModel.layer(Layer.empty).pipe(Layer.provide(Domain.InMemory))), |
| 88 | ), |
| 89 | ), |
| 90 | Layer.provideMerge(NodeHttpServer.layerTest), |
| 91 | ); |
| 92 | |
| 93 | /** Ask the app to start a sign-in; it answers with the provider URL to send the browser to. */ |
| 94 | const startSignIn = Effect.fn(function* (path: string, body: object) { |
| 95 | const client = yield* HttpClient.HttpClient; |
| 96 | const response = yield* client.execute( |
| 97 | HttpClientRequest.post(path).pipe(HttpClientRequest.bodyJsonUnsafe(body)), |
| 98 | ); |
| 99 | return { response, body: (yield* response.json) as { url: string } }; |
| 100 | }); |
| 101 | |
| 102 | /** Sign in through the local provider the way a browser does, and return its session cookie. */ |
| 103 | const signIn = Effect.fn( |
| 104 | function* (user: { sub: string; name: string; email: string }) { |
| 105 | signingInAs = user; |
| 106 | const client = yield* HttpClient.HttpClient; |
| 107 | |
| 108 | // The app sends the browser to the provider, with a state cookie. |
| 109 | const started = yield* startSignIn("/api/auth/sign-in/social", { |
| 110 | provider: "local", |
| 111 | callbackURL: "/", |
| 112 | }); |
| 113 | |
| 114 | // The provider signs the user in and sends the browser back with a code. |
| 115 | const provider = yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer)); |
| 116 | const authorized = yield* provider.get(started.body.url); |
| 117 | const callback = new URL(authorized.headers.location!); |
| 118 | |
| 119 | // The app's callback exchanges the code and sets the session cookie. |
| 120 | const done = yield* client.execute( |
| 121 | HttpClientRequest.get(`${callback.pathname}${callback.search}`).pipe( |
| 122 | HttpClientRequest.setHeader("cookie", Cookies.toCookieHeader(started.response.cookies)), |
| 123 | ), |
| 124 | ); |
| 125 | expect(done.status).toBe(302); |
| 126 | return Cookies.toCookieHeader(Cookies.merge(started.response.cookies, done.cookies)); |
| 127 | }, |
| 128 | Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), |
| 129 | ); |
| 130 | |
| 131 | /** A NotesApi client whose requests carry `cookie`, as a browser's do. */ |
| 132 | const notesAs = (cookie: string) => |
| 133 | NotesApi.client.pipe( |
| 134 | Effect.provide( |
| 135 | Domain.protocolHttp("").pipe( |
| 136 | Layer.provide( |
| 137 | Layer.effect( |
| 138 | HttpClient.HttpClient, |
| 139 | Effect.map( |
| 140 | HttpClient.HttpClient, |
| 141 | HttpClient.mapRequest(HttpClientRequest.setHeader("cookie", cookie)), |
| 142 | ), |
| 143 | ), |
| 144 | ), |
| 145 | ), |
| 146 | ), |
| 147 | ); |
| 148 | |
| 149 | describe("sign-in with better-auth", () => { |
| 150 | it.live("GitHub and Google send the browser to the provider, back to this app", () => |
| 151 | Effect.gen(function* () { |
| 152 | const github = yield* startSignIn("/api/auth/sign-in/social", { provider: "github" }); |
| 153 | const toGitHub = new URL(github.body.url); |
| 154 | expect(toGitHub.origin + toGitHub.pathname).toBe("https://github.com/login/oauth/authorize"); |
| 155 | expect(toGitHub.searchParams.get("client_id")).toBe("github-client"); |
| 156 | expect(new URL(toGitHub.searchParams.get("redirect_uri")!).pathname).toBe( |
| 157 | "/api/auth/callback/github", |
| 158 | ); |
| 159 | |
| 160 | const google = yield* startSignIn("/api/auth/sign-in/social", { provider: "google" }); |
| 161 | const toGoogle = new URL(google.body.url); |
| 162 | expect(toGoogle.origin + toGoogle.pathname).toBe( |
| 163 | "https://accounts.google.com/o/oauth2/v2/auth", |
| 164 | ); |
| 165 | expect(toGoogle.searchParams.get("client_id")).toBe("google-client"); |
| 166 | expect(new URL(toGoogle.searchParams.get("redirect_uri")!).pathname).toBe( |
| 167 | "/api/auth/callback/google", |
| 168 | ); |
| 169 | }).pipe(Effect.provide(Served), Effect.scoped), |
| 170 | ); |
| 171 | |
| 172 | it.live("a signed-in user writes and reads their own notes", () => |
| 173 | Effect.gen(function* () { |
| 174 | const cookie = yield* signIn({ sub: "u-sam", name: "Sam", email: "sam@example.com" }); |
| 175 | const session = yield* (yield* Auth).getSession(new Headers({ cookie })); |
| 176 | const sam = UserId.make(session!.user.id); |
| 177 | |
| 178 | const notes = yield* notesAs(cookie); |
| 179 | yield* notes.WriteNote(sam, { text: "buy milk" }); |
| 180 | const read = yield* notes.Notes.get(sam); |
| 181 | expect(read?.notes).toEqual(["buy milk"]); |
| 182 | }).pipe(Effect.provide(RuntimeContext.phantom), Effect.provide(Served), Effect.scoped), |
| 183 | ); |
| 184 | |
| 185 | it.live("without a session, the Api refuses", () => |
| 186 | Effect.gen(function* () { |
| 187 | const notes = yield* notesAs(""); |
| 188 | const refused = yield* notes.WriteNote(UserId.make("u-1"), { text: "hi" }).pipe(Effect.flip); |
| 189 | expect(refused._tag).toBe("Unauthorized"); |
| 190 | }).pipe(Effect.provide(Served), Effect.scoped), |
| 191 | ); |
| 192 | |
| 193 | it.live("a user can't write in or read someone else's notebook", () => |
| 194 | Effect.gen(function* () { |
| 195 | const samCookie = yield* signIn({ sub: "u-sam", name: "Sam", email: "sam@example.com" }); |
| 196 | const sam = UserId.make( |
| 197 | (yield* (yield* Auth).getSession(new Headers({ cookie: samCookie })))!.user.id, |
| 198 | ); |
| 199 | const alexCookie = yield* signIn({ sub: "u-alex", name: "Alex", email: "alex@example.com" }); |
| 200 | const alex = yield* notesAs(alexCookie); |
| 201 | |
| 202 | const write = yield* alex.WriteNote(sam, { text: "hi" }).pipe(Effect.flip); |
| 203 | expect(write._tag).toBe("NotYours"); |
| 204 | const read = yield* alex.Notes.get(sam).pipe(Effect.flip); |
| 205 | expect(read._tag).toBe("NotYours"); |
| 206 | }).pipe(Effect.provide(RuntimeContext.phantom), Effect.provide(Served), Effect.scoped), |
| 207 | ); |
| 208 | }); |