@mandujs/core 0.21.0 → 0.22.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 (122) hide show
  1. package/package.json +94 -69
  2. package/src/auth/__tests__/login.test.ts +419 -0
  3. package/src/auth/__tests__/password.test.ts +122 -0
  4. package/src/auth/__tests__/reset.test.ts +296 -0
  5. package/src/auth/__tests__/tokens.test.ts +274 -0
  6. package/src/auth/__tests__/verification.test.ts +274 -0
  7. package/src/auth/index.ts +76 -0
  8. package/src/auth/login.ts +225 -0
  9. package/src/auth/password.ts +120 -0
  10. package/src/auth/reset.ts +243 -0
  11. package/src/auth/tokens.ts +612 -0
  12. package/src/auth/verification.ts +253 -0
  13. package/src/bundler/__tests__/cli-bench-utils.test.ts +149 -0
  14. package/src/bundler/__tests__/cold-start.test.ts +504 -0
  15. package/src/bundler/__tests__/csp-nonce.test.ts +278 -0
  16. package/src/bundler/__tests__/dev-reliability.test.ts +619 -0
  17. package/src/bundler/__tests__/extended-watch.test.ts +710 -0
  18. package/src/bundler/__tests__/fast-refresh.test.ts +596 -0
  19. package/src/bundler/__tests__/hdr.test.ts +353 -0
  20. package/src/bundler/__tests__/hmr-client.test.ts +532 -0
  21. package/src/bundler/__tests__/manifest-schema.test.ts +266 -0
  22. package/src/bundler/__tests__/prod-smoke.test.ts +138 -0
  23. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -0
  24. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -0
  25. package/src/bundler/__tests__/vendor-cache.test.ts +455 -0
  26. package/src/bundler/build.test.ts +8 -1
  27. package/src/bundler/build.ts +310 -18
  28. package/src/bundler/css.ts +326 -323
  29. package/src/bundler/dev.ts +1611 -59
  30. package/src/bundler/fast-refresh-plugin.ts +307 -0
  31. package/src/bundler/hmr-types.ts +252 -0
  32. package/src/bundler/manifest-schema.ts +301 -0
  33. package/src/bundler/safe-build.test.ts +128 -0
  34. package/src/bundler/safe-build.ts +77 -0
  35. package/src/bundler/scenario-matrix.ts +229 -0
  36. package/src/bundler/types.ts +11 -0
  37. package/src/bundler/vendor-cache-types.ts +130 -0
  38. package/src/bundler/vendor-cache.ts +526 -0
  39. package/src/client/router.ts +214 -56
  40. package/src/db/__tests__/db.test.ts +485 -0
  41. package/src/db/index.ts +513 -0
  42. package/src/db/migrations/__tests__/runner.test.ts +661 -0
  43. package/src/db/migrations/history-table.ts +345 -0
  44. package/src/db/migrations/lock.ts +269 -0
  45. package/src/db/migrations/runner.ts +633 -0
  46. package/src/desktop/__tests__/smoke.test.ts +100 -0
  47. package/src/desktop/__tests__/window.test.ts +172 -0
  48. package/src/desktop/__tests__/worker.test.ts +266 -0
  49. package/src/desktop/index.ts +43 -0
  50. package/src/desktop/types.ts +158 -0
  51. package/src/desktop/window.ts +492 -0
  52. package/src/desktop/worker.ts +180 -0
  53. package/src/email/__tests__/email.test.ts +355 -0
  54. package/src/email/index.ts +282 -0
  55. package/src/email/resend.ts +163 -0
  56. package/src/email/smtp.ts +64 -0
  57. package/src/filling/__tests__/session-sqlite.test.ts +454 -0
  58. package/src/filling/context.ts +72 -78
  59. package/src/filling/cookie-codec.ts +299 -0
  60. package/src/filling/deps.ts +25 -1
  61. package/src/filling/filling.ts +28 -3
  62. package/src/filling/session-sqlite.ts +617 -0
  63. package/src/filling/session.ts +265 -216
  64. package/src/guard/decision-memory.test.ts +52 -22
  65. package/src/id/__tests__/id.test.ts +120 -0
  66. package/src/id/index.ts +105 -0
  67. package/src/kitchen/index.ts +2 -2
  68. package/src/kitchen/kitchen-handler.ts +86 -0
  69. package/src/kitchen/stream/activity-sse.ts +2 -1
  70. package/src/middleware/csrf.ts +328 -0
  71. package/src/middleware/index.ts +40 -0
  72. package/src/middleware/oauth/__tests__/oauth.test.ts +574 -0
  73. package/src/middleware/oauth/index.ts +505 -0
  74. package/src/middleware/oauth/providers.ts +115 -0
  75. package/src/middleware/rate-limit/__tests__/rate-limit.test.ts +642 -0
  76. package/src/middleware/rate-limit/index.ts +522 -0
  77. package/src/middleware/rate-limit/sqlite-store.ts +382 -0
  78. package/src/middleware/secure/__tests__/secure.test.ts +360 -0
  79. package/src/middleware/secure/csp.ts +193 -0
  80. package/src/middleware/secure/index.ts +417 -0
  81. package/src/middleware/session.ts +174 -0
  82. package/src/observability/event-bus.ts +81 -79
  83. package/src/paths.ts +37 -0
  84. package/src/perf/hmr-markers.ts +215 -0
  85. package/src/perf/index.ts +104 -0
  86. package/src/resource/__tests__/generator.test.ts +603 -2
  87. package/src/resource/ddl/__tests__/diff.test.ts +639 -0
  88. package/src/resource/ddl/__tests__/emit.test.ts +799 -0
  89. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -0
  90. package/src/resource/ddl/diff.ts +392 -0
  91. package/src/resource/ddl/emit.ts +548 -0
  92. package/src/resource/ddl/persistence-types.ts +218 -0
  93. package/src/resource/ddl/snapshot.ts +447 -0
  94. package/src/resource/ddl/type-map.ts +223 -0
  95. package/src/resource/ddl/types.ts +232 -0
  96. package/src/resource/generator-repo.ts +610 -0
  97. package/src/resource/generator-schema.ts +476 -0
  98. package/src/resource/generator.ts +117 -1
  99. package/src/resource/index.ts +17 -1
  100. package/src/resource/schema.ts +30 -0
  101. package/src/router/fs-scanner.ts +3 -0
  102. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -0
  103. package/src/runtime/__tests__/hdr-client.test.ts +223 -0
  104. package/src/runtime/__tests__/http-errors.test.ts +117 -0
  105. package/src/runtime/__tests__/not-found.test.ts +152 -0
  106. package/src/runtime/boundary.tsx +21 -1
  107. package/src/runtime/fast-refresh-runtime.ts +322 -0
  108. package/src/runtime/fast-refresh-types.ts +128 -0
  109. package/src/runtime/hmr-client.ts +409 -0
  110. package/src/runtime/http-errors.ts +113 -0
  111. package/src/runtime/index.ts +6 -0
  112. package/src/runtime/logger.ts +678 -677
  113. package/src/runtime/not-found.ts +93 -0
  114. package/src/runtime/redirect.ts +133 -0
  115. package/src/runtime/server.ts +518 -20
  116. package/src/runtime/ssr.ts +340 -10
  117. package/src/runtime/streaming-ssr.ts +222 -19
  118. package/src/scheduler/__tests__/scheduler.test.ts +514 -0
  119. package/src/scheduler/index.ts +343 -0
  120. package/src/storage/s3/__tests__/s3.test.ts +479 -0
  121. package/src/storage/s3/index.ts +412 -0
  122. package/src/testing/index.ts +58 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * @mandujs/core/auth/verification — flow tests.
3
+ *
4
+ * End-to-end cover for `createEmailVerification` using the in-memory email
5
+ * sender from `@mandujs/core/email` and a `:memory:` token store. The
6
+ * token store is shared across tests in a `describe` to keep boot cost
7
+ * low; each test mints fresh tokens, so cross-test contamination is
8
+ * non-existent.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
12
+
13
+ import { createMemoryEmailSender, type MemoryEmailSender } from "../../email";
14
+ import { createAuthTokenStore, type AuthTokenStore } from "../tokens";
15
+ import { createEmailVerification } from "../verification";
16
+
17
+ // ─── Gate on Bun.SQL + CryptoHasher ─────────────────────────────────────────
18
+
19
+ const hasBun = (() => {
20
+ const g = globalThis as unknown as {
21
+ Bun?: { SQL?: unknown; CryptoHasher?: unknown };
22
+ };
23
+ return typeof g.Bun?.SQL === "function" && typeof g.Bun?.CryptoHasher === "function";
24
+ })();
25
+ const describeIfBun = hasBun ? describe : describe.skip;
26
+
27
+ // ─── Fixtures ───────────────────────────────────────────────────────────────
28
+
29
+ const SECRET = "verification-test-secret-32-bytes-or-more!";
30
+ const URL_TEMPLATE = "https://app.example.com/verify?token={token}";
31
+ const FROM = "noreply@example.com";
32
+
33
+ interface Fixture {
34
+ store: AuthTokenStore;
35
+ sender: MemoryEmailSender;
36
+ onVerifiedCalls: Array<{ userId: string; email: string }>;
37
+ }
38
+
39
+ function makeFixture(): Fixture {
40
+ return {
41
+ store: createAuthTokenStore({
42
+ secret: SECRET,
43
+ dbPath: ":memory:",
44
+ gcSchedule: false,
45
+ }),
46
+ sender: createMemoryEmailSender(),
47
+ onVerifiedCalls: [],
48
+ };
49
+ }
50
+
51
+ describeIfBun("@mandujs/core/auth/verification — createEmailVerification", () => {
52
+ let fx: Fixture;
53
+
54
+ beforeEach(() => {
55
+ fx = makeFixture();
56
+ });
57
+
58
+ afterEach(async () => {
59
+ await fx.store.close();
60
+ });
61
+
62
+ it("send() mints a token and dispatches an email with the rendered subject + html", async () => {
63
+ const renderEmail = mock(({ url, userId, email }: { url: string; userId: string; email: string }) => ({
64
+ subject: `Verify ${email}`,
65
+ html: `<a href="${url}" data-uid="${userId}">go</a>`,
66
+ text: `Verify: ${url}`,
67
+ }));
68
+
69
+ const verify = createEmailVerification({
70
+ store: fx.store,
71
+ sender: fx.sender,
72
+ fromAddress: FROM,
73
+ verifyUrlTemplate: URL_TEMPLATE,
74
+ renderEmail,
75
+ onVerified: async (args) => {
76
+ fx.onVerifiedCalls.push(args);
77
+ },
78
+ });
79
+
80
+ await verify.send("u-1", "alice@example.com");
81
+
82
+ expect(renderEmail).toHaveBeenCalledTimes(1);
83
+ expect(fx.sender.sent).toHaveLength(1);
84
+ const msg = fx.sender.sent[0]!;
85
+ expect(msg.subject).toBe("Verify alice@example.com");
86
+ expect(msg.to).toBe("alice@example.com");
87
+ expect(msg.html).toContain("data-uid=\"u-1\"");
88
+ expect(msg.text).toContain("https://app.example.com/verify?token=");
89
+ });
90
+
91
+ it("email body contains the resolved URL with the token substituted", async () => {
92
+ const verify = createEmailVerification({
93
+ store: fx.store,
94
+ sender: fx.sender,
95
+ fromAddress: FROM,
96
+ verifyUrlTemplate: URL_TEMPLATE,
97
+ renderEmail: ({ url }) => ({ subject: "Verify", html: `<a href="${url}">v</a>` }),
98
+ onVerified: async () => {},
99
+ });
100
+
101
+ await verify.send("u-2", "bob@example.com");
102
+ const msg = fx.sender.sent[0]!;
103
+ const href = /href="([^"]+)"/.exec(msg.html!)?.[1];
104
+ expect(href).toBeTruthy();
105
+ expect(href).toContain("https://app.example.com/verify?token=");
106
+ // The placeholder must NOT survive in the rendered URL.
107
+ expect(href).not.toContain("{token}");
108
+ });
109
+
110
+ it("consume(validToken) returns { userId, email } and invokes onVerified", async () => {
111
+ const verify = createEmailVerification({
112
+ store: fx.store,
113
+ sender: fx.sender,
114
+ fromAddress: FROM,
115
+ verifyUrlTemplate: URL_TEMPLATE,
116
+ renderEmail: ({ url }) => ({ subject: "Verify", html: `<a href="${url}">v</a>` }),
117
+ onVerified: async (args) => {
118
+ fx.onVerifiedCalls.push(args);
119
+ },
120
+ });
121
+
122
+ await verify.send("u-3", "carol@example.com");
123
+ const msg = fx.sender.sent[0]!;
124
+ const token = extractTokenFromUrl(msg.html!);
125
+ expect(token).toBeTruthy();
126
+
127
+ const result = await verify.consume(token!);
128
+ expect(result).toEqual({ userId: "u-3", email: "carol@example.com" });
129
+ expect(fx.onVerifiedCalls).toHaveLength(1);
130
+ expect(fx.onVerifiedCalls[0]).toEqual({ userId: "u-3", email: "carol@example.com" });
131
+ });
132
+
133
+ it("consume(consumedToken) returns null on the second call", async () => {
134
+ const verify = createEmailVerification({
135
+ store: fx.store,
136
+ sender: fx.sender,
137
+ fromAddress: FROM,
138
+ verifyUrlTemplate: URL_TEMPLATE,
139
+ renderEmail: ({ url }) => ({ subject: "Verify", html: `<a href="${url}">v</a>` }),
140
+ onVerified: async () => {},
141
+ });
142
+
143
+ await verify.send("u-4", "dave@example.com");
144
+ const token = extractTokenFromUrl(fx.sender.sent[0]!.html!)!;
145
+
146
+ const first = await verify.consume(token);
147
+ expect(first).not.toBeNull();
148
+ const second = await verify.consume(token);
149
+ expect(second).toBeNull();
150
+ });
151
+
152
+ it("consume(expiredToken) returns null", async () => {
153
+ const expiringStore = createAuthTokenStore({
154
+ secret: SECRET,
155
+ dbPath: ":memory:",
156
+ gcSchedule: false,
157
+ ttlSecondsByPurpose: { "verify-email": 0 },
158
+ });
159
+ try {
160
+ const verify = createEmailVerification({
161
+ store: expiringStore,
162
+ sender: fx.sender,
163
+ fromAddress: FROM,
164
+ verifyUrlTemplate: URL_TEMPLATE,
165
+ renderEmail: ({ url }) => ({ subject: "V", html: `<a href="${url}">v</a>` }),
166
+ onVerified: async () => {},
167
+ });
168
+ await verify.send("u-5", "eve@example.com");
169
+ const token = extractTokenFromUrl(fx.sender.sent[0]!.html!)!;
170
+ await new Promise((r) => setTimeout(r, 5));
171
+ expect(await verify.consume(token)).toBeNull();
172
+ } finally {
173
+ await expiringStore.close();
174
+ }
175
+ });
176
+
177
+ it("consume(bogus) returns null for structurally broken / unknown tokens", async () => {
178
+ const verify = createEmailVerification({
179
+ store: fx.store,
180
+ sender: fx.sender,
181
+ fromAddress: FROM,
182
+ verifyUrlTemplate: URL_TEMPLATE,
183
+ renderEmail: ({ url }) => ({ subject: "V", html: url }),
184
+ onVerified: async () => {},
185
+ });
186
+
187
+ expect(await verify.consume("garbage-no-dot")).toBeNull();
188
+ expect(await verify.consume("")).toBeNull();
189
+ // Malformed percent-encoding — must not throw.
190
+ expect(await verify.consume("%E0%A4%A")).toBeNull();
191
+ // Well-formed structure but nothing in the DB.
192
+ expect(await verify.consume("fakeid.fakenonce")).toBeNull();
193
+ });
194
+
195
+ it("verifyUrlTemplate without the {token} placeholder throws at create time", () => {
196
+ expect(() =>
197
+ createEmailVerification({
198
+ store: fx.store,
199
+ sender: fx.sender,
200
+ fromAddress: FROM,
201
+ verifyUrlTemplate: "https://app.example.com/verify?nope=1",
202
+ renderEmail: () => ({ subject: "v", html: "<p>v</p>" }),
203
+ onVerified: async () => {},
204
+ }),
205
+ ).toThrow(/\{token\}/);
206
+ });
207
+
208
+ it("empty fromAddress throws at create time", () => {
209
+ expect(() =>
210
+ createEmailVerification({
211
+ store: fx.store,
212
+ sender: fx.sender,
213
+ fromAddress: "",
214
+ verifyUrlTemplate: URL_TEMPLATE,
215
+ renderEmail: () => ({ subject: "v", html: "<p>v</p>" }),
216
+ onVerified: async () => {},
217
+ }),
218
+ ).toThrow(/fromAddress/);
219
+ });
220
+
221
+ it("fromAddress is honored on every outbound message", async () => {
222
+ const customFrom = "\"App Name\" <no-reply@example.org>";
223
+ const verify = createEmailVerification({
224
+ store: fx.store,
225
+ sender: fx.sender,
226
+ fromAddress: customFrom,
227
+ verifyUrlTemplate: URL_TEMPLATE,
228
+ renderEmail: ({ url }) => ({ subject: "V", html: `<a href="${url}">v</a>` }),
229
+ onVerified: async () => {},
230
+ });
231
+ await verify.send("u-6", "frank@example.com");
232
+ await verify.send("u-7", "grace@example.com");
233
+ expect(fx.sender.sent).toHaveLength(2);
234
+ expect(fx.sender.sent[0]!.from).toBe(customFrom);
235
+ expect(fx.sender.sent[1]!.from).toBe(customFrom);
236
+ });
237
+
238
+ it("onVerified throwing propagates — token is already consumed (idempotency note)", async () => {
239
+ const verify = createEmailVerification({
240
+ store: fx.store,
241
+ sender: fx.sender,
242
+ fromAddress: FROM,
243
+ verifyUrlTemplate: URL_TEMPLATE,
244
+ renderEmail: ({ url }) => ({ subject: "V", html: `<a href="${url}">v</a>` }),
245
+ onVerified: async () => {
246
+ throw new Error("DB write failed");
247
+ },
248
+ });
249
+
250
+ await verify.send("u-8", "heidi@example.com");
251
+ const token = extractTokenFromUrl(fx.sender.sent[0]!.html!)!;
252
+
253
+ await expect(verify.consume(token)).rejects.toThrow(/DB write failed/);
254
+ // Token is consumed — a retry returns null, forcing a fresh send.
255
+ const retry = await verify.consume(token);
256
+ expect(retry).toBeNull();
257
+ });
258
+ });
259
+
260
+ // ─── Helpers ────────────────────────────────────────────────────────────────
261
+
262
+ /**
263
+ * Extract the `token` query parameter from a URL embedded in a rendered
264
+ * HTML body. Returns `null` if the URL wasn't found — tests assert
265
+ * non-null so a missing token fails loudly.
266
+ */
267
+ function extractTokenFromUrl(html: string): string | null {
268
+ // Match the URL carried inside the template. `href="..."` is our
269
+ // rendering convention.
270
+ const hrefMatch = /href="([^"]+)"/.exec(html);
271
+ const url = hrefMatch ? hrefMatch[1]! : html;
272
+ const tokenMatch = /[?&]token=([^&"\s]+)/.exec(url);
273
+ return tokenMatch ? tokenMatch[1]! : null;
274
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @mandujs/core/auth — Unified auth barrel.
3
+ *
4
+ * One import surface for everything auth-related in Mandu:
5
+ * - Password hashing (argon2id / bcrypt) from `./password`
6
+ * - Session-backed login helpers from `./login`
7
+ * - Error classes and guards from `../filling/auth`
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import {
12
+ * hashPassword,
13
+ * verifyPassword,
14
+ * loginUser,
15
+ * logoutUser,
16
+ * currentUserId,
17
+ * requireUser,
18
+ * AuthenticationError,
19
+ * } from "@mandujs/core/auth";
20
+ * ```
21
+ *
22
+ * Fine-grained subpath imports remain available for tree-shaking-sensitive
23
+ * bundles:
24
+ * - `@mandujs/core/auth/password`
25
+ * - `@mandujs/core/auth/login`
26
+ *
27
+ * @module auth
28
+ */
29
+
30
+ // ── Password hashing (Phase 2.1) ──
31
+ export {
32
+ hashPassword,
33
+ verifyPassword,
34
+ type PasswordOptions,
35
+ } from "./password";
36
+
37
+ // ── Login / logout / read helpers (Phase 2.4) ──
38
+ export {
39
+ loginUser,
40
+ logoutUser,
41
+ currentUserId,
42
+ loggedAt,
43
+ type LoginOptions,
44
+ } from "./login";
45
+
46
+ // ── Email verification (Phase 5.3) ──
47
+ // The underlying token store (./tokens) is deliberately NOT re-exported —
48
+ // it's the shared plumbing for verification + reset, not a public primitive.
49
+ export {
50
+ createEmailVerification,
51
+ type VerificationFlow,
52
+ type VerificationFlowOptions,
53
+ } from "./verification";
54
+
55
+ // ── Password reset (Phase 5.3) ──
56
+ export {
57
+ createPasswordReset,
58
+ type ResetFlow,
59
+ type ResetFlowOptions,
60
+ } from "./reset";
61
+
62
+ // ── Error classes, guards, and user types (re-exported from filling/auth) ──
63
+ // We DO NOT re-export the factory functions (`createAuthGuard`, `createRoleGuard`)
64
+ // here — those are broader "beforeHandle" plumbing that lives on the filling
65
+ // surface. Users who need them still import from `@mandujs/core` directly.
66
+ export {
67
+ AuthenticationError,
68
+ AuthorizationError,
69
+ requireUser,
70
+ requireRole,
71
+ requireAnyRole,
72
+ requireAllRoles,
73
+ type BaseUser,
74
+ type UserWithRole,
75
+ type UserWithRoles,
76
+ } from "../filling/auth";
@@ -0,0 +1,225 @@
1
+ /**
2
+ * @mandujs/core/auth/login
3
+ *
4
+ * Ergonomic helpers that bridge Phase 2.3's `session()` middleware with
5
+ * Mandu's existing auth types in `filling/auth.ts`.
6
+ *
7
+ * These helpers **absorb the ordering hazard** from `saveSession` / `destroySession`
8
+ * (see `middleware/session.ts` lines 99-102): callers must not build a Response
9
+ * before committing the session. `loginUser` / `logoutUser` call those helpers
10
+ * internally, so handler code collapses to:
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { loginUser, logoutUser, currentUserId } from "@mandujs/core/auth";
15
+ * import { hashPassword, verifyPassword } from "@mandujs/core/auth";
16
+ *
17
+ * // login route
18
+ * const ok = await verifyPassword(plaintext, storedHash);
19
+ * if (!ok) return ctx.unauthorized();
20
+ * await loginUser(ctx, user.id);
21
+ * return ctx.redirect("/dashboard");
22
+ *
23
+ * // logout route
24
+ * await logoutUser(ctx);
25
+ * return ctx.redirect("/");
26
+ *
27
+ * // read-side
28
+ * const uid = currentUserId(ctx); // null if not logged in
29
+ * ```
30
+ *
31
+ * **Note on `ctx.set("user", ...)` vs `session.get("userId")`:** this module
32
+ * stores `userId` in the SESSION (persisted across requests via cookie).
33
+ * `requireUser` / `requireRole` from `filling/auth.ts` read from the
34
+ * REQUEST-SCOPED store at `ctx.get("user")`, which is a different location.
35
+ * A typical app bridges the two with a tiny middleware placed AFTER
36
+ * `session()`:
37
+ *
38
+ * ```ts
39
+ * .use(session({ storage }))
40
+ * .beforeHandle(async (ctx) => {
41
+ * const uid = currentUserId(ctx);
42
+ * if (uid) ctx.set("user", await db.users.findById(uid));
43
+ * })
44
+ * ```
45
+ *
46
+ * @module auth/login
47
+ */
48
+
49
+ import type { ManduContext } from "../filling/context";
50
+ import type { Session } from "../filling/session";
51
+ import { saveSession, destroySession } from "../middleware/session";
52
+ import { AuthenticationError } from "../filling/auth";
53
+
54
+ // ========== Defaults ==========
55
+
56
+ /**
57
+ * Session key under which `userId` is persisted. Kept short and stable so
58
+ * upgrading from `loginUser` to reading the raw session still works.
59
+ */
60
+ const DEFAULT_USER_ID_KEY = "userId";
61
+
62
+ /**
63
+ * Session key under which the login timestamp (ms since epoch) is persisted.
64
+ * Useful for session-age checks and re-authentication prompts.
65
+ */
66
+ const DEFAULT_LOGGED_AT_KEY = "loginAt";
67
+
68
+ /** Default ctx key used by `session()` middleware. Mirrors `middleware/session.ts`. */
69
+ const DEFAULT_SESSION_ATTACH_KEY = "session";
70
+
71
+ // ========== Types ==========
72
+
73
+ /** Options passed when storing auth state in the session. */
74
+ export interface LoginOptions {
75
+ /** Session key for user id. Default: `"userId"`. */
76
+ userIdKey?: string;
77
+ /** Session key for "logged at" timestamp (ms). Default: `"loginAt"`. */
78
+ loggedAtKey?: string;
79
+ /**
80
+ * Extra session fields to set atomically with userId. Restricted to
81
+ * JSON-serializable primitives so the session cookie round-trips cleanly.
82
+ * If you need richer types, mutate the Session directly before calling
83
+ * `loginUser`, or after it (before the response).
84
+ */
85
+ extras?: Record<string, string | number | boolean>;
86
+ }
87
+
88
+ // ========== Helpers ==========
89
+
90
+ /**
91
+ * Mark the current session as authenticated for `userId`, commit it via
92
+ * `saveSession` (so the `Set-Cookie` header lands on the next response),
93
+ * and return. Must be called **before** returning a Response from the
94
+ * handler — `saveSession` attaches cookies via `ctx.cookies`, which
95
+ * `ctx.json` / `ctx.ok` / `ctx.redirect` snapshot at build time.
96
+ *
97
+ * Throws an {@link AuthenticationError} wrapping the underlying wiring
98
+ * error when the `session()` middleware is not installed on this request.
99
+ * Using `AuthenticationError` (and not raw `Error`) keeps the login path
100
+ * uniformly catchable — the same catch block that handles bad credentials
101
+ * can handle "no session middleware" as a generic auth failure.
102
+ */
103
+ export async function loginUser(
104
+ ctx: ManduContext,
105
+ userId: string,
106
+ options?: LoginOptions,
107
+ ): Promise<void> {
108
+ if (typeof userId !== "string" || userId.length === 0) {
109
+ throw new AuthenticationError("loginUser: userId must be a non-empty string");
110
+ }
111
+
112
+ const userIdKey = options?.userIdKey ?? DEFAULT_USER_ID_KEY;
113
+ const loggedAtKey = options?.loggedAtKey ?? DEFAULT_LOGGED_AT_KEY;
114
+
115
+ const session = ctx.get<Session>(DEFAULT_SESSION_ATTACH_KEY);
116
+ if (!session) {
117
+ throw new AuthenticationError(
118
+ "Session middleware not installed: add `.use(session({ storage }))` before calling loginUser",
119
+ );
120
+ }
121
+
122
+ // All three writes happen before the commit so they land atomically in the
123
+ // same Set-Cookie. If any write throws, we propagate without committing.
124
+ session.set(userIdKey, userId);
125
+ session.set(loggedAtKey, Date.now());
126
+
127
+ if (options?.extras) {
128
+ for (const [key, value] of Object.entries(options.extras)) {
129
+ session.set(key, value);
130
+ }
131
+ }
132
+
133
+ // Commit — saveSession reads `ctx.get("session")` and attaches Set-Cookie.
134
+ // Forwards the same wiring-error from saveSession if storageKey was wired
135
+ // differently, though we already verified the session above.
136
+ try {
137
+ await saveSession(ctx);
138
+ } catch (cause) {
139
+ // Re-shape to AuthenticationError so callers have one error type on the
140
+ // login path. Preserve the original via the `cause` property (ES2022).
141
+ throw new AuthenticationError(
142
+ `loginUser: failed to commit session — ${(cause as Error)?.message ?? String(cause)}`,
143
+ );
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Clear the current session by invoking `destroySession`: wipes in-memory
149
+ * state and emits an expiring `Set-Cookie` (Max-Age=0) so the browser drops
150
+ * its copy.
151
+ *
152
+ * Idempotent: calling on a request with no session cookie, or calling twice
153
+ * in succession, is safe — `destroySession` always emits a fresh expiring
154
+ * cookie. Throws an {@link AuthenticationError} only when the session
155
+ * middleware itself was not installed (same rationale as {@link loginUser}).
156
+ */
157
+ export async function logoutUser(
158
+ ctx: ManduContext,
159
+ options?: Pick<LoginOptions, "userIdKey">,
160
+ ): Promise<void> {
161
+ const session = ctx.get<Session>(DEFAULT_SESSION_ATTACH_KEY);
162
+ if (!session) {
163
+ throw new AuthenticationError(
164
+ "Session middleware not installed: add `.use(session({ storage }))` before calling logoutUser",
165
+ );
166
+ }
167
+
168
+ // `options.userIdKey` is accepted for symmetry with loginUser, but
169
+ // destroySession wipes the entire session so per-key handling is unneeded.
170
+ // We still `unset` it first to normalize dirty state in case a caller
171
+ // composes logoutUser with pre/post inspection.
172
+ const userIdKey = options?.userIdKey ?? DEFAULT_USER_ID_KEY;
173
+ if (session.has(userIdKey)) {
174
+ session.unset(userIdKey);
175
+ }
176
+
177
+ try {
178
+ await destroySession(ctx);
179
+ } catch (cause) {
180
+ throw new AuthenticationError(
181
+ `logoutUser: failed to destroy session — ${(cause as Error)?.message ?? String(cause)}`,
182
+ );
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Read the current `userId` from the session. Returns `null` when either:
188
+ * - The session middleware is not installed on this request
189
+ * - No `userId` key is present in the session
190
+ *
191
+ * **Never throws.** This is the read path; handlers call it to decide
192
+ * whether to redirect to login, so a throwing contract would force every
193
+ * caller to wrap in try/catch. Returning `null` is the ergonomic choice.
194
+ */
195
+ export function currentUserId(
196
+ ctx: ManduContext,
197
+ options?: Pick<LoginOptions, "userIdKey">,
198
+ ): string | null {
199
+ const session = ctx.get<Session>(DEFAULT_SESSION_ATTACH_KEY);
200
+ if (!session) return null;
201
+
202
+ const userIdKey = options?.userIdKey ?? DEFAULT_USER_ID_KEY;
203
+ const raw = session.get<unknown>(userIdKey);
204
+ return typeof raw === "string" && raw.length > 0 ? raw : null;
205
+ }
206
+
207
+ /**
208
+ * Read the login timestamp (ms since epoch) from the session. Returns `null`
209
+ * when the session middleware is absent, the key is unset, or the stored
210
+ * value is not a number (defensive against hand-edited / corrupted sessions).
211
+ *
212
+ * Useful for session-age checks ("re-authenticate after 30 min for sensitive
213
+ * actions"): `Date.now() - (loggedAt(ctx) ?? 0) > THIRTY_MIN`.
214
+ */
215
+ export function loggedAt(
216
+ ctx: ManduContext,
217
+ options?: Pick<LoginOptions, "loggedAtKey">,
218
+ ): number | null {
219
+ const session = ctx.get<Session>(DEFAULT_SESSION_ATTACH_KEY);
220
+ if (!session) return null;
221
+
222
+ const loggedAtKey = options?.loggedAtKey ?? DEFAULT_LOGGED_AT_KEY;
223
+ const raw = session.get<unknown>(loggedAtKey);
224
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : null;
225
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * @mandujs/core/auth/password
3
+ *
4
+ * Password hashing and verification backed by `Bun.password`.
5
+ *
6
+ * Defaults to **argon2id** — the OWASP-recommended memory-hard KDF. `bcrypt`
7
+ * is exposed for legacy database interop only. PBKDF2/scrypt are intentionally
8
+ * not supported (see non-goals in the module design doc).
9
+ *
10
+ * This module is **Bun-native**. It will throw at first call if executed in a
11
+ * runtime without `Bun.password`. Use the Web Crypto polyfills in `@mandujs/core/id`
12
+ * as a reference for how we handle runtime-specific APIs.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { hashPassword, verifyPassword } from "@mandujs/core/auth/password";
17
+ *
18
+ * const hash = await hashPassword("s3cret!");
19
+ * const ok = await verifyPassword("s3cret!", hash); // true
20
+ * ```
21
+ *
22
+ * @module auth/password
23
+ */
24
+
25
+ /**
26
+ * bcrypt hard-limits passwords to 72 bytes. We reject at the boundary instead
27
+ * of letting Bun silently truncate, so callers get a clear error at hash time.
28
+ * See https://en.wikipedia.org/wiki/Bcrypt#User_input
29
+ */
30
+ const BCRYPT_MAX_BYTES = 72;
31
+
32
+ /**
33
+ * Password hashing options. Mirrors the `Bun.password` option shape.
34
+ */
35
+ export interface PasswordOptions {
36
+ /** Default: "argon2id". bcrypt available for legacy interop. */
37
+ algorithm?: "argon2id" | "argon2d" | "argon2i" | "bcrypt";
38
+ /** Argon2 only. Memory cost in KiB. Default: Bun default. */
39
+ memoryCost?: number;
40
+ /** Argon2 only. Time cost (iterations). Default: Bun default. */
41
+ timeCost?: number;
42
+ /** bcrypt only. Cost factor. Default: Bun default. */
43
+ cost?: number;
44
+ }
45
+
46
+ /** Minimal structural type for the Bun.password surface we consume. */
47
+ interface BunPasswordApi {
48
+ hash: (plain: string, options?: PasswordOptions) => Promise<string>;
49
+ verify: (plain: string, hash: string) => Promise<boolean>;
50
+ }
51
+
52
+ function getBunPassword(): BunPasswordApi {
53
+ const g = globalThis as unknown as { Bun?: { password?: BunPasswordApi } };
54
+ if (!g.Bun || !g.Bun.password) {
55
+ throw new Error(
56
+ "[@mandujs/core/auth/password] Bun.password is unavailable — this module requires the Bun runtime (>= 1.3).",
57
+ );
58
+ }
59
+ return g.Bun.password;
60
+ }
61
+
62
+ /**
63
+ * Hashes a plaintext password. Uses argon2id by default.
64
+ *
65
+ * Throws if `plain` is empty, or if `algorithm: "bcrypt"` is selected and the
66
+ * UTF-8 byte length exceeds 72 (bcrypt's hard limit — we surface the error
67
+ * early instead of silently truncating).
68
+ */
69
+ export async function hashPassword(
70
+ plain: string,
71
+ options?: PasswordOptions,
72
+ ): Promise<string> {
73
+ if (typeof plain !== "string" || plain.length === 0) {
74
+ throw new Error(
75
+ "[@mandujs/core/auth/password] hashPassword: plaintext must be a non-empty string.",
76
+ );
77
+ }
78
+
79
+ if (options?.algorithm === "bcrypt") {
80
+ const bytes = Buffer.byteLength(plain, "utf8");
81
+ if (bytes > BCRYPT_MAX_BYTES) {
82
+ throw new Error(
83
+ `[@mandujs/core/auth/password] hashPassword: bcrypt input exceeds 72-byte limit (got ${bytes} bytes). Use argon2id for longer passwords.`,
84
+ );
85
+ }
86
+ }
87
+
88
+ return await getBunPassword().hash(plain, options);
89
+ }
90
+
91
+ /**
92
+ * Verifies a plaintext password against a stored hash. Algorithm is
93
+ * auto-detected from the hash prefix by Bun.
94
+ *
95
+ * Returns `false` on mismatch, malformed hash, or empty input. Never throws
96
+ * for user-supplied values — a throwing verify path would leak hash-format
97
+ * signal via timing/exception type to callers on the login path, so we
98
+ * collapse every failure mode to the same boolean result.
99
+ */
100
+ export async function verifyPassword(
101
+ plain: string,
102
+ hash: string,
103
+ ): Promise<boolean> {
104
+ if (
105
+ typeof plain !== "string" ||
106
+ plain.length === 0 ||
107
+ typeof hash !== "string" ||
108
+ hash.length === 0
109
+ ) {
110
+ return false;
111
+ }
112
+
113
+ try {
114
+ return await getBunPassword().verify(plain, hash);
115
+ } catch {
116
+ // Malformed hash, unsupported algorithm, or any other internal error —
117
+ // treat as verification failure. See function-level comment for rationale.
118
+ return false;
119
+ }
120
+ }