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

clientConfig.ts

130 lines5.5 KB

1// @effect-diagnostics nodeBuiltinImport:off - one sha256 over two strings; Effect.Crypto is async and the digest feeds a synchronous Output.map.
2import * as NodeCrypto from "node:crypto";
3​
4import * as Alchemy from "alchemy";
5import * as Config from "effect/Config";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Redacted from "effect/Redacted";
12import * as Schema from "effect/Schema";
13​
14export interface RelayClientConfig {
15 readonly url: string | undefined;
16 readonly mobileTracingUrl: string;
17 readonly mobileTracingDataset: string;
18 readonly mobileTracingToken: Redacted.Redacted<string>;
19 readonly clientTracingUrl: string;
20 readonly clientTracingDataset: string;
21 readonly clientTracingToken: Redacted.Redacted<string>;
22 /**
23 * Alchemy decides whether an Action runs by hashing `JSON.stringify` of its
24 * input, and a Redacted stringifies as `<redacted>`, so a rotated token
25 * alone would never re-run it. A digest of both tokens makes the input
26 * change with them without persisting the secrets in the hash.
27 */
28 readonly tokenDigest: string;
30​
31export class RelayUrlUnavailableError extends Schema.TaggedError<RelayUrlUnavailableError>()(
32 "RelayUrlUnavailableError",
33 {},
34) {
35 override get message(): string {
36 return "The relay worker has no URL yet; deploy again once the worker exists.";
37 }
39​
40export const relayClientConfigEnv = (config: RelayClientConfig & { readonly url: string }) =>
41 ({
42 T3CODE_RELAY_URL: config.url,
43 T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,
44 T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,
45 T3CODE_MOBILE_OTLP_TRACES_TOKEN: Redacted.value(config.mobileTracingToken),
46 T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,
47 T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,
48 T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: Redacted.value(config.clientTracingToken),
49 }) as const;
50​
51export class EnvValueNotSingleLineError extends Schema.TaggedError<EnvValueNotSingleLineError>()(
52 "EnvValueNotSingleLineError",
53 { name: Schema.String },
54) {
55 override get message(): string {
56 return `${this.name} contains a line break and cannot be written as one .env assignment.`;
57 }
59​
60/**
61 * Every existing line for a name is dropped, not just the first: the file is
62 * read with `parseEnv`, where the last duplicate wins, so a stale second copy
63 * would override the value just written.
64 */
65export function reconcileEnvFile(
66 contents: string,
67 entries: Readonly<Record<string, string>>,
68): string {
69 const lines = contents === "" ? [] : contents.replace(/\n$/u, "").split("\n");
70 const assignment = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/u;
71 const pending = new Map(Object.entries(entries));
72 const out: string[] = [];
73 for (let index = 0; index < lines.length; index += 1) {
74 const line = lines[index]!;
75 const match = assignment.exec(line);
76 const name = match?.[1];
77 if (match === null || name === undefined || !(name in entries)) {
78 out.push(line);
79 continue;
80 }
81 // A quoted value can span lines; skip to its closing quote so the
82 // continuation lines go with the assignment they belong to. With no
83 // closing quote in the file, parseEnv treats the opening line as the
84 // whole value, so nothing after it is consumed.
85 const rawValue = match[2] ?? "";
86 const quote = /^(['"`])/u.exec(rawValue)?.[1];
87 if (quote !== undefined && !closesQuote(rawValue, quote)) {
88 const closing = lines.findIndex((candidate, at) => at > index && candidate.includes(quote));
89 if (closing !== -1) index = closing;
90 }
91 const value = pending.get(name);
92 if (value !== undefined) {
93 out.push(`${name}=${value}`);
94 pending.delete(name);
95 }
96 }
97 for (const [name, value] of pending) out.push(`${name}=${value}`);
98 return out.length === 0 ? "" : `${out.join("\n")}\n`;
100​
101const closesQuote = (value: string, quote: string): boolean =>
102 value.length > 1 && value.slice(1).includes(quote);
103​
104export const tokenDigest = (tokens: ReadonlyArray<Redacted.Redacted<string>>): string =>
105 NodeCrypto.createHash("sha256").update(tokens.map(Redacted.value).join("\n")).digest("hex");
106​
107export const PublishClientConfig = Alchemy.Action(
108 "PublishClientConfig",
109 Effect.gen(function* () {
110 const fs = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const override = yield* Config.String("T3CODE_RELAY_CLIENT_CONFIG_ENV").pipe(Config.option);
113 const repoRootEnv = path.fromFileUrl(new URL("../../../.env", import.meta.url));
114 const target = Option.isSome(override) ? override.value : yield* repoRootEnv;
115 return Effect.fn(function* (input: RelayClientConfig) {
116 const url = input.url;
117 if (url === undefined) return yield* new RelayUrlUnavailableError();
118 const entries = relayClientConfigEnv({ ...input, url });
119 // Provider responses are copied in verbatim; a line break in one would
120 // become an extra assignment.
121 for (const [name, value] of Object.entries(entries)) {
122 if (/[\r\n]/u.test(value)) return yield* new EnvValueNotSingleLineError({ name });
123 }
124 const existing = (yield* fs.exists(target)) ? yield* fs.readFileString(target) : "";
125 yield* fs.writeFileString(target, reconcileEnvFile(existing, entries));
126 yield* Console.log(`Wrote relay client configuration to ${target}`);
127 return { path: target };
128 });
129 }),
130);