@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 225 lines 7.97 KB
Raw
1 /**
2 * A second application assembly with custom native HTTP handlers: the
3 * suite's middleware, plus one branch-protection rule. This is the
4 * reference for "a rule about refs": an application policy is an ordinary effect
5 * over the parsed updates, it reads what the middleware put in context,
6 * and it never sees a credential.
7 *
8 * Lives in its own module (not `stack.ts`) because a Worker's generated
9 * entry imports its `main` module's DEFAULT export — one Worker class
10 * per entry module.
11 */
12 import * as Cloudflare from "@alchemy.run/cloudflare";
13 import * as Git from "@alchemy.run/git";
14 import {
15 ApiHandlersLive,
16 BlobStoreR2,
17 GIT_WORKER_OPTIONS,
18 HasherInline,
19 RegistryDurableObject,
20 ReposDurableObject,
21 } from "@alchemy.run/git";
22 import * as GitHttp from "@alchemy.run/git/Http";
23 import * as Alchemy from "alchemy";
24 import * as Http from "alchemy/Http";
25 import * as Effect from "effect/Effect";
26 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
27 import * as HttpRouter from "effect/http/HttpRouter";
28 import * as Layer from "effect/Layer";
29 import { GitHubLive } from "./http.ts";
30 import { TestAuthLive, TestCaller } from "./test-auth.ts";
31
32 /** Ordinary request effects: policies retain the middleware's typed caller. */
33 const protectMain = (repo: Git.RepoMetaData, updates: ReadonlyArray<Git.RefUpdate>) =>
34 Effect.gen(function* () {
35 const { user } = yield* TestCaller;
36 for (const update of updates) {
37 if (update.ref === "refs/heads/main" && user?.id !== repo.owner) {
38 return yield* new Git.PushDenied({
39 ref: update.ref,
40 reason: "not permitted: only the owner moves main",
41 });
42 }
43 }
44 });
45
46 const ProtocolLive = HttpApiBuilder.group(Git.Api, "protocol", (h) =>
47 Effect.gen(function* () {
48 const handlers = yield* Git.Handlers;
49 const git = yield* Git.Engine;
50 return h
51 .handleRaw("infoRefs", handlers.protocol.infoRefs)
52 .handleRaw("uploadPack", handlers.protocol.uploadPack)
53 .handleRaw("receivePack", ({ params, request }) =>
54 Effect.scoped(
55 Effect.gen(function* () {
56 const repo = yield* git.repositories
57 .get(params)
58 .pipe(Effect.catchTag("StoreError", Effect.die));
59 const push = yield* GitHttp.ReceivePack.decode(request);
60 if (push._tag === "Probe") return GitHttp.ReceivePack.probeResponse();
61 return yield* Effect.gen(function* () {
62 yield* protectMain(repo, push.updates);
63 const prepared = yield* git.preparePush(repo, push.input);
64 for (const update of prepared.updates) {
65 if (/^0+$/.test(update.newOid)) continue;
66 const object = yield* prepared.readObject(update.newOid);
67 if (object?.type === 1) {
68 const commit = yield* Git.parseCommit(object.content).pipe(Effect.orDie);
69 if (commit.message.includes("[reject-content]"))
70 return yield* new Git.PushDenied({
71 ref: update.ref,
72 reason: "commit rejected by content policy",
73 });
74 }
75 }
76 return GitHttp.ReceivePack.response(push, yield* git.commitPush(prepared));
77 }).pipe(
78 Effect.catchTag("PushDenied", (error) =>
79 Effect.succeed(GitHttp.ReceivePack.reject(push, error.reason)),
80 ),
81 );
82 }),
83 ).pipe(
84 Effect.catchTag("StoreError", (error) =>
85 Effect.succeed(GitHttp.ReceivePack.failure(error.reason)),
86 ),
87 Effect.catchTag(["WireProtocolError", "PackIngestError"], (error) =>
88 Effect.succeed(GitHttp.ReceivePack.failure(error.reason)),
89 ),
90 ),
91 );
92 }),
93 );
94
95 const RefsLive = HttpApiBuilder.group(Git.Api, "refs", (h) =>
96 Effect.gen(function* () {
97 const handlers = yield* Git.Handlers;
98 const git = yield* Git.Engine;
99 return h.handleAll({
100 ...handlers.refs,
101 update: (input) =>
102 Effect.gen(function* () {
103 const repo = yield* git.repositories
104 .get(input.params)
105 .pipe(Effect.catchTag("StoreError", Effect.die));
106 const current = yield* git.refs.get(repo, input.query.name).pipe(
107 Effect.map((ref) => ref.oid),
108 Effect.catchTag("RefNotFound", () => Effect.succeed("0".repeat(40))),
109 Effect.catchTag("StoreError", Effect.die),
110 );
111 yield* protectMain(repo, [
112 {
113 ref: input.query.name,
114 oldOid: current,
115 newOid: input.payload.newOid,
116 },
117 ]);
118 return yield* handlers.refs.update({
119 ...input,
120 payload: {
121 ...input.payload,
122 expectedOid:
123 input.payload.expectedOid !== undefined
124 ? input.payload.expectedOid
125 : current === "0".repeat(40)
126 ? null
127 : (current as Git.Oid),
128 },
129 });
130 }),
131 remove: (input) =>
132 Effect.gen(function* () {
133 const repo = yield* git.repositories
134 .get(input.params)
135 .pipe(Effect.catchTag("StoreError", Effect.die));
136 const current = yield* git.refs
137 .get(repo, input.query.name)
138 .pipe(Effect.catchTag("StoreError", Effect.die));
139 yield* protectMain(repo, [
140 {
141 ref: input.query.name,
142 oldOid: current.oid,
143 newOid: "0".repeat(40),
144 },
145 ]);
146 return yield* handlers.refs.remove({
147 ...input,
148 payload: {
149 expectedOid: input.payload.expectedOid ?? (current.oid as Git.Oid),
150 },
151 });
152 }),
153 });
154 }),
155 );
156
157 const PullsLive = HttpApiBuilder.group(Git.Api, "pulls", (h) =>
158 Effect.gen(function* () {
159 const handlers = yield* Git.Handlers;
160 const git = yield* Git.Engine;
161 return h.handleAll({
162 ...handlers.pulls,
163 merge: (input) =>
164 Effect.gen(function* () {
165 const repo = yield* git.repositories
166 .get(input.params)
167 .pipe(Effect.catchTag("StoreError", Effect.die));
168 const pull = yield* git.pulls
169 .get(repo, input.params.number)
170 .pipe(Effect.catchTag("StoreError", Effect.die));
171 yield* protectMain(repo, [
172 {
173 ref: pull.baseRef,
174 oldOid: pull.baseOid ?? "0".repeat(40),
175 newOid: pull.headOid ?? "0".repeat(40),
176 },
177 ]);
178 return yield* handlers.pulls.merge(input);
179 }),
180 });
181 }),
182 );
183
184 const ProtectedRoutes = Layer.mergeAll(
185 HttpApiBuilder.layer(Git.Api).pipe(
186 Layer.provide(Layer.mergeAll(Git.GroupsLive, GitHubLive, ProtocolLive, RefsLive, PullsLive)),
187 Layer.provide(TestAuthLive),
188 ),
189 Git.InternalApiLive,
190 ).pipe(Layer.provide(Http.Platform));
191
192 /** This assembly's bucket (its own stack, so no clash with `stack.ts`). */
193 const GitObjects = Cloudflare.R2.Bucket("GitObjects");
194
195 const ProtectedGitLive = ProtectedRoutes.pipe(
196 Layer.provide(ApiHandlersLive),
197 Layer.provide(ReposDurableObject),
198 Layer.provide(RegistryDurableObject),
199 Layer.provide(HasherInline),
200 Layer.provide(BlobStoreR2(GitObjects)),
201 );
202
203 /** Identical to the shared fixture's host except for the policy. */
204 export default class ProtectedGitHost extends Cloudflare.Worker<ProtectedGitHost>()(
205 "GitProtectedWorker",
206 {
207 main: import.meta.url,
208 ...GIT_WORKER_OPTIONS,
209 },
210 Effect.gen(function* () {
211 const fetch = yield* HttpRouter.toHttpEffect(ProtectedGitLive);
212 return { fetch };
213 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
214 ) {}
215
216 /** Deployable stack for the protected-branch test. */
217 export const makeProtectedStack = (name: string) =>
218 Alchemy.Stack(
219 name,
220 { providers: Cloudflare.providers(), state: Alchemy.localState() },
221 Effect.gen(function* () {
222 const host = yield* ProtectedGitHost;
223 return { url: host.url.as<string>() };
224 }),
225 );