Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerSecretStore.ts

198 lines6.4 KB

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