Open History to see the last commit
1/**
2 * Standalone issue trackers as Settings manages them: one credential per tracker account in the
3 * secret store, and the per-project binding that puts an account's scope beside the project's
4 * git-host issues. A tracker's first account predates accounts and has no id; each added one
5 * gets its own. Disconnecting an account clears the bindings that pointed at it.
6 */
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Semaphore from "effect/Semaphore";
12import * as DateTime from "effect/DateTime";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import {
15 IssueTrackerAccountId,
16 IssueTrackerConnectionError,
17 IssueTrackerKind,
18 type IssueTrackerBindProjectInput,
19 type IssueTrackerConnectInput,
20 type IssueTrackerConnection,
21 type IssueTrackerConnectionList,
22} from "@t3tools/contracts";
23import type {
24 IssueTrackerCredential,
25 StandaloneIssueTrackerApi,
26} from "@t3tools/source-control-core/server/IssueTracker";
27
28import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
29import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
30import * as IssueService from "./IssueService.ts";
31import {
32 decodeIssueTrackerCredential,
33 encodeIssueTrackerCredential,
34 issueTrackerSecretName,
35} from "./IssueTrackerHostLive.ts";
36import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
37
38const decoder = new TextDecoder();
39
40export class IssueTrackerConnections extends Context.Service<
41 IssueTrackerConnections,
42 {
43 /** Every standalone tracker account, each probed against its stored credential, and the bindings. */
44 readonly list: Effect.Effect<IssueTrackerConnectionList, IssueTrackerConnectionError>;
45 /**
46 * Vets the credential with the tracker and stores it only when the tracker accepts it. A null
47 * token removes the stored one and unbinds every project that pointed at the account.
48 */
49 readonly connect: (
50 input: IssueTrackerConnectInput,
51 ) => Effect.Effect<IssueTrackerConnection, IssueTrackerConnectionError>;
52 /** Binds a project to one of an account's scopes, or unbinds it with a null binding. */
53 readonly bindProject: (
54 input: IssueTrackerBindProjectInput,
55 ) => Effect.Effect<void, IssueTrackerConnectionError>;
56 }
57>()("t3/issue/IssueTrackerConnections") {}
58
59const make = Effect.gen(function* () {
60 const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
61 const secrets = yield* ServerSecretStore.ServerSecretStore;
62 const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
63 // Account checks, credential writes, and removals run one at a time, so a removal cannot land
64 // between a check and the write that relied on it.
65 const accountLock = yield* Semaphore.make(1);
66 const random = yield* SecureRandom.SecureRandom;
67
68 const requireTracker = (
69 tracker: IssueTrackerKind,
70 ): Effect.Effect<StandaloneIssueTrackerApi, IssueTrackerConnectionError> => {
71 const found = registry.standalone.find((api) => api.kind === tracker);
72 return found === undefined
73 ? Effect.fail(
74 new IssueTrackerConnectionError({
75 tracker,
76 reason: "unknown-tracker",
77 detail: "This server has no such issue tracker.",
78 }),
79 )
80 : Effect.succeed(found);
81 };
82
83 /** The kind an error about no tracker in particular is filed under. */
84 const anyTracker = registry.standalone[0]?.kind ?? IssueTrackerKind.make("none");
85
86 const secretFailure = (tracker: IssueTrackerKind, detail: string) => (cause: unknown) =>
87 new IssueTrackerConnectionError({ tracker, reason: "failed", detail, cause });
88
89 const accountFields = (accountId: IssueTrackerAccountId | null) =>
90 accountId === null ? {} : { accountId };
91
92 const disconnected = (
93 api: StandaloneIssueTrackerApi,
94 accountId: IssueTrackerAccountId | null,
95 ): IssueTrackerConnection => ({
96 ...api.standalone,
97 ...accountFields(accountId),
98 connected: false,
99 account: null,
100 detail: null,
101 scopes: [],
102 });
103
104 const requireAccount = Effect.fn("IssueTrackerConnections.requireAccount")(function* (
105 tracker: IssueTrackerKind,
106 accountId: IssueTrackerAccountId | undefined,
107 ) {
108 if (accountId === undefined) return null;
109 const saved = yield* bindings.listAccounts.pipe(
110 Effect.mapError(secretFailure(tracker, "The saved accounts could not be read.")),
111 );
112 if (saved.some((account) => account.tracker === tracker && account.accountId === accountId))
113 return accountId;
114 return yield* new IssueTrackerConnectionError({
115 tracker,
116 reason: "failed",
117 detail: "This account is not saved on the server.",
118 });
119 });
120
121 /** The tracker's view of a stored credential; a refusal is status, not a failure. */
122 const status = (
123 api: StandaloneIssueTrackerApi,
124 accountId: IssueTrackerAccountId | null,
125 credential: IssueTrackerCredential,
126 ) =>
127 api.probeCredential(credential).pipe(
128 Effect.map((probe): IssueTrackerConnection => ({
129 ...api.standalone,
130 ...accountFields(accountId),
131 connected: true,
132 account: probe.account,
133 detail: null,
134 ...(probe.workspace === undefined ? {} : { workspace: probe.workspace }),
135 scopes: probe.scopes,
136 fields: credential.fields,
137 })),
138 Effect.catch((error) =>
139 Effect.succeed<IssueTrackerConnection>({
140 ...api.standalone,
141 ...accountFields(accountId),
142 connected: true,
143 account: null,
144 detail: IssueService.trackerDetail(error),
145 scopes: [],
146 fields: credential.fields,
147 }),
148 ),
149 );
150
151 const current = (api: StandaloneIssueTrackerApi, accountId: IssueTrackerAccountId | null) =>
152 secrets.get(issueTrackerSecretName(api.kind, accountId)).pipe(
153 Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")),
154 Effect.flatMap((stored) =>
155 Option.isNone(stored)
156 ? Effect.succeed(disconnected(api, accountId))
157 : status(api, accountId, decodeIssueTrackerCredential(stored.value)),
158 ),
159 );
160
161 const list: IssueTrackerConnections["Service"]["list"] = Effect.all({
162 trackers: Effect.forEach(registry.standalone, (api) => current(api, null), { concurrency: 4 }),
163 accounts: bindings.listAccounts.pipe(
164 Effect.mapError(secretFailure(anyTracker, "The saved accounts could not be read.")),
165 Effect.flatMap((accounts) =>
166 Effect.forEach(
167 accounts.flatMap((account) => {
168 const api = registry.standalone.find((tracker) => tracker.kind === account.tracker);
169 return api === undefined ? [] : [{ api, accountId: account.accountId }];
170 }),
171 ({ api, accountId }) => current(api, accountId),
172 { concurrency: 4 },
173 ),
174 ),
175 ),
176 bindings: bindings.list().pipe(
177 // No single tracker is at fault; the first registered one carries the report.
178 Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
179 ),
180 }).pipe(
181 Effect.map(({ trackers, accounts, bindings: bound }) => {
182 const all = [...bound];
183 return {
184 trackers,
185 accounts,
186 bindings: Object.fromEntries(all.filter(([, binding]) => binding.accountId === undefined)),
187 accountBindings: Object.fromEntries(
188 all.filter(([, binding]) => binding.accountId !== undefined),
189 ),
190 };
191 }),
192 );
193
194 const disconnect = Effect.fn("IssueTrackerConnections.disconnect")(function* (
195 api: StandaloneIssueTrackerApi,
196 accountId: IssueTrackerAccountId | null,
197 ) {
198 yield* secrets
199 .remove(issueTrackerSecretName(api.kind, accountId))
200 .pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be removed.")));
201 // Bindings to an account nobody is signed into would only produce errors in every listing.
202 yield* bindings
203 .removeAccount({ tracker: api.kind, accountId })
204 .pipe(Effect.mapError(secretFailure(api.kind, "The project bindings could not be cleared.")));
205 return disconnected(api, accountId);
206 });
207
208 /** Whether another of the tracker's accounts already holds this exact credential. */
209 const heldElsewhere = Effect.fn("IssueTrackerConnections.heldElsewhere")(function* (
210 api: StandaloneIssueTrackerApi,
211 accountId: IssueTrackerAccountId | null,
212 credential: IssueTrackerCredential,
213 ) {
214 const wanted = decoder.decode(encodeIssueTrackerCredential(credential));
215 const saved = yield* bindings.listAccounts.pipe(
216 Effect.mapError(secretFailure(api.kind, "The saved accounts could not be read.")),
217 );
218 const others = [
219 null,
220 ...saved
221 .filter((account) => account.tracker === api.kind)
222 .map((account) => account.accountId),
223 ].filter((other) => other !== accountId);
224 for (const other of others) {
225 const stored = yield* secrets
226 .get(issueTrackerSecretName(api.kind, other))
227 .pipe(Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")));
228 if (Option.isSome(stored) && decoder.decode(stored.value) === wanted) return true;
229 }
230 return false;
231 });
232
233 const connect: IssueTrackerConnections["Service"]["connect"] = Effect.fn(
234 "IssueTrackerConnections.connect",
235 )(function* (input) {
236 const api = yield* requireTracker(input.tracker);
237 const addAccount = input.addAccount === true;
238 const token = input.token;
239 if (token === null) {
240 if (addAccount) {
241 return yield* new IssueTrackerConnectionError({
242 tracker: input.tracker,
243 reason: "failed",
244 detail: "A new account needs a credential.",
245 });
246 }
247 return yield* accountLock.withPermits(1)(
248 Effect.flatMap(requireAccount(api.kind, input.accountId), (existing) =>
249 disconnect(api, existing),
250 ),
251 );
252 }
253 const wanted = api.standalone.credential.fields ?? [];
254 const missing = wanted.find((field) => input.fields?.[field.key] === undefined);
255 if (missing !== undefined) {
256 return yield* new IssueTrackerConnectionError({
257 tracker: input.tracker,
258 reason: "rejected",
259 detail: `${api.standalone.displayName} needs its ${missing.label.toLowerCase()} too.`,
260 });
261 }
262 const credential: IssueTrackerCredential = {
263 token,
264 fields: Object.fromEntries(wanted.map((field) => [field.key, input.fields![field.key]!])),
265 };
266 // The tracker is asked before the lock, so a slow probe never holds up other settings.
267 const probed = yield* api.probeCredential(credential).pipe(
268 Effect.mapError(
269 (error) =>
270 new IssueTrackerConnectionError({
271 tracker: input.tracker,
272 reason: error.reason === "unauthenticated" ? "rejected" : "failed",
273 detail: IssueService.trackerDetail(error),
274 cause: error,
275 }),
276 ),
277 );
278 const accountId = yield* accountLock.withPermits(1)(
279 Effect.gen(function* () {
280 const accountId = addAccount
281 ? IssueTrackerAccountId.make(
282 yield* random
283 .uuidV4()
284 .pipe(
285 Effect.mapError(secretFailure(api.kind, "The account could not be created.")),
286 ),
287 )
288 : yield* requireAccount(api.kind, input.accountId);
289 if (yield* heldElsewhere(api, accountId, credential)) {
290 return yield* new IssueTrackerConnectionError({
291 tracker: input.tracker,
292 reason: "failed",
293 detail: "This credential is already connected as another account.",
294 });
295 }
296 yield* secrets
297 .set(
298 issueTrackerSecretName(api.kind, accountId),
299 encodeIssueTrackerCredential(credential),
300 )
301 .pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be stored.")));
302 if (addAccount && accountId !== null) {
303 const createdAt = DateTime.formatIso(yield* DateTime.now);
304 yield* bindings.addAccount({ tracker: api.kind, accountId, createdAt }).pipe(
305 Effect.tapError(() =>
306 Effect.ignore(secrets.remove(issueTrackerSecretName(api.kind, accountId))),
307 ),
308 Effect.mapError(secretFailure(api.kind, "The account could not be saved.")),
309 );
310 }
311 return accountId;
312 }),
313 );
314 return {
315 ...api.standalone,
316 ...accountFields(accountId),
317 connected: true,
318 account: probed.account,
319 detail: null,
320 ...(probed.workspace === undefined ? {} : { workspace: probed.workspace }),
321 scopes: probed.scopes,
322 fields: credential.fields,
323 };
324 });
325
326 const bindProject: IssueTrackerConnections["Service"]["bindProject"] = Effect.fn(
327 "IssueTrackerConnections.bindProject",
328 )(function* (input) {
329 if (input.binding === null) {
330 // Older clients cannot see a project bound with an added account and offer it as unbound;
331 // an unbind that does not name the binding's account leaves it alone.
332 const current = (yield* bindings
333 .list(input.projectId)
334 .pipe(
335 Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
336 )).get(input.projectId);
337 if (current !== undefined && current.accountId !== input.accountId) return;
338 } else {
339 yield* requireAccount(
340 (yield* requireTracker(input.binding.tracker)).kind,
341 input.binding.accountId,
342 );
343 }
344 // Unbinding names no tracker; the first registered one carries any report.
345 const tracker = input.binding?.tracker ?? anyTracker;
346 const updatedAt = DateTime.formatIso(yield* DateTime.now);
347 yield* bindings
348 .set({ projectId: input.projectId, binding: input.binding, updatedAt })
349 .pipe(Effect.mapError(secretFailure(tracker, "The project binding could not be saved.")));
350 }, accountLock.withPermits(1));
351
352 return IssueTrackerConnections.of({ list, connect, bindProject });
353});
354
355export const layer = Layer.effect(IssueTrackerConnections, make);