@podosoft/podokit 1.4.1 → 1.5.0

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 (97) hide show
  1. package/dist/deploy-compose-profile.js +2 -2
  2. package/dist/deploy-compose-render.js +3 -1
  3. package/dist/deploy-profile.js +2 -2
  4. package/dist/deploy-render.js +16 -8
  5. package/dist/deploy-schema.d.ts +7 -0
  6. package/dist/deploy-schema.js +40 -0
  7. package/dist/lockfile.d.ts +8 -1
  8. package/dist/lockfile.js +23 -4
  9. package/dist/provider.d.ts +1 -0
  10. package/dist/provider.js +5 -2
  11. package/dist/templates/fullstack/AGENTS.md +27 -2
  12. package/dist/templates/fullstack/README.md +1 -1
  13. package/dist/templates/fullstack/apps/api/package.json +1 -1
  14. package/dist/templates/fullstack/apps/api/scripts/run-migrations.mjs +4 -0
  15. package/dist/templates/fullstack/apps/api/src/app.extensions.ts +7 -2
  16. package/dist/templates/fullstack/apps/api/src/app.ts +6 -3
  17. package/dist/templates/fullstack/apps/api/src/config/env.validation.ts +28 -0
  18. package/dist/templates/fullstack/apps/api/src/config/providers.ts +4 -2
  19. package/dist/templates/fullstack/apps/api/src/config/server-options.spec.ts +17 -6
  20. package/dist/templates/fullstack/apps/api/src/config/server-options.ts +5 -8
  21. package/dist/templates/fullstack/apps/api/src/core/client-address.spec.ts +82 -0
  22. package/dist/templates/fullstack/apps/api/src/core/client-address.ts +68 -0
  23. package/dist/templates/fullstack/apps/api/src/core/services.ts +30 -0
  24. package/dist/templates/fullstack/apps/api/src/database/database.spec.ts +66 -0
  25. package/dist/templates/fullstack/apps/api/src/database/database.ts +34 -11
  26. package/dist/templates/fullstack/apps/api/src/database/run-migrations.spec.ts +54 -6
  27. package/dist/templates/fullstack/apps/web/Dockerfile +5 -1
  28. package/dist/templates/fullstack/apps/web/src/lib/server/api.test.ts +116 -0
  29. package/dist/templates/fullstack/apps/web/src/lib/server/api.ts +34 -4
  30. package/dist/templates/fullstack/apps/web/src/lib/server/backend-proxy.test.ts +436 -6
  31. package/dist/templates/fullstack/apps/web/src/lib/server/backend-proxy.ts +352 -38
  32. package/dist/templates/fullstack/apps/web/src/lib/server/body-limits.ts +5 -2
  33. package/dist/templates/fullstack/apps/web/src/lib/server/proxy-timeouts.ts +22 -0
  34. package/dist/templates/fullstack/apps/web/src/routes/healthz/+server.ts +13 -0
  35. package/dist/templates/fullstack/dot-env.docker.example +6 -0
  36. package/dist/templates/fullstack/dot-env.example +23 -0
  37. package/dist/templates/fullstack/infra/k3s/configmap.yaml +3 -0
  38. package/dist/templates/fullstack/infra/k3s/web-deployment.yaml +6 -3
  39. package/dist/templates/fullstack/tests/api/health.api.spec.ts +8 -0
  40. package/dist/templates/modules/admin-dashboard/files/apps/api/src/account-sessions/account-sessions.routes.spec.ts +152 -0
  41. package/dist/templates/modules/admin-dashboard/files/apps/api/src/account-sessions/account-sessions.routes.ts +112 -0
  42. package/dist/templates/modules/admin-dashboard/files/apps/api/src/admin-sessions/admin-sessions.revoker.ts +24 -0
  43. package/dist/templates/modules/admin-dashboard/files/apps/api/src/admin-sessions/admin-sessions.service.spec.ts +18 -0
  44. package/dist/templates/modules/admin-dashboard/files/apps/api/src/admin-sessions/admin-sessions.service.ts +36 -13
  45. package/dist/templates/modules/admin-dashboard/files/apps/api/src/admin.module.ts +13 -1
  46. package/dist/templates/modules/admin-dashboard/files/apps/web/src/hooks.server.test.ts +24 -1
  47. package/dist/templates/modules/admin-dashboard/files/apps/web/src/lib/account-sessions.test.ts +33 -0
  48. package/dist/templates/modules/admin-dashboard/files/apps/web/src/lib/account-sessions.ts +34 -0
  49. package/dist/templates/modules/admin-dashboard/files/apps/web/src/lib/components/account-page.svelte +62 -38
  50. package/dist/templates/modules/admin-dashboard/files/apps/web/src/lib/components/table-toolbar.svelte +3 -1
  51. package/dist/templates/modules/admin-dashboard/files/apps/web/src/lib/server/runtime-context.test.ts +6 -0
  52. package/dist/templates/modules/admin-dashboard/files/apps/web/src/lib/server/runtime-context.ts +5 -0
  53. package/dist/templates/modules/admin-dashboard/files/tests/api/account-sessions.api.spec.ts +55 -0
  54. package/dist/templates/modules/admin-dashboard/files/tests/api/auth-config.api.spec.ts +167 -154
  55. package/dist/templates/modules/admin-dashboard/files/tests/api/auth.api.spec.ts +94 -57
  56. package/dist/templates/modules/admin-dashboard/files/tests/api/exclusive.api.spec.ts +75 -0
  57. package/dist/templates/modules/admin-dashboard/files/tests/api/site-settings.api.spec.ts +49 -39
  58. package/dist/templates/modules/admin-dashboard/files/tests/api/users-admin.api.spec.ts +26 -0
  59. package/dist/templates/modules/admin-dashboard/files/tests/helpers/devices.ts +25 -0
  60. package/dist/templates/modules/admin-dashboard/files/tests/helpers/exclusive.ts +80 -0
  61. package/dist/templates/modules/admin-dashboard/files/tests/seed.setup.ts +3 -10
  62. package/dist/templates/modules/admin-dashboard/files/tests/ui/account-sessions.ui.spec.ts +46 -0
  63. package/dist/templates/modules/admin-dashboard/files/tests/ui/account.ui.spec.ts +54 -47
  64. package/dist/templates/modules/admin-dashboard/files/tests/ui/appearance.ui.spec.ts +15 -11
  65. package/dist/templates/modules/admin-dashboard/files/tests/ui/auth.ui.spec.ts +35 -31
  66. package/dist/templates/modules/admin-dashboard/files/tests/ui/general-effects.ui.spec.ts +90 -76
  67. package/dist/templates/modules/admin-dashboard/files/tests/ui/i18n.ui.spec.ts +19 -15
  68. package/dist/templates/modules/admin-dashboard/files/tests/ui/oidc.ui.spec.ts +17 -3
  69. package/dist/templates/modules/admin-dashboard/files/tests/ui/request-budget.ui.spec.ts +15 -6
  70. package/dist/templates/modules/admin-dashboard/files/tests/ui/settings-dialogs.ui.spec.ts +71 -64
  71. package/dist/templates/modules/admin-dashboard/files/tests/ui/settings.ui.spec.ts +89 -79
  72. package/dist/templates/modules/admin-dashboard/files/tests/ui/table-toolbar.ui.spec.ts +25 -0
  73. package/dist/templates/modules/admin-dashboard/files/tests/ui/two-factor.ui.spec.ts +54 -50
  74. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit-hook.ts +2 -1
  75. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit.service.spec.ts +16 -0
  76. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit.service.ts +2 -1
  77. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.module.ts +4 -1
  78. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.service.spec.ts +54 -6
  79. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.service.ts +26 -4
  80. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.ts +19 -8
  81. package/dist/templates/modules/auth/files/apps/api/src/auth/feature-gate.spec.ts +83 -0
  82. package/dist/templates/modules/auth/files/apps/api/src/auth/feature-gate.ts +51 -7
  83. package/dist/templates/modules/auth/files/apps/api/src/auth/revoke-other-sessions.spec.ts +56 -0
  84. package/dist/templates/modules/auth/files/apps/api/src/auth/revoke-other-sessions.ts +45 -0
  85. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.config.spec.ts +2 -59
  86. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.config.ts +0 -65
  87. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.identity.spec.ts +82 -21
  88. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.identity.ts +54 -15
  89. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.module.spec.ts +43 -5
  90. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.module.ts +10 -2
  91. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.routes.spec.ts +61 -3
  92. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.routes.ts +48 -15
  93. package/dist/templates/modules/rate-limit/files/tests/api/rate-limit.api.spec.ts +20 -9
  94. package/dist/templates/modules/rate-limit/module.manifest.json +6 -9
  95. package/dist/templates/todo/AGENTS.md +41 -5
  96. package/dist/templates/todo/README.md +1 -1
  97. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import { expect, test } from "@playwright/test";
2
2
  import { createPublicKey, verify, type JsonWebKey } from "node:crypto";
3
3
  import { ADMIN, USER } from "../helpers/accounts";
4
+ import { exclusive } from "../helpers/exclusive";
4
5
  import { clearSms, smsSinkReachable, waitForSmsOtp } from "../helpers/sms";
5
6
  import { totpCode } from "../helpers/totp";
6
7
 
@@ -144,46 +145,49 @@ test("two-factor: regenerating backup codes invalidates the old set", async ({ p
144
145
  });
145
146
 
146
147
  test("require-2fa: gates an un-enrolled user until they enrol", async ({ playwright }) => {
147
- const admin = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
148
- const caps = await (await admin.get("/api/account/capabilities")).json();
149
- test.skip(!caps?.twoFactor, "two-factor not enabled");
150
- await admin.post("/api/auth/sign-in/email", { data: { email: ADMIN.email, password: ADMIN.password } });
151
-
152
- const user = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
153
- const email = `rq-${Date.now()}@example.com`;
154
- const pw = "Podokit3e-Str0ng!pw";
155
- await user.post("/api/auth/sign-up/email", { data: { email, password: pw, name: "RQ" } });
156
-
157
- try {
158
- // Turn the policy on (admin; the toggle endpoint is allow-listed by the guard).
159
- await admin.put("/api/account/settings", { data: { require2fa: true } });
160
- // Capabilities carry the same policy as the dedicated endpoint.
161
- await expect(async () => {
162
- expect((await (await admin.get("/api/account/capabilities")).json()).require2fa).toBe(true);
163
- expect(await (await admin.get("/api/account/require-2fa")).json()).toEqual({ require2fa: true });
164
- }).toPass({ timeout: 8000 });
165
- // The guard caches for a few seconds — poll until the un-enrolled user is gated.
166
- await expect(async () => {
167
- expect((await user.get("/api/account/me")).status()).toBe(403);
168
- }).toPass({ timeout: 8000 });
169
-
170
- // Enrolling restores access.
171
- const enable = await (await user.post("/api/auth/two-factor/enable", { data: { password: pw } })).json();
172
- await user.post("/api/auth/two-factor/verify-totp", { data: { code: totpCode(enable.totpURI) } });
173
- expect((await user.get("/api/account/me")).status()).toBe(200);
174
- } finally {
175
- // Always turn it back off so the shared (un-enrolled) sessions aren't gated.
176
- await admin.put("/api/account/settings", { data: { require2fa: false } });
177
- await expect(async () => {
178
- const probe = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
179
- await probe.post("/api/auth/sign-in/email", { data: { email: USER.email, password: USER.password } });
180
- const status = (await probe.get("/api/account/me")).status();
181
- await probe.dispose();
182
- expect(status).toBe(200);
183
- }).toPass({ timeout: 8000 });
184
- await admin.dispose();
185
- await user.dispose();
186
- }
148
+ test.slow();
149
+ await exclusive("require2fa", async () => {
150
+ const admin = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
151
+ const caps = await (await admin.get("/api/account/capabilities")).json();
152
+ test.skip(!caps?.twoFactor, "two-factor not enabled");
153
+ await admin.post("/api/auth/sign-in/email", { data: { email: ADMIN.email, password: ADMIN.password } });
154
+
155
+ const user = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
156
+ const email = `rq-${Date.now()}@example.com`;
157
+ const pw = "Podokit3e-Str0ng!pw";
158
+ await user.post("/api/auth/sign-up/email", { data: { email, password: pw, name: "RQ" } });
159
+
160
+ try {
161
+ // Turn the policy on (admin; the toggle endpoint is allow-listed by the guard).
162
+ await admin.put("/api/account/settings", { data: { require2fa: true } });
163
+ // Capabilities carry the same policy as the dedicated endpoint.
164
+ await expect(async () => {
165
+ expect((await (await admin.get("/api/account/capabilities")).json()).require2fa).toBe(true);
166
+ expect(await (await admin.get("/api/account/require-2fa")).json()).toEqual({ require2fa: true });
167
+ }).toPass({ timeout: 8000 });
168
+ // The guard caches for a few seconds — poll until the un-enrolled user is gated.
169
+ await expect(async () => {
170
+ expect((await user.get("/api/account/me")).status()).toBe(403);
171
+ }).toPass({ timeout: 8000 });
172
+
173
+ // Enrolling restores access.
174
+ const enable = await (await user.post("/api/auth/two-factor/enable", { data: { password: pw } })).json();
175
+ await user.post("/api/auth/two-factor/verify-totp", { data: { code: totpCode(enable.totpURI) } });
176
+ expect((await user.get("/api/account/me")).status()).toBe(200);
177
+ } finally {
178
+ // Always turn it back off so the shared (un-enrolled) sessions aren't gated.
179
+ await admin.put("/api/account/settings", { data: { require2fa: false } });
180
+ await expect(async () => {
181
+ const probe = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
182
+ await probe.post("/api/auth/sign-in/email", { data: { email: USER.email, password: USER.password } });
183
+ const status = (await probe.get("/api/account/me")).status();
184
+ await probe.dispose();
185
+ expect(status).toBe(200);
186
+ }).toPass({ timeout: 8000 });
187
+ await admin.dispose();
188
+ await user.dispose();
189
+ }
190
+ });
187
191
  });
188
192
 
189
193
  test("multi-session holds several accounts and switches between them", async ({ playwright }) => {
@@ -380,9 +384,39 @@ test("an organization can have a parent and manager members", async ({ playwrigh
380
384
  await ctx.dispose();
381
385
  });
382
386
 
383
- // OIDC discovery + the enabled/disabled behaviour is covered by the front-channel
384
- // test in tests/ui/oidc.ui.spec.ts (which owns toggling the oidcProvider flag), and
385
- // the server-side gate is covered generically by the feature-toggle test above.
387
+ test("the OIDC provider's discovery and endpoints follow its setting", async ({ playwright }) => {
388
+ // The provider's metadata is answered before endpoint hooks run, so it needs its
389
+ // own check that "off" hides it. The lock keeps tests/ui/oidc.ui.spec.ts, which
390
+ // also toggles the provider, from running at the same time.
391
+ test.slow();
392
+ const admin = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
393
+ await admin.post("/api/auth/sign-in/email", { data: { email: ADMIN.email, password: ADMIN.password } });
394
+ const status = (path: string): Promise<number> => admin.get(path).then((r) => r.status());
395
+ const discovery = [
396
+ "/api/auth/.well-known/openid-configuration",
397
+ "/api/auth/.well-known/oauth-authorization-server",
398
+ ];
399
+ const allStatuses = (): Promise<number[]> =>
400
+ Promise.all([...discovery, "/api/auth/oauth2/authorize?client_id=probe"].map(status));
401
+
402
+ await exclusive("oidc-provider", async () => {
403
+ try {
404
+ expect((await admin.put("/api/account/settings", { data: { oidcProvider: false } })).ok()).toBeTruthy();
405
+ await expect.poll(allStatuses, { timeout: 8000 }).toEqual([404, 404, 404]);
406
+ // The jwt plugin's keys and session tokens are not part of the provider.
407
+ expect(await status("/api/auth/jwks")).toBe(200);
408
+
409
+ expect((await admin.put("/api/account/settings", { data: { oidcProvider: true } })).ok()).toBeTruthy();
410
+ await expect.poll(() => Promise.all(discovery.map(status)), { timeout: 8000 }).toEqual([200, 200]);
411
+ const metadata = await (await admin.get(discovery[0]!)).json();
412
+ expect(metadata.authorization_endpoint).toContain("/api/auth/oauth2/authorize");
413
+ } finally {
414
+ expect((await admin.put("/api/account/settings", { data: { oidcProvider: false } })).ok()).toBeTruthy();
415
+ }
416
+ await expect.poll(allStatuses, { timeout: 8000 }).toEqual([404, 404, 404]);
417
+ });
418
+ await admin.dispose();
419
+ });
386
420
 
387
421
  test("only admins can change settings @smoke", async ({ playwright }) => {
388
422
  const userCtx = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
@@ -393,24 +427,27 @@ test("only admins can change settings @smoke", async ({ playwright }) => {
393
427
  });
394
428
 
395
429
  test("disabling a feature blocks its endpoint server-side and re-enabling restores it @smoke", async ({ playwright }) => {
396
- // Uses a fresh admin context (not the shared storageState) so it never rotates
397
- // the seeded session. Toggles a flag and confirms the feature gate enforces it.
398
- const admin = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
399
- await admin.post("/api/auth/sign-in/email", { data: { email: ADMIN.email, password: ADMIN.password } });
400
- const caps = await (await admin.get("/api/account/capabilities")).json();
401
- test.skip(!caps?.magicLink, "magic link not enabled");
430
+ test.slow();
431
+ await exclusive("magic-link", async () => {
432
+ // Uses a fresh admin context (not the shared storageState) so it never rotates
433
+ // the seeded session. Toggles a flag and confirms the feature gate enforces it.
434
+ const admin = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
435
+ await admin.post("/api/auth/sign-in/email", { data: { email: ADMIN.email, password: ADMIN.password } });
436
+ const caps = await (await admin.get("/api/account/capabilities")).json();
437
+ test.skip(!caps?.magicLink, "magic link not enabled");
402
438
 
403
- // A disabled feature's endpoint 404s; the gate reads the flag through a short cache.
404
- const status = (): Promise<number> =>
405
- admin.post("/api/auth/sign-in/magic-link", { data: { email: "probe@example.com" } }).then((r) => r.status());
439
+ // A disabled feature's endpoint 404s; the gate reads the flag through a short cache.
440
+ const status = (): Promise<number> =>
441
+ admin.post("/api/auth/sign-in/magic-link", { data: { email: "probe@example.com" } }).then((r) => r.status());
406
442
 
407
- expect((await admin.put("/api/account/settings", { data: { magicLink: false } })).ok()).toBeTruthy();
408
- await expect.poll(status, { timeout: 8000 }).toBe(404);
443
+ expect((await admin.put("/api/account/settings", { data: { magicLink: false } })).ok()).toBeTruthy();
444
+ await expect.poll(status, { timeout: 8000 }).toBe(404);
409
445
 
410
- expect((await admin.put("/api/account/settings", { data: { magicLink: true } })).ok()).toBeTruthy();
411
- await expect.poll(status, { timeout: 8000 }).not.toBe(404);
446
+ expect((await admin.put("/api/account/settings", { data: { magicLink: true } })).ok()).toBeTruthy();
447
+ await expect.poll(status, { timeout: 8000 }).not.toBe(404);
412
448
 
413
- await admin.dispose();
449
+ await admin.dispose();
450
+ });
414
451
  });
415
452
 
416
453
  test("sign-in with a wrong password is rejected", async ({ request }) => {
@@ -0,0 +1,75 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, utimesSync, writeFileSync } from "node:fs";
4
+ import { rm } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { exclusive, lockPath } from "../helpers/exclusive";
7
+
8
+ // Checks the lock that specs changing shared settings hold. Names are unique per
9
+ // run so these never wait on, or release, a lock a real spec holds.
10
+ const unique = (label: string): string => `self-test-${label}-${process.pid}-${Date.now()}`;
11
+
12
+ test("exclusive releases its locks when the body fails", async () => {
13
+ const first = unique("first");
14
+ const second = unique("second");
15
+ await expect(
16
+ exclusive([second, first], async () => {
17
+ expect(existsSync(lockPath(first))).toBe(true);
18
+ expect(existsSync(lockPath(second))).toBe(true);
19
+ throw new Error("body failed");
20
+ }),
21
+ ).rejects.toThrow("body failed");
22
+ expect(existsSync(lockPath(first))).toBe(false);
23
+ expect(existsSync(lockPath(second))).toBe(false);
24
+
25
+ // The next holder gets the lock without waiting.
26
+ const started = Date.now();
27
+ await exclusive(first, async () => undefined);
28
+ expect(Date.now() - started).toBeLessThan(1_000);
29
+ });
30
+
31
+ test("exclusive runs holders of one lock one at a time", async () => {
32
+ const name = unique("serial");
33
+ const events: string[] = [];
34
+ const hold = (id: string): Promise<void> =>
35
+ exclusive(name, async () => {
36
+ events.push(`${id} start`);
37
+ await new Promise((resolve) => setTimeout(resolve, 100));
38
+ events.push(`${id} end`);
39
+ });
40
+ await Promise.all([hold("a"), hold("b")]);
41
+ expect(events.map((event) => event.split(" ")[1])).toEqual(["start", "end", "start", "end"]);
42
+ expect(existsSync(lockPath(name))).toBe(false);
43
+ });
44
+
45
+ test("exclusive takes over a lock left by a run that was killed", async () => {
46
+ const name = unique("stale");
47
+ mkdirSync(lockPath(name));
48
+ const longAgo = new Date(Date.now() - 10 * 60_000);
49
+ utimesSync(lockPath(name), longAgo, longAgo);
50
+ await expect(exclusive(name, async () => "acquired")).resolves.toBe("acquired");
51
+ expect(existsSync(lockPath(name))).toBe(false);
52
+ });
53
+
54
+ test("exclusive takes over a lock whose holder exited, such as after Ctrl-C", async () => {
55
+ const name = unique("exited");
56
+ const exited = spawnSync(process.execPath, ["-e", ""]).pid;
57
+ mkdirSync(lockPath(name));
58
+ writeFileSync(join(lockPath(name), "owner"), String(exited));
59
+ const started = Date.now();
60
+ await expect(exclusive(name, async () => "acquired")).resolves.toBe("acquired");
61
+ expect(Date.now() - started).toBeLessThan(1_000);
62
+ expect(existsSync(lockPath(name))).toBe(false);
63
+ });
64
+
65
+ test("exclusive waits for a lock whose holder is still running", async () => {
66
+ const name = unique("alive");
67
+ mkdirSync(lockPath(name));
68
+ writeFileSync(join(lockPath(name), "owner"), String(process.pid));
69
+ const waiting = exclusive(name, async () => "acquired");
70
+ await new Promise((resolve) => setTimeout(resolve, 500));
71
+ expect(existsSync(lockPath(name))).toBe(true);
72
+ // The holder finishes; the waiter then gets the lock.
73
+ await rm(lockPath(name), { recursive: true, force: true });
74
+ await expect(waiting).resolves.toBe("acquired");
75
+ });
@@ -1,6 +1,7 @@
1
1
  import { expect, test } from "@playwright/test";
2
2
  import { ADMIN } from "../helpers/accounts";
3
3
  import { expectObjectLength } from "../helpers/object-response";
4
+ import { exclusive } from "../helpers/exclusive";
4
5
 
5
6
  const base = process.env.E2E_BASE_URL ?? "http://localhost:5001";
6
7
  const origin = { origin: base };
@@ -18,29 +19,35 @@ async function adminCtx(playwright: import("@playwright/test").PlaywrightWorkerA
18
19
  }
19
20
 
20
21
  test("theme settings: valid preset/radius/accent round-trip", async ({ playwright }) => {
21
- const admin = await adminCtx(playwright);
22
- const put = await admin.put("/api/site/settings", {
23
- data: { themePreset: "slate", themeRadius: "0.75", brandColor: "#2563eb" },
24
- });
25
- expect(put.ok()).toBeTruthy();
22
+ test.slow();
23
+ await exclusive("site-theme", async () => {
24
+ const admin = await adminCtx(playwright);
25
+ const put = await admin.put("/api/site/settings", {
26
+ data: { themePreset: "slate", themeRadius: "0.75", brandColor: "#2563eb" },
27
+ });
28
+ expect(put.ok()).toBeTruthy();
26
29
 
27
- const anon = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
28
- const settings = await (await anon.get("/api/site/settings")).json();
29
- expect(settings.themePreset).toBe("slate");
30
- expect(settings.themeRadius).toBe("0.75");
31
- expect(settings.brandColor).toBe("#2563eb");
30
+ const anon = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
31
+ const settings = await (await anon.get("/api/site/settings")).json();
32
+ expect(settings.themePreset).toBe("slate");
33
+ expect(settings.themeRadius).toBe("0.75");
34
+ expect(settings.brandColor).toBe("#2563eb");
32
35
 
33
- // restore
34
- await admin.put("/api/site/settings", { data: { themePreset: "", themeRadius: "", brandColor: "" } });
35
- await anon.dispose();
36
+ // restore
37
+ await admin.put("/api/site/settings", { data: { themePreset: "", themeRadius: "", brandColor: "" } });
38
+ await anon.dispose();
39
+ });
36
40
  });
37
41
 
38
42
  test("theme settings: valid per-token overrides accepted", async ({ playwright }) => {
39
- const admin = await adminCtx(playwright);
40
- const overrides = JSON.stringify({ light: { primary: "#123456" }, dark: { background: "#0a0a0a" } });
41
- const put = await admin.put("/api/site/settings", { data: { themeOverrides: overrides } });
42
- expect(put.ok()).toBeTruthy();
43
- await admin.put("/api/site/settings", { data: { themeOverrides: "" } }); // restore
43
+ test.slow();
44
+ await exclusive("site-theme", async () => {
45
+ const admin = await adminCtx(playwright);
46
+ const overrides = JSON.stringify({ light: { primary: "#123456" }, dark: { background: "#0a0a0a" } });
47
+ const put = await admin.put("/api/site/settings", { data: { themeOverrides: overrides } });
48
+ expect(put.ok()).toBeTruthy();
49
+ await admin.put("/api/site/settings", { data: { themeOverrides: "" } }); // restore
50
+ });
44
51
  });
45
52
 
46
53
  test("theme settings: invalid values are rejected (no CSS injection)", async ({ playwright }) => {
@@ -62,29 +69,32 @@ test("theme settings: invalid values are rejected (no CSS injection)", async ({
62
69
  });
63
70
 
64
71
  test("site settings: one response shape and immediate reads after each write", async ({ playwright }) => {
65
- const admin = await adminCtx(playwright);
66
- const anon = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
67
- const before = await (await anon.get("/api/site/settings")).json() as Record<string, unknown>;
68
- expect(Object.keys(before)).toEqual([
69
- "name", "description", "supportEmail", "footerText", "brandColor", "themePreset", "themeRadius",
70
- "themeOverrides", "termsUrl", "privacyUrl", "locale", "timezone", "maintenanceMode", "allowSignup",
71
- "hasFavicon", "faviconVersion",
72
- ]);
73
- expect(typeof before.hasFavicon).toBe("boolean");
74
- expect(before.faviconVersion === null || typeof before.faviconVersion === "string").toBe(true);
72
+ test.slow();
73
+ await exclusive("site-general", async () => {
74
+ const admin = await adminCtx(playwright);
75
+ const anon = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
76
+ const before = await (await anon.get("/api/site/settings")).json() as Record<string, unknown>;
77
+ expect(Object.keys(before)).toEqual([
78
+ "name", "description", "supportEmail", "footerText", "brandColor", "themePreset", "themeRadius",
79
+ "themeOverrides", "termsUrl", "privacyUrl", "locale", "timezone", "maintenanceMode", "allowSignup",
80
+ "hasFavicon", "faviconVersion",
81
+ ]);
82
+ expect(typeof before.hasFavicon).toBe("boolean");
83
+ expect(before.faviconVersion === null || typeof before.faviconVersion === "string").toBe(true);
75
84
 
76
- try {
77
- // The second write lands while the first read is still cached; it must not be hidden.
78
- for (const footerText of ["first footer", "second footer"]) {
79
- expect((await admin.put("/api/site/settings", { data: { footerText } })).ok()).toBeTruthy();
80
- expect((await (await anon.get("/api/site/settings")).json()).footerText).toBe(footerText);
85
+ try {
86
+ // The second write lands while the first read is still cached; it must not be hidden.
87
+ for (const footerText of ["first footer", "second footer"]) {
88
+ expect((await admin.put("/api/site/settings", { data: { footerText } })).ok()).toBeTruthy();
89
+ expect((await (await anon.get("/api/site/settings")).json()).footerText).toBe(footerText);
90
+ }
91
+ } finally {
92
+ const footerText = typeof before.footerText === "string" ? before.footerText : "";
93
+ await admin.put("/api/site/settings", { data: { footerText } });
94
+ await anon.dispose();
95
+ await admin.dispose();
81
96
  }
82
- } finally {
83
- const footerText = typeof before.footerText === "string" ? before.footerText : "";
84
- await admin.put("/api/site/settings", { data: { footerText } });
85
- await anon.dispose();
86
- await admin.dispose();
87
- }
97
+ });
88
98
  });
89
99
 
90
100
  test("site favicon: the versioned URL is cached for good and other URLs revalidate", async ({ playwright }) => {
@@ -1,5 +1,6 @@
1
1
  import { expect, test } from "../helpers/disposable-users";
2
2
  import { ADMIN, USER } from "../helpers/accounts";
3
+ import { signInOnSeparateDevices } from "../helpers/devices";
3
4
 
4
5
  const base = process.env.E2E_BASE_URL ?? "http://localhost:5001";
5
6
  const origin = { origin: base };
@@ -125,6 +126,31 @@ test("revokeOtherSessions keeps the current session valid", async ({ playwright,
125
126
  await ctx.dispose();
126
127
  });
127
128
 
129
+ test("revokeOtherSessions removes every other session, past Better Auth's page of 100", async ({
130
+ playwright,
131
+ disposableUsers,
132
+ }) => {
133
+ test.slow();
134
+ const email = `api-revoke-many-${Date.now()}@example.com`;
135
+ const password = "Podokit3e-Str0ng!pw";
136
+ await disposableUsers.create({ email, password, name: "Many sessions" });
137
+
138
+ const statuses = await signInOnSeparateDevices(email, password, 105);
139
+ test.skip(statuses.includes(429), "needs an authentication rate limit above 105 sign-ins per window");
140
+ expect(statuses.every((status) => status === 200)).toBe(true);
141
+
142
+ const ctx = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
143
+ expect((await ctx.post("/api/auth/sign-in/email", { data: { email, password } })).ok()).toBeTruthy();
144
+ // Better Auth lists at most 100 sessions, so a full page shows the backlog.
145
+ expect(((await (await ctx.get("/api/auth/list-sessions")).json()) as unknown[]).length).toBe(100);
146
+
147
+ expect((await ctx.post("/api/auth/revoke-other-sessions")).ok()).toBeTruthy();
148
+ const left = (await (await ctx.get("/api/auth/list-sessions")).json()) as Array<{ token?: string }>;
149
+ expect(left).toHaveLength(1);
150
+ expect((await (await ctx.get("/api/auth/get-session")).json())?.user?.email).toBe(email);
151
+ await ctx.dispose();
152
+ });
153
+
128
154
  test("sessions record a client IP (forwarded through the proxy)", async ({ playwright }) => {
129
155
  const ctx = await signedIn(playwright, ADMIN);
130
156
  const res = await ctx.get("/api/auth/list-sessions");
@@ -0,0 +1,25 @@
1
+ const base = process.env.E2E_BASE_URL ?? "http://localhost:5001";
2
+
3
+ /**
4
+ * Signs in `count` times, each as a separate device, and returns the response
5
+ * statuses. Each request carries no cookies: a Playwright request context keeps
6
+ * the cookies of its earlier sign-ins, and Better Auth's multi-session plugin
7
+ * deletes a same-user session that a sign-in request carries, so signing in
8
+ * again from one context leaves one session instead of adding one.
9
+ */
10
+ export async function signInOnSeparateDevices(email: string, password: string, count: number): Promise<number[]> {
11
+ const statuses: number[] = [];
12
+ for (let start = 0; start < count; start += 10) {
13
+ const batch = Array.from({ length: Math.min(10, count - start) }, async () => {
14
+ const response = await fetch(`${base}/api/auth/sign-in/email`, {
15
+ method: "POST",
16
+ headers: { origin: base, "content-type": "application/json" },
17
+ body: JSON.stringify({ email, password }),
18
+ });
19
+ await response.body?.cancel();
20
+ return response.status;
21
+ });
22
+ statuses.push(...(await Promise.all(batch)));
23
+ }
24
+ return statuses;
25
+ }
@@ -0,0 +1,80 @@
1
+ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ // Locks for server-wide settings that specs in more than one file change. The
6
+ // suite runs on one worker by default; with --workers above 1, specs of the api
7
+ // and ui projects run at the same time, and two that flip the same setting
8
+ // would undo each other mid-test:
9
+ //
10
+ // - `require2fa`, `magic-link`, `oidc-provider`: feature flags
11
+ // - `session-idle-timeout`: automatic logout in the auth configuration
12
+ // - `social-providers`: any social sign-in provider in the auth configuration
13
+ // - `site-general`: the General settings form, which saves all of its fields
14
+ // (name, footer, locale, maintenance mode, public sign-up, ...) at once
15
+ // - `site-theme`: the Appearance settings
16
+ //
17
+ // A spec that holds a lock calls `test.slow()`, since waiting for another
18
+ // holder counts against its timeout.
19
+
20
+ // Longer than any spec holds a lock. A lock whose holder process has exited is
21
+ // taken over at once; this bounds the wait when the holder cannot be checked.
22
+ const STALE_MS = 120_000;
23
+ const OWNER_FILE = "owner";
24
+
25
+ /** The lock directory for `name`, shared by every worker on this machine. */
26
+ export function lockPath(name: string): string {
27
+ return join(tmpdir(), `podokit-e2e-${name}.lock`);
28
+ }
29
+
30
+ /** Whether the worker that holds `lock` has exited, such as after Ctrl-C. */
31
+ async function holderExited(lock: string): Promise<boolean> {
32
+ const pid = Number(await readFile(join(lock, OWNER_FILE), "utf8").catch(() => ""));
33
+ if (!Number.isInteger(pid) || pid <= 0) return false;
34
+ try {
35
+ process.kill(pid, 0);
36
+ return false;
37
+ } catch (error) {
38
+ return (error as NodeJS.ErrnoException).code === "ESRCH";
39
+ }
40
+ }
41
+
42
+ async function acquire(lock: string): Promise<void> {
43
+ for (;;) {
44
+ const created = await mkdir(lock).then(
45
+ () => true,
46
+ (error: NodeJS.ErrnoException) => {
47
+ if (error.code === "EEXIST") return false;
48
+ throw error;
49
+ },
50
+ );
51
+ if (created) {
52
+ await writeFile(join(lock, OWNER_FILE), String(process.pid)).catch(async (error: unknown) => {
53
+ await rm(lock, { recursive: true, force: true });
54
+ throw error;
55
+ });
56
+ return;
57
+ }
58
+ const age = await stat(lock).then((info) => Date.now() - info.mtimeMs, () => 0);
59
+ if (age > STALE_MS || (await holderExited(lock))) await rm(lock, { recursive: true, force: true });
60
+ else await new Promise((resolve) => setTimeout(resolve, 200));
61
+ }
62
+ }
63
+
64
+ /** Runs `body` while no other Playwright worker on this machine holds any of
65
+ * the named locks, and releases them however `body` ends. */
66
+ export async function exclusive<T>(names: string | string[], body: () => Promise<T>): Promise<T> {
67
+ // One acquisition order for every caller, so two specs that each need
68
+ // several locks cannot wait on each other.
69
+ const locks = [...new Set([names].flat())].sort().map(lockPath);
70
+ const held: string[] = [];
71
+ try {
72
+ for (const lock of locks) {
73
+ await acquire(lock);
74
+ held.push(lock);
75
+ }
76
+ return await body();
77
+ } finally {
78
+ for (const lock of held.reverse()) await rm(lock, { recursive: true, force: true });
79
+ }
80
+ }
@@ -52,16 +52,9 @@ async function seedSession(
52
52
  data: { email: account.email, password: account.password },
53
53
  });
54
54
  expect(res.ok(), `sign-in ${account.email}`).toBeTruthy();
55
- // Keep repeated local runs from filling better-auth's 100-session response
56
- // before the newly created current session can appear in account tests. The
57
- // endpoint clears at most one response page, so drain several pages when a
58
- // long-lived local database has accumulated them.
59
- for (let attempt = 0; attempt < 10; attempt += 1) {
60
- const sessionsResponse = await ctx.get("/api/auth/list-sessions");
61
- const sessions = sessionsResponse.ok() ? (await sessionsResponse.json()) as unknown : [];
62
- if (!Array.isArray(sessions) || sessions.length <= 1) break;
63
- expect((await ctx.post("/api/auth/revoke-other-sessions")).ok(), `clear old sessions for ${account.email}`).toBeTruthy();
64
- }
55
+ // Each run signs in again, so keep a long-lived local database from piling up
56
+ // this account's sessions: the seeded one is the only one left.
57
+ expect((await ctx.post("/api/auth/revoke-other-sessions")).ok(), `clear old sessions for ${account.email}`).toBeTruthy();
65
58
  writeFileSync(path, `${JSON.stringify(withTestLocale(await ctx.storageState()), null, 2)}\n`);
66
59
  await ctx.dispose();
67
60
  }
@@ -0,0 +1,46 @@
1
+ import { signInOnSeparateDevices } from "../helpers/devices";
2
+ import { expect, test } from "../helpers/disposable-users";
3
+ import { ready } from "../helpers/hydration";
4
+
5
+ const base = process.env.E2E_BASE_URL ?? "http://localhost:5001";
6
+ const origin = { origin: base };
7
+
8
+ // Better Auth's /list-sessions returns at most 100 sessions, the first ones the
9
+ // database finds, so a browser that signed in after 105 others used to see no
10
+ // "Current" row, and "Sign out other sessions" left sessions behind.
11
+ test("sessions tab shows the current session and signs out every other one past 100", async ({
12
+ browser,
13
+ playwright,
14
+ disposableUsers,
15
+ }) => {
16
+ test.slow();
17
+ const email = `ui-many-sessions-${Date.now()}@example.com`;
18
+ const password = "Podokit3e-Str0ng!pw";
19
+ await disposableUsers.create({ email, password, name: "Many sessions" });
20
+ const statuses = await signInOnSeparateDevices(email, password, 105);
21
+ test.skip(statuses.includes(429), "needs an authentication rate limit above 105 sign-ins per window");
22
+ expect(statuses.every((status) => status === 200)).toBe(true);
23
+
24
+ // Sign the browser in last, so its session is the 106th.
25
+ const signIn = await playwright.request.newContext({ baseURL: base, extraHTTPHeaders: origin });
26
+ expect((await signIn.post("/api/auth/sign-in/email", { data: { email, password } })).ok()).toBeTruthy();
27
+ const context = await browser.newContext({ storageState: await signIn.storageState() });
28
+ await context.addCookies([{ name: "locale", value: "en", url: base }]);
29
+ const page = await context.newPage();
30
+ try {
31
+ await ready(page, "/account");
32
+ await page.getByRole("button", { name: "Sessions" }).click();
33
+ await expect(page.getByText("106 sessions", { exact: true })).toBeVisible();
34
+ await expect(page.getByText("Current", { exact: true })).toBeVisible();
35
+
36
+ await page.getByRole("button", { name: "Sign out other sessions" }).click();
37
+ await expect(page.getByText("Signed out other sessions")).toBeVisible();
38
+ await expect(page.getByText("1 sessions", { exact: true })).toBeVisible();
39
+ await expect(page.getByText("Current", { exact: true })).toBeVisible();
40
+ const left = (await (await signIn.get("/api/account/sessions?limit=100")).json()) as { total: number };
41
+ expect(left.total).toBe(1);
42
+ } finally {
43
+ await context.close();
44
+ await signIn.dispose();
45
+ }
46
+ });