Open History to see the last commit
1import * as Crypto from "node:crypto";
2
3import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
4import * as PlatformError from "effect/PlatformError";
5
6import { ServerConfig } from "../../config.ts";
7import {
8 SecretStoreError,
9 ServerSecretStore,
10 type ServerSecretStoreShape,
11} from "../Services/ServerSecretStore.ts";
12
13export const makeServerSecretStore = Effect.gen(function* () {
14 const fileSystem = yield* FileSystem.FileSystem;
15 const path = yield* Path.Path;
16 const serverConfig = yield* ServerConfig;
17
18 yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
19 yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
20 Effect.mapError(
21 (cause) =>
22 new SecretStoreError({
23 message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
24 cause,
25 }),
26 ),
27 );
28
29 const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
30
31 const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
32 Predicate.isTagged(u, "PlatformError");
33
34 const get: ServerSecretStoreShape["get"] = (name) =>
35 fileSystem.readFile(resolveSecretPath(name)).pipe(
36 Effect.map((bytes) => Uint8Array.from(bytes)),
37 Effect.catch((cause) =>
38 cause.reason._tag === "NotFound"
39 ? Effect.succeed(null)
40 : Effect.fail(
41 new SecretStoreError({
42 message: `Failed to read secret ${name}.`,
43 cause,
44 }),
45 ),
46 ),
47 );
48
49 const set: ServerSecretStoreShape["set"] = (name, value) => {
50 const secretPath = resolveSecretPath(name);
51 const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
52 return Effect.gen(function* () {
53 yield* fileSystem.writeFile(tempPath, value);
54 yield* fileSystem.chmod(tempPath, 0o600);
55 yield* fileSystem.rename(tempPath, secretPath);
56 yield* fileSystem.chmod(secretPath, 0o600);
57 }).pipe(
58 Effect.catch((cause) =>
59 fileSystem.remove(tempPath).pipe(
60 Effect.ignore,
61 Effect.flatMap(() =>
62 Effect.fail(
63 new SecretStoreError({
64 message: `Failed to persist secret ${name}.`,
65 cause,
66 }),
67 ),
68 ),
69 ),
70 ),
71 );
72 };
73
74 const create: ServerSecretStoreShape["set"] = (name, value) => {
75 const secretPath = resolveSecretPath(name);
76 return Effect.scoped(
77 Effect.gen(function* () {
78 const file = yield* fileSystem.open(secretPath, {
79 flag: "wx",
80 mode: 0o600,
81 });
82 yield* file.writeAll(value);
83 yield* file.sync;
84 yield* fileSystem.chmod(secretPath, 0o600);
85 }),
86 ).pipe(
87 Effect.mapError(
88 (cause) =>
89 new SecretStoreError({
90 message: `Failed to persist secret ${name}.`,
91 cause,
92 }),
93 ),
94 );
95 };
96
97 const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
98 get(name).pipe(
99 Effect.flatMap((existing) => {
100 if (existing) {
101 return Effect.succeed(existing);
102 }
103
104 const generated = Crypto.randomBytes(bytes);
105 return create(name, generated).pipe(
106 Effect.as(Uint8Array.from(generated)),
107 Effect.catchTag("SecretStoreError", (error) =>
108 isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
109 ? get(name).pipe(
110 Effect.flatMap((created) =>
111 created !== null
112 ? Effect.succeed(created)
113 : Effect.fail(
114 new SecretStoreError({
115 message: `Failed to read secret ${name} after concurrent creation.`,
116 }),
117 ),
118 ),
119 )
120 : Effect.fail(error),
121 ),
122 );
123 }),
124 );
125
126 const remove: ServerSecretStoreShape["remove"] = (name) =>
127 fileSystem.remove(resolveSecretPath(name)).pipe(
128 Effect.catch((cause) =>
129 cause.reason._tag === "NotFound"
130 ? Effect.void
131 : Effect.fail(
132 new SecretStoreError({
133 message: `Failed to remove secret ${name}.`,
134 cause,
135 }),
136 ),
137 ),
138 );
139
140 return {
141 get,
142 set,
143 getOrCreateRandom,
144 remove,
145 } satisfies ServerSecretStoreShape;
146});
147
148export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);