@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 130 lines 5.41 KB
Raw
1 import { GitApi, isRead, RegistryStore } from "@alchemy.run/git";
2 import { RuntimeContext } from "alchemy/RuntimeContext";
3 /**
4 * The suites' auth, in user land, the way a host builds it: one `HttpRouter`
5 * middleware in front of every git route. Two shared secrets name two
6 * users; anything else is anonymous, and anonymous may read public
7 * repositories and nothing more. The engine never sees a credential.
8 *
9 * So that the suites work out of the box (local dev especially), a
10 * deterministic default `GIT_SERVICE_SECRET` is installed into
11 * `process.env` at module load unless the caller already exported one.
12 */
13 import * as Context from "effect/Context";
14 import * as Effect from "effect/Effect";
15 import * as HttpApiMiddleware from "effect/http-api/HttpApiMiddleware";
16 import * as HttpRouter from "effect/http/HttpRouter";
17 import * as HttpServerRequest from "effect/http/HttpServerRequest";
18 import * as HttpServerResponse from "effect/http/HttpServerResponse";
19 import * as Schema from "effect/Schema";
20
21 /**
22 * The secret every suite authenticates with. Honors a caller-provided
23 * `GIT_SERVICE_SECRET` (the deployed-cloud suites may point at a
24 * standing deployment); otherwise a deterministic test-only value.
25 */
26 export const TEST_SECRET: string =
27 process.env.GIT_SERVICE_SECRET ?? "test-secret-git-service-suite";
28 /** A second credential, resolved to a second user (for the hook tests). */
29 export const TEST_SECRET_DEV = "test-secret-git-service-suite-dev";
30 export const TEST_USER = { id: "e2e", name: "Suite" } as const;
31 export const TEST_USER_DEV = { id: "dev", name: "Dev" } as const;
32 process.env.GIT_SERVICE_SECRET ??= TEST_SECRET;
33
34 export interface TestUser {
35 readonly id: string;
36 readonly name: string;
37 }
38
39 /** 401 — no usable credential, on a route that needs one. */
40 export class Unauthorized extends Schema.TaggedError<Unauthorized>()(
41 "Unauthorized",
42 {},
43 { httpApiStatus: 401 },
44 ) {}
45
46 /**
47 * Who is calling, as the middleware resolved it: a user, or `null` for an
48 * anonymous read of a public repository. Routes and hooks read it.
49 */
50 export class TestCaller extends Context.Service<TestCaller, { readonly user: TestUser | null }>()(
51 "test/Git/Caller",
52 ) {}
53
54 /** API schema for typed clients. Authentication is applied to router layers. */
55 // Client-only error declaration: router middleware returns this error on 401.
56 class AuthenticationErrors extends HttpApiMiddleware.Service<AuthenticationErrors>()(
57 "test/Git/AuthenticationErrors",
58 { error: Unauthorized },
59 ) {}
60 export class TestApi extends GitApi.middleware(AuthenticationErrors) {}
61
62 /**
63 * The credential a request carries: `git` sends HTTP Basic with the
64 * token in the password field, the REST clients a bearer token.
65 */
66 const credential = (headers: Readonly<Record<string, string | undefined>>): string | undefined => {
67 const header = headers.authorization;
68 if (header === undefined) return undefined;
69 const space = header.indexOf(" ");
70 if (space === -1) return undefined;
71 const scheme = header.slice(0, space).toLowerCase();
72 const rest = header.slice(space + 1).trim();
73 if (scheme === "bearer" || scheme === "token") return rest || undefined;
74 if (scheme === "basic") {
75 const decoded = Buffer.from(rest, "base64").toString("utf8");
76 const colon = decoded.indexOf(":");
77 return colon === -1 ? undefined : decoded.slice(colon + 1) || undefined;
78 }
79 return undefined;
80 };
81
82 /** A 401 that makes `git` ask for credentials (or fail with "Authentication failed"). */
83 const unauthorized = HttpServerResponse.jsonUnsafe(
84 { _tag: "Unauthorized" },
85 { status: 401, headers: { "www-authenticate": 'Basic realm="git"' } },
86 );
87
88 /**
89 * Two secrets, two users; anything else is anonymous. Anonymous callers
90 * may read a public repository: the REST and raw reads, the GitHub
91 * facade's `GET`s, and a clone or fetch over the wire. Everything else
92 * is a 401 with `WWW-Authenticate`, so `git` prompts.
93 */
94 export const TestAuthLive = HttpRouter.middleware<{ provides: TestCaller }>()(
95 Effect.gen(function* () {
96 const registry = yield* RegistryStore;
97 return (httpEffect) =>
98 Effect.gen(function* () {
99 const request = yield* HttpServerRequest.HttpServerRequest;
100 const presented = credential(request.headers);
101 if (presented === TEST_SECRET) {
102 return yield* Effect.provideService(httpEffect, TestCaller, {
103 user: TEST_USER,
104 });
105 }
106 if (presented === TEST_SECRET_DEV) {
107 return yield* Effect.provideService(httpEffect, TestCaller, {
108 user: TEST_USER_DEV,
109 });
110 }
111 if (presented !== undefined) return unauthorized;
112
113 // Anonymous: a read of one public repository, or nothing. A
114 // repository that does not exist is the route's 404, so a 401
115 // never confirms a private one.
116 if (!isRead(request)) return unauthorized;
117 const params = yield* HttpRouter.params;
118 const owner = params.owner?.toLowerCase();
119 const name = params.repo?.toLowerCase().replace(/\.git$/, "");
120 if (owner === undefined || name === undefined) return unauthorized;
121 const entry = yield* registry
122 .resolve(owner, name)
123 .pipe(Effect.catchTag("StoreError", () => Effect.succeed(undefined)));
124 if (entry !== undefined && !entry.public) return unauthorized;
125 return yield* Effect.provideService(httpEffect, TestCaller, {
126 user: null,
127 });
128 }).pipe(Effect.provide(RuntimeContext.phantom));
129 }),
130 ).layer;