Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Crypto from "effect/Crypto";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as Predicate from "effect/Predicate";
9import * as PlatformError from "effect/PlatformError";
10
11import { ServerConfig } from "../config.ts";
12
13export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
14 readonly message: string;
15 readonly cause?: unknown;
16}> {}
17
18export interface ServerSecretStoreShape {
19 readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
20 readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
21 readonly getOrCreateRandom: (
22 name: string,
23 bytes: number,
24 ) => Effect.Effect<Uint8Array, SecretStoreError>;
25 readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
26}
27
28export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
29 "t3/auth/ServerSecretStore",
30) {}
31
32export const make = Effect.fn("makeServerSecretStore")(function* () {
33 const crypto = yield* Crypto.Crypto;
34 const fileSystem = yield* FileSystem.FileSystem;
35 const path = yield* Path.Path;
36 const serverConfig = yield* ServerConfig;
37
38 yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
39 yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
40 Effect.mapError(
41 (cause) =>
42 new SecretStoreError({
43 message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
44 cause,
45 }),
46 ),
47 );
48
49 const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
50
51 const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
52 Predicate.isTagged(u, "PlatformError");
53
54 const get: ServerSecretStoreShape["get"] = (name) =>
55 fileSystem.readFile(resolveSecretPath(name)).pipe(
56 Effect.map((bytes) => Uint8Array.from(bytes)),
57 Effect.catch((cause) =>
58 cause.reason._tag === "NotFound"
59 ? Effect.succeed(null)
60 : Effect.fail(
61 new SecretStoreError({
62 message: `Failed to read secret ${name}.`,
63 cause,
64 }),
65 ),
66 ),
67 Effect.withSpan("ServerSecretStore.get"),
68 );
69
70 const set: ServerSecretStoreShape["set"] = (name, value) => {
71 const secretPath = resolveSecretPath(name);
72 return crypto.randomUUIDv4.pipe(
73 Effect.mapError(
74 (cause) =>
75 new SecretStoreError({
76 message: `Failed to create temporary path for secret ${name}.`,
77 cause,
78 }),
79 ),
80 Effect.flatMap((uuid) => {
81 const tempPath = `${secretPath}.${uuid}.tmp`;
82 return Effect.gen(function* () {
83 yield* fileSystem.writeFile(tempPath, value);
84 yield* fileSystem.chmod(tempPath, 0o600);
85 yield* fileSystem.rename(tempPath, secretPath);
86 yield* fileSystem.chmod(secretPath, 0o600);
87 }).pipe(
88 Effect.catch((cause) =>
89 fileSystem.remove(tempPath).pipe(
90 Effect.ignore,
91 Effect.flatMap(() =>
92 Effect.fail(
93 new SecretStoreError({
94 message: `Failed to persist secret ${name}.`,
95 cause,
96 }),
97 ),
98 ),
99 ),
100 ),
101 );
102 }),
103 Effect.withSpan("ServerSecretStore.set"),
104 );
105 };
106
107 const create: ServerSecretStoreShape["set"] = (name, value) => {
108 const secretPath = resolveSecretPath(name);
109 return Effect.scoped(
110 Effect.gen(function* () {
111 const file = yield* fileSystem.open(secretPath, {
112 flag: "wx",
113 mode: 0o600,
114 });
115 yield* file.writeAll(value);
116 yield* file.sync;
117 yield* fileSystem.chmod(secretPath, 0o600);
118 }),
119 ).pipe(
120 Effect.mapError(
121 (cause) =>
122 new SecretStoreError({
123 message: `Failed to persist secret ${name}.`,
124 cause,
125 }),
126 ),
127 );
128 };
129
130 const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
131 get(name).pipe(
132 Effect.flatMap((existing) => {
133 if (existing) {
134 return Effect.succeed(existing);
135 }
136
137 return crypto.randomBytes(bytes).pipe(
138 Effect.mapError(
139 (cause) =>
140 new SecretStoreError({
141 message: `Failed to generate random bytes for secret ${name}.`,
142 cause,
143 }),
144 ),
145 Effect.flatMap((generated) =>
146 create(name, generated).pipe(
147 Effect.as(Uint8Array.from(generated)),
148 Effect.catchTag("SecretStoreError", (error) =>
149 isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
150 ? get(name).pipe(
151 Effect.flatMap((created) =>
152 created !== null
153 ? Effect.succeed(created)
154 : Effect.fail(
155 new SecretStoreError({
156 message: `Failed to read secret ${name} after concurrent creation.`,
157 }),
158 ),
159 ),
160 )
161 : Effect.fail(error),
162 ),
163 ),
164 ),
165 );
166 }),
167 Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
168 );
169
170 const remove: ServerSecretStoreShape["remove"] = (name) =>
171 fileSystem.remove(resolveSecretPath(name)).pipe(
172 Effect.catch((cause) =>
173 cause.reason._tag === "NotFound"
174 ? Effect.void
175 : Effect.fail(
176 new SecretStoreError({
177 message: `Failed to remove secret ${name}.`,
178 cause,
179 }),
180 ),
181 ),
182 Effect.withSpan("ServerSecretStore.remove"),
183 );
184
185 return {
186 get,
187 set,
188 getOrCreateRandom,
189 remove,
190 } satisfies ServerSecretStoreShape;
191});
192
193export const layer = Layer.effect(ServerSecretStore, make());