Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open
2// flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose.
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5
6import {
7 type DefaultAppearancePreference,
8 EnvironmentTheme,
9 type ServerSettingsError,
10 EnvironmentThemeFile,
11 EnvironmentThemeId,
12 environmentThemeFileHasColors,
13 THEME_CSS_MAX_LENGTH,
14} from "@t3tools/contracts";
15import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
16import { themeCssLoadsRemoteFiles } from "@t3tools/shared/themeCss";
17import {
18 MOBILE_DEFAULT_THEME_ID,
19 MOBILE_THEME_IDS,
20 UNPUBLISHABLE_THEME_IDS,
21} from "@t3tools/shared/themePalettes";
22import * as Cause from "effect/Cause";
23import * as Context from "effect/Context";
24import * as DateTime from "effect/DateTime";
25import * as Deferred from "effect/Deferred";
26import * as Duration from "effect/Duration";
27import * as Effect from "effect/Effect";
28import * as Equal from "effect/Equal";
29import * as Exit from "effect/Exit";
30import * as FileSystem from "effect/FileSystem";
31import * as Layer from "effect/Layer";
32import * as Option from "effect/Option";
33import * as PubSub from "effect/PubSub";
34import * as Ref from "effect/Ref";
35import * as Schema from "effect/Schema";
36import * as Semaphore from "effect/Semaphore";
37import * as Scope from "effect/Scope";
38import * as Stream from "effect/Stream";
39import { lock } from "proper-lockfile";
40
41import * as ServerConfig from "./config.ts";
42import * as ServerSettings from "./serverSettings.ts";
43import { watchDirectoryPath } from "./watchDirectoryReplacements.ts";
44
45const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
46 Schema.fromJsonString(EnvironmentThemeFile),
47);
48const encodeEnvironmentThemeFileJson = Schema.encodeEffect(
49 fromJsonStringPretty(EnvironmentThemeFile),
50);
51const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
52
53const THEME_FILE_SUFFIX = ".json";
54
55const MAX_THEME_FILES = 32;
56/**
57 * Shared with publishing so it cannot accept files the watcher skips. Fits the longest CSS in any
58 * JSON encoding, at up to 6 bytes per character for a `\uXXXX` escape, plus the colors.
59 */
60export const MAX_THEME_FILE_BYTES = 6 * THEME_CSS_MAX_LENGTH + 16 * 1024;
61// Clients cache every published theme in localStorage, which holds about 5 MB per origin.
62const MAX_THEME_TOTAL_BYTES = 2 * 1024 * 1024;
63
64/** A theme's background is `<id>.<extension>` beside `<id>.json`; earlier extensions win. */
65const THEME_BACKGROUND_EXTENSIONS = ["webp", "png", "jpg", "jpeg"] as const;
66const MAX_THEME_BACKGROUND_BYTES = 16 * 1024 * 1024;
67
68interface PublishedThemes {
69 readonly seq: number;
70 readonly themes: ReadonlyArray<EnvironmentTheme>;
71}
72
73const INVALID_ID =
74 "is not a valid theme id. Use lowercase letters, digits, and hyphens, and not a built-in name.";
75const NOT_PUBLISHED = "could not be published. The themes directory may be full or not writable.";
76
77/** A theme the service will not publish or select. `problem` ends the sentence naming it. */
78export class EnvironmentThemeRefusedError extends Schema.TaggedError<EnvironmentThemeRefusedError>()(
79 "EnvironmentThemeRefusedError",
80 {
81 themeId: Schema.String,
82 problem: Schema.String,
83 known: Schema.optional(Schema.Array(Schema.String)),
84 cause: Schema.optional(Schema.Defect()),
85 },
86) {
87 override get message(): string {
88 const known = this.known ? ` Available: ${this.known.join(", ")}.` : "";
89 return `Theme "${this.themeId}" ${this.problem}${known}`;
90 }
91}
92
93/**
94 * Hold through the settings write so CLI and server publishers share one catalog snapshot.
95 * Returns a guard that skips a rollback once a stalled holder has lost the lock to another.
96 */
97export const acquireThemePublishLock = Effect.fn("EnvironmentTheme.acquirePublishLock")(function* (
98 themesDir: string,
99 themeId: string,
100) {
101 const fs = yield* FileSystem.FileSystem;
102 yield* fs
103 .makeDirectory(themesDir, { recursive: true })
104 .pipe(
105 Effect.mapError(
106 (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
107 ),
108 );
109 let compromised = false;
110 yield* Effect.acquireRelease(
111 Effect.tryPromise({
112 try: () =>
113 lock(themesDir, {
114 lockfilePath: NodePath.join(themesDir, ".t3-theme-publish.lock"),
115 stale: 60_000,
116 onCompromised: () => {
117 compromised = true;
118 },
119 }),
120 catch: (cause) =>
121 new EnvironmentThemeRefusedError({
122 themeId,
123 problem:
124 (cause as { code?: unknown } | null)?.code === "ELOCKED"
125 ? "could not be published because the themes directory is busy. Try again."
126 : NOT_PUBLISHED,
127 cause,
128 }),
129 }),
130 (release) => Effect.promise(() => release().catch(() => undefined)),
131 );
132 return (rollback: Effect.Effect<void>) =>
133 Effect.suspend(() => (compromised ? Effect.void : rollback));
134});
135
136/** The settings write that makes a theme or mode the default failed. */
137export class EnvironmentThemeNotSelectedError extends Schema.TaggedError<EnvironmentThemeNotSelectedError>()(
138 "EnvironmentThemeNotSelectedError",
139 {
140 /** Absent when only the appearance was set. */
141 themeId: Schema.optional(Schema.String),
142 cause: Schema.Defect(),
143 },
144) {
145 override get message(): string {
146 const subject = this.themeId === undefined ? "The appearance" : `Theme "${this.themeId}"`;
147 return `${subject} was not applied, because the settings could not be saved.`;
148 }
149}
150
151export class EnvironmentThemeService extends Context.Service<
152 EnvironmentThemeService,
153 {
154 readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
155
156 /** The default theme id and the published themes, plus the one named `themeId`. */
157 readonly read: (themeId?: string) => Effect.Effect<
158 {
159 readonly current: string;
160 /** Where theme files and their background images live. */
161 readonly themesDir: string;
162 readonly themes: ReadonlyArray<EnvironmentTheme>;
163 readonly theme?: EnvironmentTheme;
164 },
165 EnvironmentThemeRefusedError | ServerSettingsError
166 >;
167
168 /**
169 * Makes `themeId` the environment theme and `appearance` its mode, so connected clients
170 * switch to them. With `theme`, first publishes that file under the id, replacing one already
171 * there.
172 */
173 readonly apply: (
174 input:
175 | {
176 readonly themeId: string;
177 readonly theme?: EnvironmentThemeFile | undefined;
178 readonly appearance?: Exclude<DefaultAppearancePreference, ""> | undefined;
179 }
180 | { readonly appearance: Exclude<DefaultAppearancePreference, ""> },
181 ) => Effect.Effect<void, EnvironmentThemeRefusedError | EnvironmentThemeNotSelectedError>;
182
183 /** Subscribes before reading to retain changes during connection. */
184 readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
185 }
186>()("t3/environmentTheme/EnvironmentThemeService") {}
187
188/** True when anything, a dangling symlink included, is at the path. */
189const pathIsTaken = (filePath: string): boolean => {
190 try {
191 NodeFS.lstatSync(filePath);
192 return true;
193 } catch {
194 return false;
195 }
196};
197
198/** Validates and reads one handle; rejects symlinked files, allows symlinked directories.
199 * Uses non-blocking opens against FIFOs; Windows lacks these flags and checks symlinks with lstat. */
200export const readThemeFileGuarded = (
201 filePath: string,
202 maxBytes: number,
203 onMissing?: () => void,
204): string | null => {
205 let fd: number;
206 try {
207 if (NodeFS.constants.O_NOFOLLOW === undefined && NodeFS.lstatSync(filePath).isSymbolicLink()) {
208 return null;
209 }
210 fd = NodeFS.openSync(
211 filePath,
212 NodeFS.constants.O_RDONLY |
213 (NodeFS.constants.O_NOFOLLOW ?? 0) |
214 (NodeFS.constants.O_NONBLOCK ?? 0),
215 );
216 } catch (error) {
217 if ((error as NodeJS.ErrnoException).code === "ENOENT") onMissing?.();
218 return null;
219 }
220 try {
221 const info = NodeFS.fstatSync(fd);
222 if (!info.isFile() || info.size > maxBytes) return null;
223 const contents = Buffer.alloc(info.size);
224 let offset = 0;
225 while (offset < contents.length) {
226 const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);
227 if (read <= 0) break;
228 offset += read;
229 }
230 // Unlike Buffer#toString, TextDecoder drops a UTF-8 BOM, which JSON.parse rejects.
231 return new TextDecoder().decode(contents.subarray(0, offset));
232 } catch {
233 return null;
234 } finally {
235 NodeFS.closeSync(fd);
236 }
237};
238
239/**
240 * The background image published beside `themeId`, if any. Symlinks and oversized files are
241 * skipped. `entries` lets a directory scan skip lookups for names it did not list.
242 */
243export function findThemeBackground(
244 themesDir: string,
245 themeId: string,
246 entries?: ReadonlySet<string>,
247): { readonly path: string; readonly revision: string } | null {
248 for (const extension of THEME_BACKGROUND_EXTENSIONS) {
249 const name = `${themeId}.${extension}`;
250 if (entries !== undefined && !entries.has(name)) continue;
251 // Native separators: the asset route refuses a path that differs from its canonical form.
252 const filePath = NodePath.join(themesDir, name);
253 let info: NodeFS.BigIntStats;
254 try {
255 info = NodeFS.lstatSync(filePath, { bigint: true });
256 } catch {
257 continue;
258 }
259 if (!info.isFile() || info.size > MAX_THEME_BACKGROUND_BYTES) continue;
260 return {
261 path: filePath,
262 revision: [info.ino, info.size, info.mtimeNs].map((part) => part.toString(36)).join("-"),
263 };
264 }
265 return null;
266}
267
268export const readPublishedThemes = Effect.fn(function* (
269 themesDir: string,
270 /** Runs when the directory or a file it listed is gone, as when an ancestor moves mid-read. */
271 onPathMissing: Effect.Effect<void> = Effect.void,
272) {
273 const fs = yield* FileSystem.FileSystem;
274 const entries = yield* Effect.catch(fs.readDirectory(themesDir), (error) =>
275 Effect.as(error.reason._tag === "NotFound" ? onPathMissing : Effect.void, []),
276 );
277 let listedFileMissing = false;
278 const markListedFileMissing = () => {
279 listedFileMissing = true;
280 };
281
282 const themes: Array<EnvironmentTheme> = [];
283 const entryNames = new Set(entries);
284 let examined = 0;
285 let totalBytes = 0;
286 for (const entry of entries.toSorted()) {
287 if (!entry.endsWith(THEME_FILE_SUFFIX)) continue;
288 const id = entry.slice(0, -THEME_FILE_SUFFIX.length);
289 // Reserved ids shadow built-ins or capture clients that never chose them.
290 if (!isEnvironmentThemeId(id) || UNPUBLISHABLE_THEME_IDS.has(id)) continue;
291
292 // Cap examined files, not accepted themes, to bound work on malformed directories.
293 examined += 1;
294 if (examined > MAX_THEME_FILES) {
295 yield* Effect.logWarning("ignoring environment theme files past the limit", {
296 path: themesDir,
297 limit: MAX_THEME_FILES,
298 });
299 break;
300 }
301
302 const filePath = `${themesDir}/${entry}`;
303 const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES, markListedFileMissing);
304 if (raw === null) {
305 yield* Effect.logWarning("ignoring unusable environment theme file", {
306 path: filePath,
307 limit: MAX_THEME_FILE_BYTES,
308 });
309 continue;
310 }
311 if (raw.trim().length === 0) continue;
312
313 const decoded = decodeEnvironmentThemeFileJsonExit(raw);
314 if (decoded._tag === "Failure") {
315 yield* Effect.logWarning("ignoring invalid environment theme", {
316 path: filePath,
317 detail: Cause.pretty(decoded.cause),
318 });
319 continue;
320 }
321 const file = decoded.value;
322 if (!environmentThemeFileHasColors(file)) {
323 yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });
324 continue;
325 }
326
327 totalBytes += Buffer.byteLength(raw);
328 if (totalBytes > MAX_THEME_TOTAL_BYTES) {
329 yield* Effect.logWarning("ignoring environment themes past the total size limit", {
330 path: themesDir,
331 limit: MAX_THEME_TOTAL_BYTES,
332 });
333 break;
334 }
335
336 const background = findThemeBackground(themesDir, id, entryNames);
337 themes.push({ id, ...file, ...(background ? { background: background.revision } : {}) });
338 }
339 if (listedFileMissing) yield* onPathMissing;
340 return themes;
341});
342
343const make = Effect.gen(function* () {
344 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
345 const fs = yield* FileSystem.FileSystem;
346 const settings = yield* ServerSettings.ServerSettingsService;
347 // Sequence numbers let subscribers drop queued events older than their initial snapshot.
348 const changes = yield* PubSub.sliding<PublishedThemes>(1);
349 const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
350 const pathMissing = yield* Ref.make(false);
351 // Serialize read/compare/publish so slow older reads cannot publish with newer sequence numbers.
352 const refreshSemaphore = yield* Semaphore.make(1);
353 const watcherScope = yield* Scope.make("sequential");
354 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
355
356 const refresh = refreshSemaphore.withPermits(1)(
357 Effect.gen(function* () {
358 const themes = yield* readPublishedThemes(
359 environmentThemesDir,
360 Ref.set(pathMissing, true),
361 ).pipe(Effect.provideService(FileSystem.FileSystem, fs));
362 // Compare the whole value so new fields cannot silently miss republishes.
363 const [changed, next] = yield* Ref.modify(
364 published,
365 (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {
366 if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];
367 const updated: PublishedThemes = { seq: previous.seq + 1, themes };
368 return [[true, updated], updated];
369 },
370 );
371 if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);
372 return next;
373 }),
374 );
375
376 yield* fs
377 .makeDirectory(environmentThemesDir, { recursive: true })
378 .pipe(Effect.ignoreCause({ log: true }));
379
380 const watchDirectory = (directory: string) =>
381 Stream.unwrap(
382 Effect.gen(function* () {
383 const ready = yield* Deferred.make<void>();
384 const markReady = () => Deferred.doneUnsafe(ready, Exit.void);
385 const events = fs.watch(directory, { onReady: markReady }).pipe(
386 Stream.as(undefined),
387 Stream.catchIf(
388 (error) => error.reason._tag === "NotFound",
389 () => Stream.empty,
390 ),
391 Stream.ignoreCause({ log: true }),
392 Stream.ensuring(Effect.sync(markReady)),
393 );
394 return Stream.merge(events, Stream.fromEffect(Deferred.await(ready)));
395 }),
396 );
397
398 const watchEvents = watchDirectoryPath(
399 environmentThemesDir,
400 watchDirectory(environmentThemesDir),
401 Ref.getAndSet(pathMissing, false),
402 ).pipe(
403 // A save emits several events, and fs.watch can fire before content is flushed.
404 Stream.debounce(Duration.millis(100)),
405 );
406
407 yield* refresh;
408 yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
409 Effect.ignoreCause({ log: true }),
410 Effect.forkIn(watcherScope),
411 Effect.asVoid,
412 );
413
414 // One publish at a time: they share a staging path, and each one checks what is served after it.
415 const publishSemaphore = yield* Semaphore.make(1);
416
417 /** Callers hold `publishSemaphore`. Succeeds with the effect that undoes this publish. */
418
419 const publish = Effect.fnUntraced(function* (themeId: string, file: EnvironmentThemeFile) {
420 if (UNPUBLISHABLE_THEME_IDS.has(themeId)) {
421 return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
422 }
423 if (!environmentThemeFileHasColors(file)) {
424 return yield* new EnvironmentThemeRefusedError({
425 themeId,
426 problem: "has no colors. Give canvas and accent, or at least one color role.",
427 });
428 }
429 if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {
430 return yield* new EnvironmentThemeRefusedError({
431 themeId,
432 problem:
433 "has CSS that loads files. Remove @import, image-set(), and url() that is not data: or #id.",
434 });
435 }
436 const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(
437 Effect.mapError(
438 (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
439 ),
440 );
441 if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) {
442 return yield* new EnvironmentThemeRefusedError({
443 themeId,
444 problem: `is larger than ${MAX_THEME_FILE_BYTES} bytes.`,
445 });
446 }
447
448 const whileLocked = yield* acquireThemePublishLock(environmentThemesDir, themeId).pipe(
449 Effect.provideService(FileSystem.FileSystem, fs),
450 );
451 const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;
452 // The watcher reads only .json names, so it never sees a half-written file.
453 const staging = `${destination}.staging-${process.pid}`;
454 // Exclusive create: a link left at the staging path is removed, never written through.
455 const replace = (next: string) =>
456 fs.remove(staging, { force: true }).pipe(
457 Effect.andThen(fs.writeFileString(staging, next, { flag: "wx" })),
458 Effect.andThen(fs.rename(staging, destination)),
459 Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),
460 );
461
462 // The guarded reader does not block on a FIFO and does not follow a symlink.
463 const previous = Option.fromNullOr(readThemeFileGuarded(destination, MAX_THEME_FILE_BYTES));
464 // A file it cannot read back, such as one over the size limit, could not be restored.
465 if (Option.isNone(previous) && pathIsTaken(destination)) {
466 return yield* new EnvironmentThemeRefusedError({
467 themeId,
468 problem: "would replace a file that could not be backed up. Use another theme id.",
469 });
470 }
471 const servedBefore = (yield* refresh).themes.map((theme) => theme.id);
472 // Puts back what was there, so a failed apply does not take a working theme away.
473 const revert = Option.match(previous, {
474 onNone: () => fs.remove(destination, { force: true }),
475 onSome: replace,
476 }).pipe(Effect.ignore, whileLocked, Effect.andThen(refresh), Effect.asVoid);
477
478 yield* replace(contents).pipe(
479 Effect.mapError(
480 (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
481 ),
482 );
483 // The reader stops at its count and size limits, so this file can go unserved, or it can
484 // push another theme out. Both count as a failed publish.
485 const served = new Set((yield* refresh).themes.map((theme) => theme.id));
486 if (served.has(themeId) && servedBefore.every((id) => served.has(id))) return revert;
487 yield* revert;
488 return yield* new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED });
489 });
490
491 const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(
492 "EnvironmentThemeService.apply",
493 )(function* (input) {
494 const themeId = "themeId" in input ? input.themeId : undefined;
495 const theme = "theme" in input ? input.theme : undefined;
496 const { appearance } = input;
497 if (themeId !== undefined && !isEnvironmentThemeId(themeId)) {
498 return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
499 }
500 // Timestamps make clients apply a set again when its value did not change. Theme and
501 // appearance have one each, so setting one does not undo a later local choice of the other.
502 // The stock theme is an empty default with a set time, which clients adopt as stock.
503 const defaultTheme = themeId === MOBILE_DEFAULT_THEME_ID ? "" : themeId;
504 const select = Effect.gen(function* () {
505 const setAt = DateTime.formatIso(yield* DateTime.now);
506 yield* settings
507 .updateSettings({
508 ...(defaultTheme === undefined ? {} : { defaultTheme, defaultThemeSetAt: setAt }),
509 ...(appearance === undefined
510 ? {}
511 : { defaultAppearance: appearance, defaultAppearanceSetAt: setAt }),
512 })
513 .pipe(Effect.mapError((cause) => new EnvironmentThemeNotSelectedError({ themeId, cause })));
514 });
515 // One at a time, so a selection never sees a file that a failed publish then takes back.
516 // If the theme cannot be selected, the file it replaced comes back.
517 yield* publishSemaphore.withPermits(1)(
518 Effect.gen(function* () {
519 if (themeId === undefined) return yield* select;
520 if (theme === undefined) {
521 const known = [...MOBILE_THEME_IDS, ...(yield* refresh).themes.map(({ id }) => id)];
522 if (!known.includes(themeId)) {
523 return yield* new EnvironmentThemeRefusedError({
524 themeId,
525 problem: "is not a built-in or published theme.",
526 known,
527 });
528 }
529 return yield* select;
530 }
531 const revert = yield* publish(themeId, theme);
532 yield* select.pipe(Effect.tapError(() => revert));
533 }).pipe(Effect.scoped),
534 );
535 });
536
537 const read: EnvironmentThemeService["Service"]["read"] = Effect.fn(
538 "EnvironmentThemeService.read",
539 )(function* (themeId) {
540 const { themes } = yield* refresh;
541 const { defaultTheme } = yield* settings.getSettings;
542 const themesDir = environmentThemesDir;
543 if (themeId === undefined) return { current: defaultTheme, themesDir, themes };
544 const theme = themes.find((candidate) => candidate.id === themeId);
545 if (theme === undefined) {
546 return yield* new EnvironmentThemeRefusedError({
547 themeId,
548 problem: "is not a published theme.",
549 known: themes.map(({ id }) => id),
550 });
551 }
552 return { current: defaultTheme, themesDir, themes, theme };
553 });
554
555 return {
556 current: Effect.map(refresh, (state) => state.themes),
557 read,
558 apply,
559 get streamChanges() {
560 return Stream.unwrap(
561 Effect.gen(function* () {
562 const subscription = yield* PubSub.subscribe(changes);
563 const snapshot = yield* refresh;
564 return Stream.concat(
565 Stream.make(snapshot.themes),
566 Stream.fromSubscription(subscription).pipe(
567 Stream.filter((update) => update.seq > snapshot.seq),
568 Stream.map((update) => update.themes),
569 ),
570 );
571 }),
572 );
573 },
574 } satisfies EnvironmentThemeService["Service"];
575});
576
577export const layer = Layer.effect(EnvironmentThemeService, make);