Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import * as Semaphore from "effect/Semaphore";
7import * as Stream from "effect/Stream";
8import * as SubscriptionRef from "effect/SubscriptionRef";
9
10import type { ConnectionCatalogEntry } from "./catalog.ts";
11import { ConnectionBlockedError, type ConnectionAttemptError } from "./model.ts";
12
13export const GitHubRoutingPermission = Schema.Literals(["off", "read", "read-write"]);
14export type GitHubRoutingPermission = typeof GitHubRoutingPermission.Type;
15export const StoredGitHubRoutingPermission = Schema.Struct({
16 environmentId: EnvironmentId,
17 connectionKey: Schema.String,
18 permission: GitHubRoutingPermission,
19});
20export type StoredGitHubRoutingPermission = typeof StoredGitHubRoutingPermission.Type;
21
22/** Trust belongs to the saved endpoint, never to an environment id advertised by a server alone. */
23export function gitHubRoutingConnectionKey(entry: ConnectionCatalogEntry): string | null {
24 const target = entry.target;
25 if (target._tag === "RelayConnectionTarget")
26 return JSON.stringify([target._tag, target.environmentId]);
27 const profile = Option.getOrNull(entry.profile);
28 if (target._tag === "SshConnectionTarget") {
29 if (profile?._tag !== "SshConnectionProfile") return null;
30 const { alias, hostname, username, port } = profile.target;
31 return JSON.stringify([target._tag, target.environmentId, alias, hostname, username, port]);
32 }
33 const baseUrls =
34 target._tag === "PrimaryConnectionTarget"
35 ? [target.httpBaseUrl, target.wsBaseUrl]
36 : profile?._tag === "BearerConnectionProfile"
37 ? [profile.httpBaseUrl, profile.wsBaseUrl]
38 : null;
39 if (baseUrls === null) return null;
40 try {
41 const urls = baseUrls.map((baseUrl) => new URL(baseUrl));
42 if (
43 !["http:", "https:"].includes(urls[0]!.protocol) ||
44 !["ws:", "wss:"].includes(urls[1]!.protocol) ||
45 urls.some((url) => url.username || url.password)
46 )
47 return null;
48 return JSON.stringify([
49 target._tag,
50 target.environmentId,
51 ...urls.map((url) => url.href.replace(/\/+$/, "")),
52 ]);
53 } catch {
54 return null;
55 }
56}
57
58export function gitHubRoutingPermissionFor(
59 entry: ConnectionCatalogEntry,
60 permissions: ReadonlyArray<StoredGitHubRoutingPermission>,
61): GitHubRoutingPermission {
62 const key = gitHubRoutingConnectionKey(entry);
63 return key === null
64 ? "off"
65 : (permissions.find((permission) => permission.connectionKey === key)?.permission ?? "off");
66}
67
68export class GitHubRoutingPermissions extends Context.Reference<{
69 readonly get: (entry: ConnectionCatalogEntry) => Effect.Effect<GitHubRoutingPermission>;
70 readonly changes: Stream.Stream<ReadonlyArray<StoredGitHubRoutingPermission>>;
71 readonly set: (
72 entry: ConnectionCatalogEntry,
73 permission: GitHubRoutingPermission,
74 ) => Effect.Effect<void, ConnectionAttemptError>;
75 readonly forget: (environmentId: EnvironmentId) => Effect.Effect<void, ConnectionAttemptError>;
76}>("@t3tools/client-runtime/connection/GitHubRoutingPermissions", {
77 defaultValue: () => ({
78 get: () => Effect.succeed("off"),
79 changes: Stream.succeed([]),
80 set: () =>
81 Effect.fail(
82 new ConnectionBlockedError({
83 reason: "unsupported",
84 detail: "GitHub routing preferences are unavailable on this client.",
85 }),
86 ),
87 forget: () => Effect.void,
88 }),
89}) {}
90
91export const makeGitHubRoutingPermissions = Effect.fn("makeGitHubRoutingPermissions")(
92 function* (storage: {
93 readonly read: Effect.Effect<
94 ReadonlyArray<StoredGitHubRoutingPermission>,
95 ConnectionAttemptError
96 >;
97 readonly write: (
98 permissions: ReadonlyArray<StoredGitHubRoutingPermission>,
99 ) => Effect.Effect<void, ConnectionAttemptError>;
100 }) {
101 const state = yield* SubscriptionRef.make(yield* storage.read);
102 const lock = yield* Semaphore.make(1);
103 const update = (
104 transform: (
105 current: ReadonlyArray<StoredGitHubRoutingPermission>,
106 ) => ReadonlyArray<StoredGitHubRoutingPermission>,
107 ) =>
108 lock.withPermits(1)(
109 Effect.gen(function* () {
110 const current = yield* SubscriptionRef.get(state);
111 const next = transform(current);
112 if (next === current) return;
113 yield* storage.write(next);
114 yield* SubscriptionRef.set(state, next);
115 }),
116 );
117 return GitHubRoutingPermissions.of({
118 get: (entry) =>
119 SubscriptionRef.get(state).pipe(
120 Effect.map((permissions) => gitHubRoutingPermissionFor(entry, permissions)),
121 ),
122 changes: SubscriptionRef.changes(state),
123 set: (entry, permission) => {
124 const connectionKey = gitHubRoutingConnectionKey(entry);
125 if (connectionKey === null)
126 return Effect.fail(
127 new ConnectionBlockedError({
128 reason: "configuration",
129 detail: "This environment does not have a saved connection endpoint.",
130 }),
131 );
132 return update((current) => [
133 ...current.filter((value) => value.environmentId !== entry.target.environmentId),
134 ...(permission === "off"
135 ? []
136 : [{ environmentId: entry.target.environmentId, connectionKey, permission }]),
137 ]);
138 },
139 forget: (environmentId) =>
140 update((current) =>
141 current.some((permission) => permission.environmentId === environmentId)
142 ? current.filter((permission) => permission.environmentId !== environmentId)
143 : current,
144 ),
145 });
146 },
147);