@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, 04:45 UTC

main
ts 45 lines 1.51 KB
Raw
1 import { RuntimeContext } from "alchemy";
2 import * as Effect from "effect/Effect";
3 import * as HttpApiMiddleware from "effect/http-api/HttpApiMiddleware";
4 import * as Layer from "effect/Layer";
5 import * as Schema from "effect/Schema";
6 import { Auth } from "./auth.ts";
7 import { CurrentUser } from "./current-user.ts";
8
9 export class Unauthorized extends Schema.TaggedError<Unauthorized>()(
10 "Unauthorized",
11 {},
12 { httpApiStatus: 401 },
13 ) {}
14
15 export class AuthenticationUnavailable extends Schema.TaggedError<AuthenticationUnavailable>()(
16 "AuthenticationUnavailable",
17 {},
18 { httpApiStatus: 503 },
19 ) {}
20
21 export class Authentication extends HttpApiMiddleware.Service<
22 Authentication,
23 { provides: CurrentUser }
24 >()("app/Authentication", {
25 error: [Unauthorized, AuthenticationUnavailable],
26 }) {
27 static readonly layer = Layer.effect(
28 Authentication,
29 Effect.gen(function* () {
30 const auth = yield* Auth;
31 return (httpEffect) =>
32 Effect.gen(function* () {
33 const session = yield* auth.getSession().pipe(
34 Effect.mapError(() => new AuthenticationUnavailable()),
35 Effect.catchDefect(() => Effect.fail(new AuthenticationUnavailable())),
36 );
37 if (session === null) return yield* new Unauthorized();
38 return yield* Effect.provideService(httpEffect, CurrentUser, session.user);
39 }).pipe(
40 // HttpApi does not carry Alchemy's runtime marker; the Worker owns request scope.
41 Effect.provide(RuntimeContext.phantom),
42 );
43 }),
44 );
45 }