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

authenticationState.ts

81 lines3.4 KB

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