Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Crypto from "effect/Crypto";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Predicate from "effect/Predicate";
9import * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11
12import * as ServerConfig from "../config.ts";
13
14const secretStoreErrorContext = {
15 resource: Schema.String,
16 cause: Schema.Defect(),
17};
18
19export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
20 "SecretStoreSecureError",
21 {
22 ...secretStoreErrorContext,
23 },
24) {
25 override get message(): string {
26 return `Failed to secure ${this.resource}.`;
27 }
28}
29
30export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
31 "SecretStoreReadError",
32 {
33 ...secretStoreErrorContext,
34 },
35) {
36 override get message(): string {
37 return `Failed to read ${this.resource}.`;
38 }
39}
40
41export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
42 "SecretStoreTemporaryPathError",
43 {
44 ...secretStoreErrorContext,
45 },
46) {
47 override get message(): string {
48 return `Failed to create temporary path for ${this.resource}.`;
49 }
50}
51
52export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
53 "SecretStorePersistError",
54 {
55 ...secretStoreErrorContext,
56 },
57) {
58 override get message(): string {
59 return `Failed to persist ${this.resource}.`;
60 }
61}
62
63export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
64 "SecretStoreRandomGenerationError",
65 {
66 ...secretStoreErrorContext,
67 },
68) {
69 override get message(): string {
70 return `Failed to generate random bytes for ${this.resource}.`;
71 }
72}
73
74export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
75 "SecretStoreConcurrentReadError",
76 {
77 resource: Schema.String,
78 },
79) {
80 override get message(): string {
81 return `Failed to read ${this.resource} after concurrent creation.`;
82 }
83}
84
85export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
86 "SecretStoreRemoveError",
87 {
88 ...secretStoreErrorContext,
89 },
90) {
91 override get message(): string {
92 return `Failed to remove ${this.resource}.`;
93 }
94}
95
96export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
97 "SecretStoreDecodeError",
98 {
99 ...secretStoreErrorContext,
100 },
101) {
102 override get message(): string {
103 return `Failed to decode ${this.resource}.`;
104 }
105}
106
107export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
108 "SecretStoreEncodeError",
109 {
110 ...secretStoreErrorContext,
111 },
112) {
113 override get message(): string {
114 return `Failed to encode ${this.resource}.`;
115 }
116}
117
118export const SecretStoreError = Schema.Union([
119 SecretStoreSecureError,
120 SecretStoreReadError,
121 SecretStoreTemporaryPathError,
122 SecretStorePersistError,
123 SecretStoreRandomGenerationError,
124 SecretStoreConcurrentReadError,
125 SecretStoreRemoveError,
126 SecretStoreDecodeError,
127 SecretStoreEncodeError,
128]);
129export type SecretStoreError = typeof SecretStoreError.Type;
130export const isSecretStoreError = Schema.is(SecretStoreError);
131
132const isPlatformError = (value: unknown): value is PlatformError.PlatformError =>
133 Predicate.isTagged(value, "PlatformError");
134
135export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
136 "cause" in error && isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists";
137
138export class ServerSecretStore extends Context.Service<
139 ServerSecretStore,
140 {
141 readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
142 readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
143 readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
144 readonly getOrCreateRandom: (
145 name: string,
146 bytes: number,
147 ) => Effect.Effect<Uint8Array, SecretStoreError>;
148 readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
149 }
150>()("t3/auth/ServerSecretStore") {}
151
152export const make = Effect.gen(function* () {
153 const crypto = yield* Crypto.Crypto;
154 const fileSystem = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 const serverConfig = yield* ServerConfig.ServerConfig;
157
158 yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
159 yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
160 Effect.mapError(
161 (cause) =>
162 new SecretStoreSecureError({
163 resource: `secrets directory ${serverConfig.secretsDir}`,
164 cause,
165 }),
166 ),
167 );
168
169 const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
170
171 const get: ServerSecretStore["Service"]["get"] = (name) =>
172 fileSystem.readFile(resolveSecretPath(name)).pipe(
173 Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
174 Effect.catch((cause) =>
175 cause.reason._tag === "NotFound"
176 ? Effect.succeed(Option.none())
177 : Effect.fail(
178 new SecretStoreReadError({
179 resource: `secret ${name}`,
180 cause,
181 }),
182 ),
183 ),
184 Effect.withSpan("ServerSecretStore.get"),
185 );
186
187 const set: ServerSecretStore["Service"]["set"] = (name, value) => {
188 const secretPath = resolveSecretPath(name);
189 return crypto.randomUUIDv4.pipe(
190 Effect.mapError(
191 (cause) =>
192 new SecretStoreTemporaryPathError({
193 resource: `secret ${name}`,
194 cause,
195 }),
196 ),
197 Effect.flatMap((uuid) => {
198 const tempPath = `${secretPath}.${uuid}.tmp`;
199 return Effect.gen(function* () {
200 yield* fileSystem.writeFile(tempPath, value);
201 yield* fileSystem.chmod(tempPath, 0o600);
202 yield* fileSystem.rename(tempPath, secretPath);
203 yield* fileSystem.chmod(secretPath, 0o600);
204 }).pipe(
205 Effect.catch((cause) =>
206 fileSystem.remove(tempPath).pipe(
207 Effect.ignore,
208 Effect.flatMap(() =>
209 Effect.fail(
210 new SecretStorePersistError({
211 resource: `secret ${name}`,
212 cause,
213 }),
214 ),
215 ),
216 ),
217 ),
218 );
219 }),
220 Effect.withSpan("ServerSecretStore.set"),
221 );
222 };
223
224 const create: ServerSecretStore["Service"]["create"] = (name, value) => {
225 const secretPath = resolveSecretPath(name);
226 return Effect.scoped(
227 Effect.gen(function* () {
228 const file = yield* fileSystem.open(secretPath, {
229 flag: "wx",
230 mode: 0o600,
231 });
232 yield* file.writeAll(value);
233 yield* file.sync;
234 yield* fileSystem.chmod(secretPath, 0o600);
235 }),
236 ).pipe(
237 Effect.mapError(
238 (cause) =>
239 new SecretStorePersistError({
240 resource: `secret ${name}`,
241 cause,
242 }),
243 ),
244 );
245 };
246
247 const getOrCreateRandom: ServerSecretStore["Service"]["getOrCreateRandom"] = (name, bytes) =>
248 get(name).pipe(
249 Effect.flatMap(
250 Option.match({
251 onSome: Effect.succeed,
252 onNone: () =>
253 crypto.randomBytes(bytes).pipe(
254 Effect.mapError(
255 (cause) =>
256 new SecretStoreRandomGenerationError({
257 resource: `secret ${name}`,
258 cause,
259 }),
260 ),
261 Effect.flatMap((generated) =>
262 create(name, generated).pipe(
263 Effect.as(Uint8Array.from(generated)),
264 Effect.catchIf(isSecretStoreError, (error) =>
265 isSecretAlreadyExistsError(error)
266 ? get(name).pipe(
267 Effect.flatMap(
268 Option.match({
269 onSome: Effect.succeed,
270 onNone: () =>
271 Effect.fail(
272 new SecretStoreConcurrentReadError({
273 resource: `secret ${name}`,
274 }),
275 ),
276 }),
277 ),
278 )
279 : Effect.fail(error),
280 ),
281 ),
282 ),
283 ),
284 }),
285 ),
286 Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
287 );
288
289 const remove: ServerSecretStore["Service"]["remove"] = (name) =>
290 fileSystem.remove(resolveSecretPath(name)).pipe(
291 Effect.catch((cause) =>
292 cause.reason._tag === "NotFound"
293 ? Effect.void
294 : Effect.fail(
295 new SecretStoreRemoveError({
296 resource: `secret ${name}`,
297 cause,
298 }),
299 ),
300 ),
301 Effect.withSpan("ServerSecretStore.remove"),
302 );
303
304 return ServerSecretStore.of({
305 get,
306 set,
307 create,
308 getOrCreateRandom,
309 remove,
310 });
311});
312
313export const layer = Layer.effect(ServerSecretStore, make);