Open History to see the last commit
1import * as Crypto from "node:crypto";
2
3import { Effect, FileSystem, Layer, Path } 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 isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
32 cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
33
34 const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
35 cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
36
37 const get: ServerSecretStoreShape["get"] = (name) =>
38 fileSystem.readFile(resolveSecretPath(name)).pipe(
39 Effect.map((bytes) => Uint8Array.from(bytes)),
40 Effect.catch((cause) =>
41 isMissingSecretFileError(cause)
42 ? Effect.succeed(null)
43 : Effect.fail(
44 new SecretStoreError({
45 message: `Failed to read secret ${name}.`,
46 cause,
47 }),
48 ),
49 ),
50 );
51
52 const set: ServerSecretStoreShape["set"] = (name, value) => {
53 const secretPath = resolveSecretPath(name);
54 const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
55 return Effect.gen(function* () {
56 yield* fileSystem.writeFile(tempPath, value);
57 yield* fileSystem.chmod(tempPath, 0o600);
58 yield* fileSystem.rename(tempPath, secretPath);
59 yield* fileSystem.chmod(secretPath, 0o600);
60 }).pipe(
61 Effect.catch((cause) =>
62 fileSystem.remove(tempPath).pipe(
63 Effect.ignore,
64 Effect.flatMap(() =>
65 Effect.fail(
66 new SecretStoreError({
67 message: `Failed to persist secret ${name}.`,
68 cause,
69 }),
70 ),
71 ),
72 ),
73 ),
74 );
75 };
76
77 const create: ServerSecretStoreShape["set"] = (name, value) => {
78 const secretPath = resolveSecretPath(name);
79 return Effect.scoped(
80 Effect.gen(function* () {
81 const file = yield* fileSystem.open(secretPath, {
82 flag: "wx",
83 mode: 0o600,
84 });
85 yield* file.writeAll(value);
86 yield* file.sync;
87 yield* fileSystem.chmod(secretPath, 0o600);
88 }),
89 ).pipe(
90 Effect.mapError(
91 (cause) =>
92 new SecretStoreError({
93 message: `Failed to persist secret ${name}.`,
94 cause,
95 }),
96 ),
97 );
98 };
99
100 const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
101 get(name).pipe(
102 Effect.flatMap((existing) => {
103 if (existing) {
104 return Effect.succeed(existing);
105 }
106
107 const generated = Crypto.randomBytes(bytes);
108 return create(name, generated).pipe(
109 Effect.as(Uint8Array.from(generated)),
110 Effect.catchTag("SecretStoreError", (error) =>
111 isAlreadyExistsSecretFileError(error.cause)
112 ? get(name).pipe(
113 Effect.flatMap((created) =>
114 created !== null
115 ? Effect.succeed(created)
116 : Effect.fail(
117 new SecretStoreError({
118 message: `Failed to read secret ${name} after concurrent creation.`,
119 }),
120 ),
121 ),
122 )
123 : Effect.fail(error),
124 ),
125 );
126 }),
127 );
128
129 const remove: ServerSecretStoreShape["remove"] = (name) =>
130 fileSystem.remove(resolveSecretPath(name)).pipe(
131 Effect.catch((cause) =>
132 isMissingSecretFileError(cause)
133 ? Effect.void
134 : Effect.fail(
135 new SecretStoreError({
136 message: `Failed to remove secret ${name}.`,
137 cause,
138 }),
139 ),
140 ),
141 );
142
143 return {
144 get,
145 set,
146 getOrCreateRandom,
147 remove,
148 } satisfies ServerSecretStoreShape;
149});
150
151export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);