-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocker.ts
More file actions
449 lines (393 loc) · 11.2 KB
/
Copy pathdocker.ts
File metadata and controls
449 lines (393 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import fs from "fs";
import path from "path";
import { fetchEnvExample } from "../../core/fetch.js";
import { parseEnv, parseEnvString } from "../../core/env.js";
import { generateSecret } from "../../core/secrets.js";
import { generateJWKS } from "../../core/jwks.js";
import {
buildOAuthAuthEnv,
withLoginMethod,
type CollectedOAuthProvider,
} from "../../core/oauthProviders.js";
import {
POSTGRES_IMAGE,
SEAMLESS_AUTH_ADMIN_DASHBOARD_IMAGE,
SEAMLESS_AUTH_API_IMAGE,
} from "../../core/images.js";
export async function generateDockerCompose(
root: string,
options: {
authMode: "local" | "docker";
adminMode: AdminMode;
oauth?: CollectedOAuthProvider[];
ownerEmail?: string;
},
) {
const { compose, shared } = await buildCompose(options, root);
fs.writeFileSync(
path.join(root, "docker-compose.yml"),
compose.trim() + "\n",
);
console.log("Docker compose created.");
return shared;
}
async function buildCompose(
options: {
authMode: "local" | "docker";
adminMode: AdminMode;
oauth?: CollectedOAuthProvider[];
ownerEmail?: string;
},
root: string,
) {
const { authMode, adminMode, oauth, ownerEmail } = options;
const { service: authBlock, shared } = await authService(
authMode,
root,
oauth,
adminMode,
ownerEmail,
);
const includeAdminContainer = adminMode === "image" || adminMode === "source";
return {
compose: `# Ports are published on 127.0.0.1 so this stack is reachable from this machine
# only. The auth server is configured to return OTP codes in the response for
# local login, which would otherwise be an authentication bypass for anyone on
# the same network. Drop the 127.0.0.1 prefix only if you know you want that.
services:
db:
image: ${POSTGRES_IMAGE}
container_name: seamless-db
ports:
- "127.0.0.1:5432:5432"
environment:
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
POSTGRES_DB: postgres
volumes:
# PostgreSQL 18+ images store data in a major-versioned subdirectory
# (/var/lib/postgresql/18/docker), so the mount goes one level up. Mounting
# .../data instead leaves the volume unused and the container refuses to
# start. See docker-library/postgres#1259.
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U myuser -d postgres"]
interval: 5s
timeout: 5s
retries: 5
${authBlock}
${apiService(shared, adminMode)}
${webService()}
${includeAdminContainer ? adminService(adminMode) : ""}
volumes:
pgdata:
`,
shared,
};
}
async function authService(
mode: "local" | "docker",
root: string,
oauth: CollectedOAuthProvider[] = [],
adminMode: AdminMode = "api",
ownerEmail?: string,
) {
if (mode === "local") {
// auth/.env was already written by generateAuthServer (with its secrets and any
// OAuth config). Read those values back rather than regenerating, which would mint
// a new API_SERVICE_TOKEN that no longer matches the one the API was given.
const shared = extractSharedFromExistingEnv(root);
return {
service: `
auth:
container_name: seamless-auth
build:
context: ./auth
dockerfile: Dockerfile.dev
ports:
- "127.0.0.1:5312:5312"
env_file:
- ./auth/.env
environment:
DB_HOST: db
ISSUER: http://auth:5312
volumes:
- ./auth:/app
- /app/node_modules
depends_on:
db:
condition: service_healthy
`,
shared,
};
}
return await authServiceDocker(oauth, adminMode, ownerEmail);
}
// The app API's CORS allowlist. The console is same-origin here in API-served
// mode, so 5174 only belongs when a standalone dashboard container runs there.
function apiUiOrigins(adminMode: AdminMode): string {
const web = "http://localhost:5173";
if (adminMode === "image" || adminMode === "source") {
return `${web},http://localhost:5174`;
}
return web;
}
function apiService(shared: any, adminMode: AdminMode) {
return `
api:
container_name: api
build: ./api
ports:
- "127.0.0.1:3000:3000"
env_file:
- ./api/.env
environment:
AUTH_SERVER_URL: http://auth:5312
UI_ORIGINS: ${apiUiOrigins(adminMode)}
DB_HOST: db
API_SERVICE_TOKEN: ${shared.apiToken}
JWKS_KID: ${shared.kid}
volumes:
- ./api:/app
- /app/node_modules
depends_on:
db:
condition: service_healthy
auth:
condition: service_started
`;
}
function webService() {
return `
web:
container_name: web
build: ./web
ports:
- "127.0.0.1:5173:80"
environment:
API_URL: http://localhost:3000/
volumes:
- ./web:/app
- /app/node_modules
depends_on:
- api
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/health"]
interval: 5s
timeout: 5s
retries: 10
`;
}
async function authServiceDocker(
oauth: CollectedOAuthProvider[] = [],
adminMode: AdminMode = "api",
ownerEmail?: string,
) {
const raw = await fetchEnvExample();
const parsed = parseEnvString(raw);
const { env, shared } = buildAuthEnv(
parsed,
"docker",
oauth,
adminMode,
ownerEmail,
);
const envBlock = envToDockerBlock(env);
return {
service: `
auth:
image: ${SEAMLESS_AUTH_API_IMAGE}
container_name: seamless-auth
ports:
- "127.0.0.1:5312:5312"
environment:
${envBlock}
depends_on:
db:
condition: service_healthy
`,
shared,
};
}
function adminService(mode: "image" | "source") {
if (mode === "source") {
return `
admin:
container_name: admin
build: ./admin
ports:
- "127.0.0.1:5174:80"
environment:
API_URL: http://localhost:3000/
AUTH_MODE: server
volumes:
- ./admin:/app
- /app/node_modules
depends_on:
- api
`;
}
return `
admin:
image: ${SEAMLESS_AUTH_ADMIN_DASHBOARD_IMAGE}
container_name: admin
ports:
- "127.0.0.1:5174:80"
environment:
API_URL: http://localhost:3000/
depends_on:
- api
`;
}
export type AdminMode = "api" | "image" | "source" | "none";
// WebAuthn allowed origins the auth server accepts passkey ceremonies from. The
// web app (5173) is always present; the console adds either the app API origin
// (when the API serves it at /console) or the standalone container origin (5174).
function adminOrigins(adminMode: AdminMode): string {
const web = "http://localhost:5173";
if (adminMode === "api") return `${web},http://localhost:3000`;
if (adminMode === "image" || adminMode === "source") {
return `${web},http://localhost:5174`;
}
return web;
}
export function buildAuthEnv(
env: Record<string, string>,
mode: "local" | "docker",
oauth: CollectedOAuthProvider[] = [],
adminMode: AdminMode = "api",
ownerEmail?: string,
) {
const apiToken = generateSecret(32);
const kid = "dev-main";
// The auth server grants the admin role at signup to an address listed here,
// so registering in the scaffolded app produces a working /console admin with
// no separate promotion step. Signup-time only: setting this after an account
// already exists promotes nobody.
if (ownerEmail) {
env.OWNER_EMAIL = ownerEmail;
}
env.PORT = "5312";
env.NODE_ENV = "development";
env.AUTH_MODE = "server";
env.ISSUER =
mode === "docker" ? "http://auth:5312" : "http://localhost:5312";
env.DB_HOST = mode === "docker" ? "db" : "localhost";
env.DB_PORT = "5432";
env.API_SERVICE_TOKEN = apiToken;
// Dedicated secrets the auth server otherwise leaves empty (falling back to the
// service token). Generate real ones so a scaffolded stack is production-shaped.
env.REFRESH_TOKEN_LOOKUP_SECRET = generateSecret(32);
env.TOTP_SECRET_ENCRYPTION_KEY = generateSecret(32);
env.APP_ORIGINS = "http://localhost:3000";
env.ORIGINS = adminOrigins(adminMode);
// Serve the bundled admin dashboard build only when the app API proxies it at
// /console; otherwise the console is a standalone container (or omitted).
env.SERVE_ADMIN_DASHBOARD = adminMode === "api" ? "true" : "false";
// Enable email OTP so `seamless login` works against a freshly scaffolded stack
// out of the box. The auth server's own default (passkey,magic_link) has no
// method the CLI can drive without a browser authenticator.
env.LOGIN_METHODS = withLoginMethod(env.LOGIN_METHODS, "email_otp");
// Let `seamless login --local` read the OTP straight from the response instead
// of needing a mail provider. Dev-only: the auth server ignores this under a
// production NODE_ENV, and the scaffold runs as development.
env.ALLOW_UNCREDENTIALED_DELIVERY_SECRETS = "true";
// When the OAuth template collected providers, wire them into the auth server
// (OAUTH_PROVIDERS, per-provider secret env vars, OAUTH_STATE_SECRET) and enable
// the oauth login method.
if (oauth.length > 0) {
const { env: oauthEnv } = buildOAuthAuthEnv(oauth);
Object.assign(env, oauthEnv);
env.LOGIN_METHODS = withLoginMethod(env.LOGIN_METHODS, "oauth");
}
return {
env,
shared: {
apiToken,
kid,
},
};
}
export function envToDockerBlock(env: Record<string, string>) {
return Object.entries(env)
.map(([k, v]) => {
if (v.includes("\n")) {
return ` ${k}: |\n${indentMultiline(v, 8)}`;
}
return ` ${k}: ${JSON.stringify(v)}`;
})
.join("\n");
}
function indentMultiline(value: string, spaces: number) {
const indent = " ".repeat(spaces);
return value
.split("\n")
.map((line) => `${indent}${line}`)
.join("\n");
}
export function buildJWKSConfig() {
const kid = "main";
const { publicKey, privateKey } = generateJWKS();
return {
kid,
privateKey,
publicKey,
publicJwksJson: JSON.stringify(
{
keys: [
{
kid,
pem: publicKey,
},
],
},
null,
2,
),
};
}
export async function configureAuthLocalEnv(
root: string,
oauth: CollectedOAuthProvider[] = [],
adminMode: AdminMode = "api",
ownerEmail?: string,
) {
const authDir = path.join(root, "auth");
const envExamplePath = path.join(authDir, ".env.example");
const envPath = path.join(authDir, ".env");
if (!fs.existsSync(envExamplePath)) {
throw new Error(".env.example not found in auth directory");
}
const raw = fs.readFileSync(envExamplePath, "utf-8");
const parsed = parseEnvString(raw);
const { env, shared } = buildAuthEnv(
parsed,
"local",
oauth,
adminMode,
ownerEmail,
);
writeEnvFile(envPath, env);
return shared;
}
function writeEnvFile(filePath: string, env: Record<string, string>) {
const content = Object.entries(env)
.map(([k, v]) => {
if (v.includes("\n")) {
return `${k}="${escapeMultiline(v)}"`;
}
return `${k}=${v}`;
})
.join("\n");
fs.writeFileSync(filePath, content + "\n");
}
function escapeMultiline(value: string) {
return value.replace(/\n/g, "\\n");
}
export function extractSharedFromExistingEnv(root: string) {
const env = parseEnv(path.join(root, "auth", ".env"));
return {
apiToken: env.API_SERVICE_TOKEN,
kid: env.SEAMLESS_JWKS_ACTIVE_KID || env.JWKS_ACTIVE_KID || "dev-main",
};
}