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