@o3co/create-auth-provider 0.15.0 → 0.17.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.ja.md +139 -48
  2. package/README.md +138 -47
  3. package/dist/index.d.mts +33 -10
  4. package/dist/index.d.mts.map +1 -1
  5. package/dist/index.mjs +118 -59
  6. package/dist/internal/template-filter.d.mts +7 -10
  7. package/dist/internal/template-filter.d.mts.map +1 -1
  8. package/dist/internal/template-filter.mjs +7 -10
  9. package/package.json +6 -4
  10. package/templates/standalone/.dockerignore +15 -2
  11. package/templates/standalone/.env.example +69 -24
  12. package/templates/standalone/Dockerfile +7 -3
  13. package/templates/standalone/README.ja.md +677 -184
  14. package/templates/standalone/README.md +699 -238
  15. package/templates/standalone/config/application.conf +203 -325
  16. package/templates/standalone/config/clients.yaml +2 -0
  17. package/templates/standalone/config/clients.yaml.example +4 -0
  18. package/templates/standalone/config/development.conf +13 -4
  19. package/templates/standalone/config/mailpit.conf +8 -0
  20. package/templates/standalone/config/production.conf +5 -6
  21. package/templates/standalone/config/reference.conf +399 -0
  22. package/templates/standalone/docker-compose.mailpit.yml +36 -0
  23. package/templates/standalone/docker-compose.production.yml +58 -30
  24. package/templates/standalone/docker-compose.yml +13 -3
  25. package/templates/standalone/gitignore +4 -2
  26. package/templates/standalone/package.json +9 -6
  27. package/templates/standalone/src/__tests__/access-token-lifetime-alias.test.mts +65 -32
  28. package/templates/standalone/src/__tests__/adapters.test.mts +358 -0
  29. package/templates/standalone/src/__tests__/all-modules-composition.fixture.mts +1178 -0
  30. package/templates/standalone/src/__tests__/all-modules-composition.multi.test.mts +256 -0
  31. package/templates/standalone/src/__tests__/all-modules-composition.test.mts +1119 -0
  32. package/templates/standalone/src/__tests__/audit-sink.test.mts +78 -76
  33. package/templates/standalone/src/__tests__/configPath.test.mts +13 -11
  34. package/templates/standalone/src/__tests__/core-federations.test.mts +226 -0
  35. package/templates/standalone/src/__tests__/core-sections.test.mts +190 -0
  36. package/templates/standalone/src/__tests__/device-code-store-client-module.test.mts +9 -14
  37. package/templates/standalone/src/__tests__/documented-env-overrides.test.mts +672 -271
  38. package/templates/standalone/src/__tests__/federation-grants-composition.test.mts +480 -78
  39. package/templates/standalone/src/__tests__/federation-grants-survive-logout.test.mts +102 -66
  40. package/templates/standalone/src/__tests__/federation-token-refresh-outage.test.mts +135 -0
  41. package/templates/standalone/src/__tests__/google-federation-config-module.test.mts +49 -18
  42. package/templates/standalone/src/__tests__/google-session.fixture.mts +315 -0
  43. package/templates/standalone/src/__tests__/host-routes.test.mts +134 -0
  44. package/templates/standalone/src/__tests__/library-references.fixture.mts +183 -0
  45. package/templates/standalone/src/__tests__/listen.test.mts +121 -0
  46. package/templates/standalone/src/__tests__/logger-projection.test.mts +77 -0
  47. package/templates/standalone/src/__tests__/mail-sender.test.mts +134 -0
  48. package/templates/standalone/src/__tests__/mailpit-compose.test.mts +328 -0
  49. package/templates/standalone/src/__tests__/metrics.test.mts +17 -7
  50. package/templates/standalone/src/__tests__/mfa-switch.redis.test.mts +123 -0
  51. package/templates/standalone/src/__tests__/mfa-switch.test.mts +780 -0
  52. package/templates/standalone/src/__tests__/oidc-federation-config-module.test.mts +52 -46
  53. package/templates/standalone/src/__tests__/own-modules.test.mts +1457 -0
  54. package/templates/standalone/src/__tests__/post-logout-redirect.test.mts +183 -0
  55. package/templates/standalone/src/__tests__/redis-connection-error-log.test.mts +135 -0
  56. package/templates/standalone/src/__tests__/redis-rate-limiter-config-survives.test.mts +112 -81
  57. package/templates/standalone/src/__tests__/refresh-token-family-client-module.test.mts +25 -31
  58. package/templates/standalone/src/__tests__/replica-safety.test.mts +166 -145
  59. package/templates/standalone/src/__tests__/router-error-answers.test.mts +146 -0
  60. package/templates/standalone/src/__tests__/scaffold-assets.test.mts +275 -95
  61. package/templates/standalone/src/__tests__/sections.test.mts +480 -0
  62. package/templates/standalone/src/__tests__/session-logout-invalidates-token.test.mts +67 -55
  63. package/templates/standalone/src/__tests__/session-requirements.test.mts +299 -0
  64. package/templates/standalone/src/__tests__/shutdown.test.mts +319 -115
  65. package/templates/standalone/src/__tests__/smoke.test.mts +179 -233
  66. package/templates/standalone/src/__tests__/store-credential.test.mts +317 -0
  67. package/templates/standalone/src/__tests__/supertest-loopback.test.mts +182 -11
  68. package/templates/standalone/src/__tests__/three-tier-resolution.test.mts +108 -95
  69. package/templates/standalone/src/__tests__/two-phase-config.test.mts +438 -0
  70. package/templates/standalone/src/__tests__/upstream-amr.acceptance.test.mts +390 -0
  71. package/templates/standalone/src/adapters.mts +149 -0
  72. package/templates/standalone/src/app.mts +71 -115
  73. package/templates/standalone/src/buildModules.mts +229 -251
  74. package/templates/standalone/src/configPath.mts +422 -29
  75. package/templates/standalone/src/listen.mts +60 -0
  76. package/templates/standalone/src/logger.mts +31 -57
  77. package/templates/standalone/src/metrics.mts +24 -47
  78. package/templates/standalone/src/mfaSwitch.mts +262 -0
  79. package/templates/standalone/src/modules.mts +480 -464
  80. package/templates/standalone/src/rootRenames.mts +79 -0
  81. package/templates/standalone/src/routes.mts +89 -0
  82. package/templates/standalone/src/sections.mts +366 -0
  83. package/templates/standalone/src/shutdown.mts +54 -126
  84. package/templates/standalone/tests/index.test.js +2 -2
  85. package/templates/standalone/tests/package-lock.json +1615 -2223
  86. package/templates/standalone/tests/package.json +2 -2
  87. package/templates/standalone/tests/vitest.config.mjs +26 -0
  88. package/templates/standalone/vitest.config.mts +8 -7
  89. package/templates/standalone/vitest.supertest-loopback.mts +97 -69
  90. package/templates/versions.json +18 -15
  91. package/templates/standalone/src/__tests__/terminal-error.test.mts +0 -96
  92. package/templates/standalone/src/terminalError.mts +0 -60
@@ -0,0 +1,121 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Starting the listener: one object-first `server_listening` line once the
19
+ * socket is bound, and none for a port that was never bound. `listen` wires
20
+ * the server's events itself rather than trust `app.listen`, whose Express 5
21
+ * callback is handed the bind `error` as well as `listening`.
22
+ */
23
+
24
+ import { createServer, type Server } from "node:http";
25
+ import type { AddressInfo } from "node:net";
26
+ import type { Logger } from "@o3co/auth-provider-core";
27
+ import express from "express";
28
+ import { afterEach, describe, expect, it } from "vitest";
29
+ import { listen } from "#/listen.mjs";
30
+
31
+ /** A logger that records what each level is handed. */
32
+ function recordingLogger(): { logger: Logger; calls: Array<{ level: string; args: unknown[] }> } {
33
+ const calls: Array<{ level: string; args: unknown[] }> = [];
34
+ const record =
35
+ (level: string) =>
36
+ (...args: unknown[]): void => {
37
+ calls.push({ level, args });
38
+ };
39
+ const logger: Logger = {
40
+ trace: record("trace"),
41
+ debug: record("debug"),
42
+ info: record("info"),
43
+ warn: record("warn"),
44
+ error: record("error"),
45
+ fatal: record("fatal"),
46
+ child: () => logger,
47
+ };
48
+ return { logger, calls };
49
+ }
50
+
51
+ const opened: Server[] = [];
52
+
53
+ afterEach(async () => {
54
+ await Promise.all(
55
+ opened.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))),
56
+ );
57
+ });
58
+
59
+ describe("listen", () => {
60
+ it("says server_listening once, object-first, with the port the socket holds", async () => {
61
+ const { logger, calls } = recordingLogger();
62
+ const server = await listen(express(), 0, logger);
63
+ opened.push(server);
64
+ const { port } = server.address() as AddressInfo;
65
+ expect(port).toBeGreaterThan(0);
66
+ expect(calls).toEqual([{ level: "info", args: [{ port }, "server_listening"] }]);
67
+ });
68
+
69
+ it("logs a server error after the bind — server_error, the projection — rather than swallowing it", async () => {
70
+ // Every `error` after the bind (accept EMFILE) is logged: a spent
71
+ // once-listener would lose the first, and with no listener left the
72
+ // second would be thrown out of the process.
73
+ const { logger, calls } = recordingLogger();
74
+ const server = await listen(express(), 0, logger);
75
+ opened.push(server);
76
+ calls.length = 0;
77
+
78
+ const failure = Object.assign(new Error("accept EMFILE"), { code: "EMFILE" });
79
+ server.emit("error", failure);
80
+ server.emit("error", failure);
81
+
82
+ expect(calls).toEqual([
83
+ {
84
+ level: "error",
85
+ args: [{ err: expect.objectContaining({ name: "Error", code: "EMFILE" }) }, "server_error"],
86
+ },
87
+ {
88
+ level: "error",
89
+ args: [{ err: expect.objectContaining({ name: "Error", code: "EMFILE" }) }, "server_error"],
90
+ },
91
+ ]);
92
+ const line = calls[0]?.args[0] as { err: unknown };
93
+ expect(line.err).not.toBeInstanceOf(Error);
94
+ });
95
+
96
+ it("leaves the bound server one error listener, server_error's: the bind's own is removed", async () => {
97
+ // The listener that turns a bind failure into a rejection has done its
98
+ // job once the socket is bound. Left attached, it would take every
99
+ // later error beside server_error's — a callback already spent.
100
+ const { logger } = recordingLogger();
101
+ const server = await listen(express(), 0, logger);
102
+ opened.push(server);
103
+
104
+ expect(server.listenerCount("error")).toBe(1);
105
+ // And nothing of `listen`'s own left on `listening`: an http.Server
106
+ // keeps one there itself (its connection tracking).
107
+ expect(server.listenerCount("listening")).toBe(createServer().listenerCount("listening"));
108
+ });
109
+
110
+ it("rejects with the server's error for a port already bound, and announces nothing", async () => {
111
+ const holder = createServer();
112
+ // Every interface, as `server.listen(port)` binds, so the two collide.
113
+ await new Promise<void>((resolve) => holder.listen(0, resolve));
114
+ opened.push(holder);
115
+ const { port } = holder.address() as AddressInfo;
116
+
117
+ const { logger, calls } = recordingLogger();
118
+ await expect(listen(express(), port, logger)).rejects.toMatchObject({ code: "EADDRINUSE" });
119
+ expect(calls).toEqual([]);
120
+ });
121
+ });
@@ -0,0 +1,77 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * What the template's own logger writes for a projected error — the line on
19
+ * stdout, from `createAppLogger` in a process of its own, as the service
20
+ * writes it. Every field of core's `loggableError` projection must reach
21
+ * it, at every level of the cause chain: the logger's `err` serializer must
22
+ * not take the projection for an Error and fold its causes into one message.
23
+ */
24
+
25
+ import { execFileSync } from "node:child_process";
26
+ import { createRequire } from "node:module";
27
+ import { fileURLToPath } from "node:url";
28
+ import { describe, expect, it } from "vitest";
29
+
30
+ const templateRoot = fileURLToPath(new URL("../..", import.meta.url));
31
+ const tsxCli = createRequire(import.meta.url).resolve("tsx/cli");
32
+
33
+ /**
34
+ * A request failure caused by a Store failure caused by a parse failure,
35
+ * logged through `createAppLogger` in a child process; the line it wrote.
36
+ */
37
+ const SCRIPT = `
38
+ const { createAppLogger } = await import("./src/logger.mts");
39
+ const { loggableError } = await import("@o3co/auth-provider-core");
40
+ let parse;
41
+ try { JSON.parse('{"a":1,'); } catch (err) { parse = err; }
42
+ const store = Object.assign(new Error("the Store could not be read", { cause: parse }), {
43
+ name: "StoreTransportError", code: "ECONNREFUSED", reason: "unreachable", storeStatus: 503,
44
+ });
45
+ const failed = Object.assign(new Error("request failed", { cause: store }), {
46
+ type: "upstream.failed", status: 502,
47
+ });
48
+ createAppLogger({ level: "info" }).error({ err: loggableError(failed) }, "unhandled_request_error");
49
+ `;
50
+
51
+ describe("createAppLogger writes a projected error whole", () => {
52
+ it("keeps every field of every level of the cause chain on the line", () => {
53
+ const stdout = execFileSync(
54
+ process.execPath,
55
+ [tsxCli, "--input-type=module", "--eval", SCRIPT],
56
+ { cwd: templateRoot, encoding: "utf8" },
57
+ );
58
+ const line = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") as {
59
+ msg?: string;
60
+ err?: Record<string, unknown>;
61
+ };
62
+
63
+ expect(line.msg).toBe("unhandled_request_error");
64
+ expect(line.err).toMatchObject({
65
+ name: "Error",
66
+ type: "upstream.failed",
67
+ status: 502,
68
+ cause: {
69
+ name: "StoreTransportError",
70
+ code: "ECONNREFUSED",
71
+ reason: "unreachable",
72
+ storeStatus: 503,
73
+ cause: { name: "SyntaxError", position: 7 },
74
+ },
75
+ });
76
+ });
77
+ });
@@ -0,0 +1,134 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * The mail sender the template installs behind core's `mailSender` slot,
19
+ * both from `@o3co/auth-provider-standard`: the development sender where the
20
+ * configuration was selected as development — the name `app.mts` defaults
21
+ * to — the SMTP sender's module under any other name, and none when
22
+ * `buildModules` is told no name. A deployment's own sender modules, passed
23
+ * as `mailSenderModules`, replace that choice under every name. Nothing in
24
+ * the template reads the slot: this is the wiring alone.
25
+ */
26
+
27
+ import { defineModule, type MailSender, type Module } from "@o3co/auth-provider-core";
28
+ import {
29
+ standardDevelopmentMailSenderModule,
30
+ standardSmtpMailSenderModule,
31
+ } from "@o3co/auth-provider-standard";
32
+ import { afterEach, describe, expect, it } from "vitest";
33
+ import { buildModules } from "#/buildModules.mjs";
34
+ import {
35
+ type Composition,
36
+ compose,
37
+ resolveConfig,
38
+ SINGLE_ENV,
39
+ } from "./all-modules-composition.fixture.mjs";
40
+
41
+ const DEVELOPMENT = standardDevelopmentMailSenderModule({ environment: "development" }).name;
42
+ const SMTP = standardSmtpMailSenderModule.name;
43
+
44
+ /** A deployment's own sender, built at boot so the slot holds it with nothing reading it. */
45
+ const OWN_SENDER: MailSender = {
46
+ kind: "deployment-own",
47
+ send: async () => ({ outcome: "delivered" }),
48
+ };
49
+ const ownSenderModule: Module = defineModule({
50
+ name: "deployment-own-mail-sender",
51
+ lifecycle: { mailSender: { eager: true } },
52
+ provides: { mailSender: () => OWN_SENDER },
53
+ });
54
+ const OWN = ownSenderModule.name;
55
+
56
+ /** The mail sender modules `buildModules` lists for `environment`. */
57
+ const senders = (
58
+ environment: string | undefined,
59
+ mailSenderModules?: readonly Module[],
60
+ ): string[] =>
61
+ buildModules(resolveConfig(SINGLE_ENV), {
62
+ ...(environment === undefined ? {} : { environment }),
63
+ ...(mailSenderModules === undefined ? {} : { mailSenderModules }),
64
+ })
65
+ .map((module) => module.name)
66
+ .filter((name) => name === DEVELOPMENT || name === SMTP || name === OWN);
67
+
68
+ const ENVIRONMENTS = ["development", "production", "staging", "test", "Development"] as const;
69
+
70
+ describe("the template's mail sender", () => {
71
+ let current: Composition | undefined;
72
+ afterEach(async () => {
73
+ await current?.handle.dispose();
74
+ current = undefined;
75
+ });
76
+
77
+ it("is the development sender in development, and none where no environment is named", () => {
78
+ expect(senders("development")).toEqual([DEVELOPMENT]);
79
+ expect(senders(undefined)).toEqual([]);
80
+ });
81
+
82
+ it("is the SMTP sender's module under any other environment", () => {
83
+ for (const environment of ["production", "staging", "test", "Development"]) {
84
+ expect(senders(environment), environment).toEqual([SMTP]);
85
+ }
86
+ });
87
+
88
+ it("fills the slot with the development sender when the composition boots in development", async () => {
89
+ current = await compose({ environment: "development" });
90
+ expect((current.handle.components.mailSender as MailSender | undefined)?.kind).toBe(
91
+ "standard-development",
92
+ );
93
+ });
94
+
95
+ it("boots in production with the SMTP sender's module installed and no SMTP settings, building no sender where nothing reads the slot", async () => {
96
+ current = await compose();
97
+ expect(current.modules.map((module) => module.name)).toContain(SMTP);
98
+ expect(current.handle.components.mailSender).toBeUndefined();
99
+ });
100
+
101
+ describe("given the deployment's own sender modules", () => {
102
+ it("installs them in place of the bundled sender, under every environment name and none", () => {
103
+ for (const environment of [...ENVIRONMENTS, undefined]) {
104
+ expect(senders(environment, [ownSenderModule]), String(environment)).toEqual([OWN]);
105
+ }
106
+ });
107
+
108
+ it("installs no sender at all when the list is empty", () => {
109
+ for (const environment of [...ENVIRONMENTS, undefined]) {
110
+ expect(senders(environment, []), String(environment)).toEqual([]);
111
+ }
112
+ });
113
+
114
+ it.each(["development", "production"])(
115
+ "fills the slot with the deployment's sender when the composition boots in %s",
116
+ async (environment) => {
117
+ current = await compose({ environment, mailSenderModules: [ownSenderModule] });
118
+ const names = current.modules.map((module) => module.name);
119
+ expect(names).toContain(OWN);
120
+ expect(names).not.toContain(DEVELOPMENT);
121
+ expect(names).not.toContain(SMTP);
122
+ expect(current.handle.components.mailSender).toBe(OWN_SENDER);
123
+ },
124
+ );
125
+
126
+ it("boots in production with no sender when the list is empty", async () => {
127
+ current = await compose({ environment: "production", mailSenderModules: [] });
128
+ const names = current.modules.map((module) => module.name);
129
+ expect(names).not.toContain(DEVELOPMENT);
130
+ expect(names).not.toContain(SMTP);
131
+ expect(current.handle.components.mailSender).toBeUndefined();
132
+ });
133
+ });
134
+ });
@@ -0,0 +1,328 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * The development compose run, `docker-compose.yml`, with MFA on as the
19
+ * template ships it, and the Mailpit overlay, `docker-compose.mailpit.yml`: a
20
+ * development run whose mail goes through the SMTP sender to Mailpit. It is an
21
+ * overlay on `docker-compose.yml`, so a plain `docker compose up` starts no
22
+ * Mailpit, and the production file names none. The compose files are read as
23
+ * the fixed-shape files they are, and the process each run describes is booted
24
+ * from the shipped files, as `app.mts` boots them, under the environment the
25
+ * run sets: `.env.example`'s lines, then each compose file's `environment`, the
26
+ * overlay's last. Redis is a stand-in: nothing here issues a command.
27
+ */
28
+
29
+ import { generateKeyPairSync } from "node:crypto";
30
+ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
31
+ import { tmpdir } from "node:os";
32
+ import { join } from "node:path";
33
+ import { fileURLToPath } from "node:url";
34
+ import {
35
+ createApp,
36
+ type MailSender,
37
+ memoryRefreshTokenFamilyStoreModule,
38
+ } from "@o3co/auth-provider-core";
39
+ import {
40
+ standardDevelopmentMailSenderModule,
41
+ standardSmtpMailSenderModule,
42
+ } from "@o3co/auth-provider-standard";
43
+ import { afterEach, describe, expect, it, vi } from "vitest";
44
+ import { buildModules } from "#/buildModules.mjs";
45
+ import { readOwnLayers, readSwitches, resolveConfigPaths, resolveForBoot } from "#/configPath.mjs";
46
+ import { createRecordingLogger } from "./all-modules-composition.fixture.mjs";
47
+
48
+ vi.mock("redis", () => ({
49
+ createClient: vi.fn(() => ({
50
+ connect: vi.fn().mockResolvedValue(undefined),
51
+ quit: vi.fn().mockResolvedValue(undefined),
52
+ ping: vi.fn().mockResolvedValue("PONG"),
53
+ on: vi.fn(),
54
+ })),
55
+ }));
56
+
57
+ vi.mock("connect-redis", async () => {
58
+ const { EventEmitter } = await import("node:events");
59
+ // express-session subscribes to store events, so the stand-in is an emitter.
60
+ return {
61
+ RedisStore: class MockRedisStore extends EventEmitter {
62
+ get(): unknown {
63
+ return undefined;
64
+ }
65
+ set(): void {}
66
+ destroy(): void {}
67
+ },
68
+ };
69
+ });
70
+
71
+ vi.mock("ioredis", () => {
72
+ const explicit: Record<string, unknown> = {
73
+ on: () => undefined,
74
+ quit: async () => "OK",
75
+ disconnect: () => undefined,
76
+ ping: async () => "PONG",
77
+ };
78
+ const makeMockRedis = (): object =>
79
+ new Proxy(
80
+ {},
81
+ {
82
+ get(_target, prop) {
83
+ // A function-valued `then` would make the instance a thenable.
84
+ if (typeof prop !== "string" || prop === "then") return undefined;
85
+ if (prop === "duplicate") return makeMockRedis;
86
+ if (prop in explicit) return explicit[prop];
87
+ return async () => null;
88
+ },
89
+ },
90
+ );
91
+ function MockRedis(): object {
92
+ return makeMockRedis();
93
+ }
94
+ return { Redis: MockRedis, default: MockRedis };
95
+ });
96
+
97
+ const standaloneDir = fileURLToPath(new URL("../..", import.meta.url));
98
+ const configDir = fileURLToPath(new URL("../../config", import.meta.url));
99
+ const read = (rel: string): string => readFileSync(join(standaloneDir, rel), "utf8");
100
+
101
+ const OVERLAY = "docker-compose.mailpit.yml";
102
+
103
+ /** The lines of a service's block in a compose file, comments and blank lines left out. */
104
+ function serviceBlock(rel: string, name: string): string[] {
105
+ const lines = read(rel).split("\n");
106
+ const services = lines.findIndex((line) => /^services:\s*$/.test(line));
107
+ const start = lines.findIndex(
108
+ (line, at) => at > services && new RegExp(`^ {2}${name}:\\s*$`).test(line),
109
+ );
110
+ if (services === -1 || start === -1) return [];
111
+ const block: string[] = [];
112
+ for (const line of lines.slice(start + 1)) {
113
+ if (line.trim() === "" || /^\s*#/.test(line)) continue;
114
+ if (!/^ {4}/.test(line)) break;
115
+ block.push(line);
116
+ }
117
+ return block;
118
+ }
119
+
120
+ const unquote = (text: string): string => text.trim().replace(/^["']|["']$/g, "");
121
+
122
+ /** A scalar key of a service's block. */
123
+ function scalar(block: readonly string[], key: string): string | undefined {
124
+ for (const line of block) {
125
+ const match = new RegExp(`^ {4}${key}:\\s*(\\S.*)$`).exec(line);
126
+ if (match) return unquote(match[1] as string);
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ /** The entries under a key of a service's block, each trimmed. */
132
+ function entries(block: readonly string[], key: string): string[] {
133
+ const at = block.findIndex((line) => new RegExp(`^ {4}${key}:\\s*$`).test(line));
134
+ if (at === -1) return [];
135
+ const found: string[] = [];
136
+ for (const line of block.slice(at + 1)) {
137
+ if (!/^ {6}/.test(line)) break;
138
+ found.push(line.trim());
139
+ }
140
+ return found;
141
+ }
142
+
143
+ /** The `- "…"` entries of a list, unquoted. */
144
+ const listOf = (lines: readonly string[]): string[] =>
145
+ lines.map((line) => unquote(line.replace(/^-\s*/, "")));
146
+
147
+ /** `.env.example`'s uncommented lines: what a `.env` copied from it sets. */
148
+ function dotenvExample(): Record<string, string> {
149
+ const env: Record<string, string> = {};
150
+ for (const line of read(".env.example").split("\n")) {
151
+ const match = /^([A-Z][A-Z0-9_]*)=(.*)$/.exec(line);
152
+ if (match) env[match[1] as string] = match[2] as string;
153
+ }
154
+ return env;
155
+ }
156
+
157
+ /**
158
+ * A service's `environment`, interpolated as compose does from the project's
159
+ * `.env`: `${VAR:-default}` is the variable when it is set and not empty, the
160
+ * default otherwise.
161
+ */
162
+ function environmentOf(
163
+ rel: string,
164
+ service: string,
165
+ dotenv: Readonly<Record<string, string>>,
166
+ ): Record<string, string> {
167
+ const env: Record<string, string> = {};
168
+ for (const line of entries(serviceBlock(rel, service), "environment")) {
169
+ const match = /^([A-Z][A-Z0-9_]*):\s*(.*)$/.exec(line);
170
+ if (!match) continue;
171
+ env[match[1] as string] = unquote(match[2] as string).replace(
172
+ /\$\{([A-Z][A-Z0-9_]*):-([^}]*)\}/g,
173
+ (_, name: string, fallback: string) => (dotenv[name] ? dotenv[name] : fallback),
174
+ );
175
+ }
176
+ return env;
177
+ }
178
+
179
+ describe("Mailpit runs only in the overlay", () => {
180
+ it("is not a service of the development or the production compose file", () => {
181
+ expect(serviceBlock("docker-compose.yml", "mailpit")).toEqual([]);
182
+ expect(serviceBlock("docker-compose.production.yml", "mailpit")).toEqual([]);
183
+ expect(read("docker-compose.production.yml")).not.toMatch(/mailpit/i);
184
+ });
185
+
186
+ it("runs a pinned Mailpit image in the app's network namespace", () => {
187
+ const mailpit = serviceBlock(OVERLAY, "mailpit");
188
+ expect(scalar(mailpit, "image")).toMatch(/^axllent\/mailpit:v\d+\.\d+\.\d+$/);
189
+ expect(scalar(mailpit, "network_mode")).toBe("service:app");
190
+ });
191
+
192
+ it("publishes Mailpit's web UI on loopback, from the app service that owns the namespace", () => {
193
+ expect(listOf(entries(serviceBlock(OVERLAY, "app"), "ports"))).toContain("127.0.0.1:8025:8025");
194
+ });
195
+
196
+ it("points the SMTP sender at Mailpit over the app's loopback, in plaintext", () => {
197
+ expect(environmentOf(OVERLAY, "app", {})).toMatchObject({
198
+ STANDARD_SMTP_MAIL_SENDER_HOST: "localhost",
199
+ STANDARD_SMTP_MAIL_SENDER_PORT: "1025",
200
+ STANDARD_SMTP_MAIL_SENDER_SECURE: "none",
201
+ });
202
+ });
203
+ });
204
+
205
+ describe("the process each development run describes", () => {
206
+ const handles: { dispose(): Promise<void> }[] = [];
207
+ afterEach(async () => {
208
+ for (const handle of handles.splice(0)) await handle.dispose();
209
+ });
210
+
211
+ const signingKey = generateKeyPairSync("ed25519", {
212
+ publicKeyEncoding: { type: "spki", format: "pem" },
213
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
214
+ });
215
+ const clientsFile = (() => {
216
+ const file = join(mkdtempSync(join(tmpdir(), "mailpit-compose-")), "clients.yaml");
217
+ writeFileSync(file, "");
218
+ return file;
219
+ })();
220
+
221
+ /** What the operator writes into `.env` beside `.env.example`'s lines: its required blanks. */
222
+ const OPERATOR: Readonly<Record<string, string>> = {
223
+ OAUTH_JWT_ISSUER: "http://localhost:3000",
224
+ KEY_STORE_LOCAL_PRIVATE_KEY: signingKey.privateKey,
225
+ KEY_STORE_LOCAL_PUBLIC_KEY: signingKey.publicKey,
226
+ SESSION_STORE_SECRET: "mailpit-compose-session-secret.at-least-32-bytes.ok",
227
+ REPOSITORIES_USER_HTTP_AUTHENTICATE_URL: "https://users.test/authenticate",
228
+ REPOSITORIES_USER_HTTP_AUTHENTICATE_BY_TOKEN_URL: "https://users.test/by-token",
229
+ REPOSITORIES_CLIENT_YAML_PATH: clientsFile,
230
+ };
231
+
232
+ /**
233
+ * The container's environment: `.env`, then each compose file's
234
+ * `environment`, the overlay's last unless `overlay` is false.
235
+ */
236
+ function containerEnv(overlay = true): Record<string, string> {
237
+ const dotenv: Record<string, string> = { ...dotenvExample(), ...OPERATOR };
238
+ // The pem pair is given inline here; the paths name files this test has not written.
239
+ delete dotenv.KEY_STORE_LOCAL_PRIVATE_KEY_PATH;
240
+ delete dotenv.KEY_STORE_LOCAL_PUBLIC_KEY_PATH;
241
+ return {
242
+ ...Object.fromEntries(Object.entries(dotenv).filter(([, value]) => value !== "")),
243
+ ...environmentOf("docker-compose.yml", "app", dotenv),
244
+ ...(overlay ? environmentOf(OVERLAY, "app", dotenv) : {}),
245
+ };
246
+ }
247
+
248
+ it("boots docker-compose.yml's run with MFA required: development, the development mail sender, the MFA stores on its Redis", async () => {
249
+ const env = containerEnv(false);
250
+ // `app.mts`: CONFIG_ENV, then NODE_ENV, then development; the run sets neither.
251
+ expect(env.CONFIG_ENV ?? env.NODE_ENV).toBeUndefined();
252
+ const { applicationConfPath, envConfPath } = resolveConfigPaths(configDir, "development");
253
+ const own = readOwnLayers([envConfPath, applicationConfPath], { env });
254
+ const switches = readSwitches(own);
255
+ expect(switches.mfaMode).toBe("required");
256
+ // A hot reload restarts the process on every save, and Redis keeps the
257
+ // factors, and the sessions beside them, across it.
258
+ expect(switches.adapters).toMatchObject({
259
+ mfaFactorStore: "redis",
260
+ mfaTransactionStore: "redis",
261
+ });
262
+
263
+ const modules = buildModules(switches, {
264
+ environment: "development",
265
+ logger: createRecordingLogger(),
266
+ refreshTokenFamilyModules: [memoryRefreshTokenFamilyStoreModule],
267
+ });
268
+ const handle = await createApp({
269
+ modules,
270
+ bootstrapComponents: {
271
+ config: resolveForBoot(own, modules, switches),
272
+ pathResolver: (s: string) => s,
273
+ logger: createRecordingLogger(),
274
+ },
275
+ });
276
+ handles.push(handle);
277
+ expect((handle.components.mailSender as MailSender | undefined)?.kind).toBe(
278
+ "standard-development",
279
+ );
280
+ expect((handle.components.config as { mfa?: { mode?: unknown } } | undefined)?.mfa?.mode).toBe(
281
+ "required",
282
+ );
283
+ });
284
+
285
+ it("selects a configuration that is not development, so the SMTP sender is installed", () => {
286
+ const configEnv = containerEnv().CONFIG_ENV;
287
+ expect(configEnv).toBeDefined();
288
+ expect(configEnv).not.toBe("development");
289
+ // A missing `{ENV}.conf` is fatal at boot.
290
+ expect(existsSync(resolveConfigPaths(configDir, configEnv as string).envConfPath)).toBe(true);
291
+ });
292
+
293
+ it("boots with MFA on and the SMTP sender in the mailSender slot, relaying to Mailpit", async () => {
294
+ const env = containerEnv();
295
+ const configEnv = env.CONFIG_ENV as string;
296
+ const { applicationConfPath, envConfPath } = resolveConfigPaths(configDir, configEnv);
297
+ const own = readOwnLayers([envConfPath, applicationConfPath], { env });
298
+ const switches = readSwitches(own);
299
+ expect(switches.mfaMode).toBe("required");
300
+
301
+ const modules = buildModules(switches, {
302
+ environment: configEnv,
303
+ logger: createRecordingLogger(),
304
+ refreshTokenFamilyModules: [memoryRefreshTokenFamilyStoreModule],
305
+ });
306
+ const names = modules.map((module) => module.name);
307
+ expect(names).toContain(standardSmtpMailSenderModule.name);
308
+ expect(names).not.toContain(
309
+ standardDevelopmentMailSenderModule({ environment: "development" }).name,
310
+ );
311
+
312
+ const handle = await createApp({
313
+ modules,
314
+ bootstrapComponents: {
315
+ config: resolveForBoot(own, modules, switches),
316
+ pathResolver: (s: string) => s,
317
+ logger: createRecordingLogger(),
318
+ },
319
+ });
320
+ handles.push(handle);
321
+ expect((handle.components.mailSender as MailSender | undefined)?.kind).toBe("standard-smtp");
322
+ expect(
323
+ (handle.components.config as Record<string, unknown> | undefined)?.[
324
+ "standard-smtp-mail-sender"
325
+ ],
326
+ ).toMatchObject({ host: "localhost", port: 1025, secure: "none" });
327
+ });
328
+ });