@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 259 lines 10.3 KB
Raw
1 import type { RuntimeContext } from "alchemy";
2 import { Random } from "alchemy";
3 import type { HttpEffect } from "alchemy/Http";
4 import { makeExecutionMemo } from "alchemy/Runtime/ExecutionMemo";
5 import { betterAuth, type Auth, type BetterAuthOptions } from "better-auth";
6 import * as Effect from "effect/Effect";
7 import * as HttpServerRequest from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import * as Option from "effect/Option";
10 import * as Redacted from "effect/Redacted";
11 import { makeApiProxy, type BetterAuthApi } from "./ApiProxy.ts";
12 import { Database } from "./Database.ts";
13 import type { BetterAuthApiError } from "./Errors.ts";
14 import { SecondaryStorage, toPromiseStorage } from "./SecondaryStorage.ts";
15
16 /**
17 * Better Auth options, minus the fields alchemy owns:
18 *
19 * - `database` comes from the {@link Database} platform layer
20 * (`Cloudflare.D1`, `Postgres`, `Memory`, ...)
21 * - `secondaryStorage` comes from the optional {@link SecondaryStorage}
22 * layer (`Cloudflare.KV`)
23 * - `secret` is widened to accept `Redacted` values and Effects (resource
24 * outputs), and defaults to an auto-provisioned stable random secret
25 *
26 * plus alchemy extensions (`id`, `migrate`).
27 */
28 export interface BetterAuthProps extends Omit<
29 BetterAuthOptions,
30 "database" | "secondaryStorage" | "secret"
31 > {
32 /**
33 * Distinguishes multiple BetterAuth instances in one namespace — suffixes
34 * the auto-provisioned secret resource and the migration action logical
35 * ids.
36 *
37 * @default "BetterAuth"
38 */
39 readonly id?: string;
40 /**
41 * Deploy-time automatic schema migration. Runs as an internal alchemy
42 * Action during `alchemy deploy` (never at plan, never inside the
43 * deployed runtime) and re-runs only when the auth schema (plugins,
44 * additional fields, indexes) or the target database changes.
45 *
46 * `false` opts out. `true` on a Database layer without migration support
47 * (Memory, Drizzle) fails the deploy with a descriptive error.
48 *
49 * @default true when the Database layer supports migration
50 */
51 readonly migrate?: boolean;
52 /**
53 * The Better Auth signing secret. Accepts a literal string, a `Redacted`
54 * value, or an Effect resolving to one (e.g. another resource's output
55 * accessor).
56 *
57 * @default an auto-provisioned `Alchemy.Random` secret (`${id}Secret`),
58 * generated once and stable across deploys
59 */
60 readonly secret?:
61 | string
62 | Redacted.Redacted<string>
63 | Effect.Effect<Redacted.Redacted<string>, never, RuntimeContext>;
64 }
65
66 /**
67 * The Better Auth options type seen by `Auth<Options>` — the user's literal
68 * options with the alchemy extension fields stripped, so plugin/session/user
69 * type inference flows through untouched.
70 */
71 export type AuthOptions<O extends BetterAuthProps> =
72 Omit<O, "id" | "migrate" | "secret"> extends infer T extends BetterAuthOptions
73 ? T
74 : BetterAuthOptions;
75
76 /** The inferred `{ session, user }` shape for a given options type. */
77 export type Session<O extends BetterAuthProps> = Auth<AuthOptions<O>>["$Infer"]["Session"];
78
79 export interface BetterAuthInstance<O extends BetterAuthProps> {
80 /**
81 * The per-execution Better Auth instance (memoized on the execution
82 * scope). Escape hatch for anything the effectified surface doesn't
83 * cover (`$context`, `asResponse`/`returnHeaders` call forms, ...).
84 */
85 readonly auth: Effect.Effect<Auth<AuthOptions<O>>, never, RuntimeContext>;
86 /**
87 * Every `auth.api.*` endpoint mirrored as an Effect with a typed
88 * {@link BetterAuthApiError} failure.
89 */
90 readonly api: BetterAuthApi<Auth<AuthOptions<O>>["api"]>;
91 /**
92 * HTTP handler for the Better Auth routes — mount it under your
93 * `basePath` (default `/api/auth`):
94 *
95 * ```typescript
96 * fetch: Effect.gen(function* () {
97 * const request = yield* HttpServerRequest;
98 * if (request.url.startsWith("/api/auth")) {
99 * return yield* auth.fetch;
100 * }
101 * // ...
102 * })
103 * ```
104 */
105 readonly fetch: HttpEffect<RuntimeContext>;
106 /**
107 * Look up the session for the ambient request (or explicit `Headers`).
108 * Resolves `null` for anonymous requests — failures are real errors, not
109 * missing sessions.
110 */
111 readonly getSession: {
112 (): Effect.Effect<
113 Session<O> | null,
114 BetterAuthApiError,
115 RuntimeContext | HttpServerRequest.HttpServerRequest
116 >;
117 (headers: Headers): Effect.Effect<Session<O> | null, BetterAuthApiError, RuntimeContext>;
118 };
119 /** Type-level mirror of `auth.$Infer` (phantom — no runtime value). */
120 readonly Infer: Auth<AuthOptions<O>>["$Infer"];
121 }
122
123 /**
124 * Create a Better Auth instance wired to alchemy.
125 *
126 * The database comes from a {@link Database} platform layer provided on
127 * the surrounding Worker/Function impl effect; the signing secret defaults
128 * to a stable auto-provisioned random secret; schema migrations run
129 * automatically at deploy time.
130 *
131 * ```typescript
132 * Effect.gen(function* () {
133 * const auth = yield* BetterAuth({
134 * basePath: "/api/auth",
135 * emailAndPassword: { enabled: true },
136 * });
137 * return { fetch: ... };
138 * }).pipe(Effect.provide(CloudflareD1(Db)))
139 * ```
140 */
141 export const BetterAuth = <const O extends BetterAuthProps>(
142 options: O,
143 ): Effect.Effect<BetterAuthInstance<O>, never, Database> =>
144 Effect.gen(function* () {
145 const { id = "BetterAuth", migrate, secret, ...userOptions } = options as BetterAuthProps;
146 const authOptions = userOptions as BetterAuthOptions;
147
148 const db = yield* Database;
149 const secondary = yield* Effect.serviceOption(SecondaryStorage);
150
151 // Resolve the signing secret to an Effect usable at runtime. The
152 // default is a Random resource whose Output accessor binds the value
153 // into the host environment at deploy and reads it back at runtime.
154 let secretAccessor: Effect.Effect<Redacted.Redacted<string>>;
155 if (secret === undefined) {
156 const resource = yield* Random(`${id}Secret`);
157 secretAccessor = yield* resource.text;
158 } else if (typeof secret === "string") {
159 secretAccessor = Effect.succeed(Redacted.make(secret));
160 } else if (Effect.isEffect(secret)) {
161 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- RuntimeContext is satisfied by the host at runtime
162 secretAccessor = secret as Effect.Effect<Redacted.Redacted<string>>;
163 } else {
164 secretAccessor = Effect.succeed(secret);
165 }
166
167 // Deploy-time migration registration. The whole block — including the
168 // Migrate module with its better-auth/db + kysely imports — is
169 // unreachable at runtime and dead-code-eliminated from bundles.
170 if (!globalThis.__ALCHEMY_RUNTIME__) {
171 const { registerMigration } = yield* Effect.promise(() => import("./Migrate.ts"));
172 yield* registerMigration({ id, options: authOptions, db, migrate });
173 }
174
175 // One Better Auth instance per execution (Worker event, DO call,
176 // Lambda invoke): the database input may hold sockets (pg/mysql
177 // pools), which are IoContext-pinned on workerd — they are acquired
178 // on the execution scope and released when the event settles.
179 const makeAuth = yield* makeExecutionMemo(
180 Effect.gen(function* () {
181 const database = yield* db.runtime;
182 const secretValue = Redacted.value(yield* secretAccessor);
183
184 // Background tasks (better-auth's internal fire-and-forget work)
185 // are awaited by a finalizer on the execution scope — the bridges
186 // register it with `ctx.waitUntil` on workerd and settle it
187 // inline on Lambda.
188 const pending: Promise<unknown>[] = [];
189 yield* Effect.addFinalizer(() => Effect.promise(() => Promise.allSettled(pending)));
190
191 const context = yield* Effect.context<RuntimeContext>();
192 const runPromise = <A, E>(effect: Effect.Effect<A, E, RuntimeContext>): Promise<A> =>
193 Effect.runPromiseWith(context)(effect);
194
195 return betterAuth({
196 ...authOptions,
197 database,
198 secret: secretValue,
199 ...(Option.isSome(secondary)
200 ? {
201 secondaryStorage: toPromiseStorage(secondary.value, runPromise),
202 }
203 : {}),
204 advanced: {
205 ...authOptions.advanced,
206 backgroundTasks: authOptions.advanced?.backgroundTasks ?? {
207 handler: (promise) => {
208 pending.push(promise);
209 },
210 },
211 },
212 }) as unknown as Auth<AuthOptions<O>>;
213 }),
214 );
215
216 const api = makeApiProxy<Auth<AuthOptions<O>>>(makeAuth);
217
218 const fetch: HttpEffect<RuntimeContext> = Effect.gen(function* () {
219 const request = yield* HttpServerRequest.HttpServerRequest;
220 const webRequest = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);
221 const auth = yield* makeAuth;
222 // `auth.handler` never rejects for API errors — they come back as
223 // error Responses, exactly what a pass-through route wants.
224 const response = yield* Effect.promise(() => auth.handler(webRequest));
225 return HttpServerResponse.fromWeb(response);
226 });
227
228 const apiAny = api as Record<
229 string,
230 (input: unknown) => Effect.Effect<unknown, BetterAuthApiError, RuntimeContext>
231 >;
232 const getSession = ((headers?: Headers) =>
233 headers === undefined
234 ? Effect.gen(function* () {
235 const request = yield* HttpServerRequest.HttpServerRequest;
236 const webRequest = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);
237 return yield* apiAny.getSession!({ headers: webRequest.headers });
238 })
239 : apiAny.getSession!({
240 headers,
241 })) as BetterAuthInstance<O>["getSession"];
242
243 return {
244 auth: makeAuth,
245 api,
246 fetch,
247 getSession,
248 Infer: undefined as unknown as BetterAuthInstance<O>["Infer"],
249 } satisfies BetterAuthInstance<O>;
250 }).pipe(
251 (effect) =>
252 // Deploy-only requirements picked up by the init effect — the Random
253 // provider during stack evaluation, RuntimeContext for Output binds,
254 // Stack for migration Action registration — are provided ambiently by
255 // stack evaluation at deploy and by the bridge at runtime. They are
256 // erased from the public type (same doctrine as `makeExecutionMemo`
257 // erasing `Scope`); the one requirement the CALLER owns is `Database`.
258 effect as unknown as Effect.Effect<BetterAuthInstance<O>, never, Database>,
259 );