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

main
ts 175 lines 6.92 KB
Raw
1 import { msg } from "gt-i18n";
2 import { translatableDetail } from "../errors/translatable.ts";
3 import { EnvironmentId } from "@t3tools/contracts";
4 import * as Context from "effect/Context";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8 import * as Semaphore from "effect/Semaphore";
9 import * as Stream from "effect/Stream";
10 import * as SubscriptionRef from "effect/SubscriptionRef";
11
12 import type { ConnectionCatalogEntry } from "./catalog.ts";
13 import { ConnectionBlockedError, type ConnectionAttemptError } from "./model.ts";
14
15 export const PullRequestRoutingPermission = Schema.Literals(["off", "read", "read-write"]);
16 export type PullRequestRoutingPermission = typeof PullRequestRoutingPermission.Type;
17 export const StoredPullRequestRoutingPermission = Schema.Struct({
18 environmentId: EnvironmentId,
19 connectionKey: Schema.String,
20 permission: PullRequestRoutingPermission,
21 });
22 export type StoredPullRequestRoutingPermission = typeof StoredPullRequestRoutingPermission.Type;
23
24 /**
25 * Trust belongs to the saved endpoints, never to an environment id advertised
26 * by a server alone. With several routes the key covers all of them, sorted so
27 * reordering keeps trust but adding or changing an address revokes it.
28 */
29 export function pullRequestRoutingConnectionKey(entry: ConnectionCatalogEntry): string | null {
30 const routes = [
31 { target: entry.target, profile: entry.profile },
32 ...(entry.alternateRoutes ?? []),
33 ].filter((route) => {
34 const profile = Option.getOrNull(route.profile);
35 return !(profile?._tag === "BearerConnectionProfile" && profile.learned === true);
36 });
37 if (routes.length === 1) return routeConnectionKey(routes[0]!.target, routes[0]!.profile);
38 const keys = routes.map((route) => routeConnectionKey(route.target, route.profile));
39 return keys.every((key) => key !== null) ? JSON.stringify([...keys].sort()) : null;
40 }
41
42 function routeConnectionKey(
43 target: ConnectionCatalogEntry["target"],
44 routeProfile: ConnectionCatalogEntry["profile"],
45 ): string | null {
46 const entry = { profile: routeProfile };
47 if (target._tag === "RelayConnectionTarget")
48 return JSON.stringify([target._tag, target.environmentId]);
49 const profile = Option.getOrNull(entry.profile);
50 if (target._tag === "SshConnectionTarget") {
51 if (profile?._tag !== "SshConnectionProfile") return null;
52 const { alias, hostname, username, port } = profile.target;
53 return JSON.stringify([target._tag, target.environmentId, alias, hostname, username, port]);
54 }
55 const baseUrls =
56 target._tag === "PrimaryConnectionTarget"
57 ? [target.httpBaseUrl, target.wsBaseUrl]
58 : profile?._tag === "BearerConnectionProfile"
59 ? [profile.httpBaseUrl, profile.wsBaseUrl]
60 : null;
61 if (baseUrls === null) return null;
62 try {
63 const urls = baseUrls.map((baseUrl) => new URL(baseUrl));
64 if (
65 !["http:", "https:"].includes(urls[0]!.protocol) ||
66 !["ws:", "wss:"].includes(urls[1]!.protocol) ||
67 urls.some((url) => url.username || url.password)
68 )
69 return null;
70 return JSON.stringify([
71 target._tag,
72 target.environmentId,
73 ...urls.map((url) => url.href.replace(/\/+$/, "")),
74 ]);
75 } catch {
76 return null;
77 }
78 }
79
80 export function pullRequestRoutingPermissionFor(
81 entry: ConnectionCatalogEntry,
82 permissions: ReadonlyArray<StoredPullRequestRoutingPermission>,
83 ): PullRequestRoutingPermission {
84 const key = pullRequestRoutingConnectionKey(entry);
85 return key === null
86 ? "off"
87 : (permissions.find((permission) => permission.connectionKey === key)?.permission ?? "off");
88 }
89
90 export class PullRequestRoutingPermissions extends Context.Reference<{
91 readonly get: (entry: ConnectionCatalogEntry) => Effect.Effect<PullRequestRoutingPermission>;
92 readonly changes: Stream.Stream<ReadonlyArray<StoredPullRequestRoutingPermission>>;
93 readonly set: (
94 entry: ConnectionCatalogEntry,
95 permission: PullRequestRoutingPermission,
96 ) => Effect.Effect<void, ConnectionAttemptError>;
97 readonly forget: (environmentId: EnvironmentId) => Effect.Effect<void, ConnectionAttemptError>;
98 }>("@t3tools/client-runtime/connection/PullRequestRoutingPermissions", {
99 defaultValue: () => ({
100 get: () => Effect.succeed("off"),
101 changes: Stream.succeed([]),
102 set: () =>
103 Effect.fail(
104 new ConnectionBlockedError({
105 reason: "unsupported",
106 ...translatableDetail(
107 msg("Pull request routing preferences are unavailable on this client."),
108 ),
109 }),
110 ),
111 forget: () => Effect.void,
112 }),
113 }) {}
114
115 export const makePullRequestRoutingPermissions = Effect.fn("makePullRequestRoutingPermissions")(
116 function* (storage: {
117 readonly read: Effect.Effect<
118 ReadonlyArray<StoredPullRequestRoutingPermission>,
119 ConnectionAttemptError
120 >;
121 readonly write: (
122 permissions: ReadonlyArray<StoredPullRequestRoutingPermission>,
123 ) => Effect.Effect<void, ConnectionAttemptError>;
124 }) {
125 const state = yield* SubscriptionRef.make(yield* storage.read);
126 const lock = yield* Semaphore.make(1);
127 const update = (
128 transform: (
129 current: ReadonlyArray<StoredPullRequestRoutingPermission>,
130 ) => ReadonlyArray<StoredPullRequestRoutingPermission>,
131 ) =>
132 lock.withPermits(1)(
133 Effect.gen(function* () {
134 const current = yield* SubscriptionRef.get(state);
135 const next = transform(current);
136 if (next === current) return;
137 yield* storage.write(next);
138 yield* SubscriptionRef.set(state, next);
139 }),
140 );
141 return PullRequestRoutingPermissions.of({
142 get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {
143 return SubscriptionRef.get(state).pipe(
144 Effect.map((permissions) => pullRequestRoutingPermissionFor(entry, permissions)),
145 );
146 }),
147 changes: SubscriptionRef.changes(state),
148 set: Effect.fn("PullRequestRoutingPermissions.set")(function (entry, permission) {
149 const connectionKey = pullRequestRoutingConnectionKey(entry);
150 if (connectionKey === null)
151 return Effect.fail(
152 new ConnectionBlockedError({
153 reason: "configuration",
154 ...translatableDetail(
155 msg("This environment does not have a saved connection endpoint."),
156 ),
157 }),
158 );
159 return update((current) => [
160 ...current.filter((value) => value.environmentId !== entry.target.environmentId),
161 ...(permission === "off"
162 ? []
163 : [{ environmentId: entry.target.environmentId, connectionKey, permission }]),
164 ]);
165 }),
166 forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {
167 return update((current) =>
168 current.some((permission) => permission.environmentId === environmentId)
169 ? current.filter((permission) => permission.environmentId !== environmentId)
170 : current,
171 );
172 }),
173 });
174 },
175 );