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

AcpRegistryAuthenticationState.ts

85 lines3.4 KB

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