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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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
152/** @public Service construction is part of the canonical Effect module API. */
153export const make = Effect.gen(function* () {
154 const crypto = yield* Crypto.Crypto;
155 const fileSystem = yield* FileSystem.FileSystem;
156 const path = yield* Path.Path;
157 const serverConfig = yield* ServerConfig.ServerConfig;
158
159 yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
160 yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
161 Effect.mapError(
162 (cause) =>
163 new SecretStoreSecureError({
164 resource: `secrets directory ${serverConfig.secretsDir}`,
165 cause,
166 }),
167 ),
168 );
169
170 const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
171
172 const get: ServerSecretStore["Service"]["get"] = (name) =>
173 fileSystem.readFile(resolveSecretPath(name)).pipe(
174 Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
175 Effect.catch((cause) =>
176 cause.reason._tag === "NotFound"
177 ? Effect.succeedNone
178 : Effect.fail(
179 new SecretStoreReadError({
180 resource: `secret ${name}`,
181 cause,
182 }),
183 ),
184 ),
185 Effect.withSpan("ServerSecretStore.get"),
186 );
187
188 const set: ServerSecretStore["Service"]["set"] = (name, value) => {
189 const secretPath = resolveSecretPath(name);
190 return crypto.randomUUIDv4.pipe(
191 Effect.mapError(
192 (cause) =>
193 new SecretStoreTemporaryPathError({
194 resource: `secret ${name}`,
195 cause,
196 }),
197 ),
198 Effect.flatMap((uuid) => {
199 const tempPath = `${secretPath}.${uuid}.tmp`;
200 return Effect.gen(function* () {
201 yield* fileSystem.writeFile(tempPath, value);
202 yield* fileSystem.chmod(tempPath, 0o600);
203 yield* fileSystem.rename(tempPath, secretPath);
204 yield* fileSystem.chmod(secretPath, 0o600);
205 }).pipe(
206 Effect.catch((cause) =>
207 fileSystem.remove(tempPath).pipe(
208 Effect.ignore,
209 Effect.flatMap(() =>
210 Effect.fail(
211 new SecretStorePersistError({
212 resource: `secret ${name}`,
213 cause,
214 }),
215 ),
216 ),
217 ),
218 ),
219 );
220 }),
221 Effect.withSpan("ServerSecretStore.set"),
222 );
223 };
224
225 const create: ServerSecretStore["Service"]["create"] = (name, value) => {
226 const secretPath = resolveSecretPath(name);
227 return Effect.scoped(
228 Effect.gen(function* () {
229 const file = yield* fileSystem.open(secretPath, {
230 flag: "wx",
231 mode: 0o600,
232 });
233 yield* file.writeAll(value);
234 yield* file.sync;
235 yield* fileSystem.chmod(secretPath, 0o600);
236 }),
237 ).pipe(
238 Effect.mapError(
239 (cause) =>
240 new SecretStorePersistError({
241 resource: `secret ${name}`,
242 cause,
243 }),
244 ),
245 );
246 };
247
248 const getOrCreateRandom: ServerSecretStore["Service"]["getOrCreateRandom"] = (name, bytes) =>
249 get(name).pipe(
250 Effect.flatMap(
251 Option.match({
252 onSome: Effect.succeed,
253 onNone: () =>
254 crypto.randomBytes(bytes).pipe(
255 Effect.mapError(
256 (cause) =>
257 new SecretStoreRandomGenerationError({
258 resource: `secret ${name}`,
259 cause,
260 }),
261 ),
262 Effect.flatMap((generated) =>
263 create(name, generated).pipe(
264 Effect.as(Uint8Array.from(generated)),
265 Effect.catchIf(isSecretStoreError, (error) =>
266 isSecretAlreadyExistsError(error)
267 ? get(name).pipe(
268 Effect.flatMap(
269 Option.match({
270 onSome: Effect.succeed,
271 onNone: () =>
272 Effect.fail(
273 new SecretStoreConcurrentReadError({
274 resource: `secret ${name}`,
275 }),
276 ),
277 }),
278 ),
279 )
280 : Effect.fail(error),
281 ),
282 ),
283 ),
284 ),
285 }),
286 ),
287 Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
288 );
289
290 const remove: ServerSecretStore["Service"]["remove"] = (name) =>
291 fileSystem.remove(resolveSecretPath(name)).pipe(
292 Effect.catch((cause) =>
293 cause.reason._tag === "NotFound"
294 ? Effect.void
295 : Effect.fail(
296 new SecretStoreRemoveError({
297 resource: `secret ${name}`,
298 cause,
299 }),
300 ),
301 ),
302 Effect.withSpan("ServerSecretStore.remove"),
303 );
304
305 return ServerSecretStore.of({
306 get,
307 set,
308 create,
309 getOrCreateRandom,
310 remove,
311 });
312});
313
314export const layer = Layer.effect(ServerSecretStore, make);