Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpRegistryAuthenticationState.ts

79 lines3.1 KB

1import * as NodeCrypto from "node:crypto";
2import type {
3 AcpRegistrySettings,
4 ProviderInstanceEnvironment,
5 ProviderInstanceId,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Ref from "effect/Ref";
11import * as Schema from "effect/Schema";
12import * as Semaphore from "effect/Semaphore";
13​
14import { writeFileStringAtomically } from "../../atomicWrite.ts";
15​
16const decodeState = Schema.decodeUnknownEffect(
17 Schema.fromJsonString(Schema.Struct({ binding: Schema.String, authenticated: Schema.Boolean })),
18);
19const hash = (value: unknown) =>
20 NodeCrypto.createHash("sha256").update(JSON.stringify(value)).digest("hex");
21​
22/** Remember explicit sign-in success, never discovery success or the agent's credentials. */
23export const makeAcpRegistryAuthenticationState = Effect.fn("makeAcpRegistryAuthenticationState")(
24 function* (input: {
25 readonly cacheDir: string;
26 readonly instanceId: ProviderInstanceId;
27 readonly settings: AcpRegistrySettings;
28 readonly environment: ProviderInstanceEnvironment;
29 readonly processEnvironment: NodeJS.ProcessEnv;
30 }) {
31 const fs = yield* FileSystem.FileSystem;
32 const path = yield* Path.Path;
33 const filePath = path.join(input.cacheDir, `acp-auth-${hash(input.instanceId)}.json`);
34 // Cosmetic settings and model discovery can rebuild the driver without
35 // changing the account. Credential overrides and profile paths cannot.
36 const binding = hash({
37 ...(input.settings.source === "local"
38 ? { source: "local", commandArgs: input.settings.commandArgs }
39 : {}),
40 agentId: input.settings.agentId,
41 commandPath: input.settings.commandPath,
42 distribution: input.settings.distribution,
43 authMethodId: input.settings.authMethodId,
44 environment: [...input.environment].toSorted((a, b) => a.name.localeCompare(b.name)),
45 profiles: [
46 "HOME",
47 "XDG_CONFIG_HOME",
48 "XDG_DATA_HOME",
49 "XDG_STATE_HOME",
50 "APPDATA",
51 "LOCALAPPDATA",
52 ].map((name) => input.processEnvironment[name] ?? null),
53 });
54 const saved = yield* fs.readFileString(filePath).pipe(
55 Effect.flatMap(decodeState),
56 Effect.orElseSucceed(() => undefined),
57 );
58 const confirmed = yield* Ref.make(saved?.binding === binding && saved.authenticated);
59 const lock = yield* Semaphore.make(1);
60 const persist = (authenticated: boolean) =>
61 writeFileStringAtomically({
62 filePath,
63 contents: JSON.stringify({ binding, authenticated }),
64 }).pipe(
65 Effect.provideService(FileSystem.FileSystem, fs),
66 Effect.provideService(Path.Path, path),
67 Effect.tapError(() => Effect.logWarning("Could not save ACP sign-in confirmation.")),
68 Effect.ignore,
69 );
70 if (saved && saved.binding !== binding) yield* persist(false);
71 return {
72 get: Ref.get(confirmed),
73 set: (authenticated: boolean) =>
74 lock.withPermit(
75 Ref.set(confirmed, authenticated).pipe(Effect.andThen(persist(authenticated))),
76 ),
77 };
78 },
79);