@softure-ai/auth 0.1.11 → 0.1.12

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.
package/CHANGELOG.md CHANGED
@@ -4,12 +4,29 @@ Newest first. Each version lists what changed for an app that uses `@softure-ai/
4
4
  production, the version gets a line `verified in: <app>@<commit>` ([docs/05](../../docs/05-adoption-playbook.md),
5
5
  "Definition of done"). Versions before the first one below are described in their GitHub Releases (`auth@x.y.z`).
6
6
 
7
+ ## 0.1.12
8
+
9
+ - `createAuthGuard({ redirect: "relative" })` answers with a path-only `Location` (`/login?next=…`), so a stack on a
10
+ port or host the config cannot list keeps the browser where it is; `createAuthGuard({ excludeExact })` lets exact
11
+ paths through (`/pricing` and `/pricing/`, not `/pricing/plans`) for an app with an exact public allowlist (#314).
12
+ - `createTestAccount` builds fixture accounts (#314): `id`, `createdAt` and a ready `passwordHash` (stored as is, never
13
+ hashed); a module context (`{ db, clock, config }`) as the first argument hashes with the app's parameters and, with
14
+ `runHooks: true`, runs the app's `onRegistered` in the account's transaction (`fields` for `event.fields`). One
15
+ password with one set of parameters is hashed once per test run.
16
+ - `adminEmails` also takes the raw environment string (#314): entries split on commas and whitespace, trimmed and
17
+ lowercased; an entry that is not an email is dropped with one log line naming its position and grants nothing. A
18
+ list still refuses a bad entry at config load.
19
+
7
20
  ## 0.1.11
8
21
 
9
22
  - The guard's login redirect uses core's `resolveAppOrigin` (#311): an origin listed in the config's
10
23
  `origins.trustedOrigins` is trusted like one in the guard's `trustedOrigins` option, and `origins.trustRequestHost`
11
24
  is honoured. A non-http(s) `X-Forwarded-Proto` value now falls back to the URL's scheme instead of making the
12
25
  origin unreadable. Needs `@softure-ai/core` 0.1.8.
26
+ - `AUTH_RATE_LIMIT_BUCKETS` declares what each bucket counts by: `register`, `login`, `password-reset` and
27
+ `password-reset-confirm` `key: "ip"`; `login-account`, `change-password` and `password-reset-account`
28
+ `key: "account"`. Change one threshold with `overrideBuckets` from `@softure-ai/security` 0.1.8.
29
+ - Requires `@softure-ai/security` `^0.1.8`: earlier versions refuse the `key` field.
13
30
 
14
31
  ## 0.1.10
15
32
 
package/README.md CHANGED
@@ -50,7 +50,7 @@ same way.
50
50
  import { defineSoftureConfig } from "@softure-ai/core";
51
51
  import { registerSoftureConfig } from "@softure-ai/core/next";
52
52
  import { auth, AUTH_RATE_LIMIT_BUCKETS } from "@softure-ai/auth";
53
- import { cloudflareIp, security } from "@softure-ai/security";
53
+ import { cloudflareIp, overrideBuckets, security } from "@softure-ai/security";
54
54
 
55
55
  const config = defineSoftureConfig({
56
56
  database: { url: process.env.DATABASE_URL! },
@@ -58,8 +58,8 @@ const config = defineSoftureConfig({
58
58
  timezone: "Europe/Warsaw",
59
59
  appOrigin: process.env.APP_ORIGIN!,
60
60
  modules: [
61
- // auth counts attempts in these buckets; change the numbers, keep the names.
62
- security({ clientIp: cloudflareIp(), buckets: { ...AUTH_RATE_LIMIT_BUCKETS } }),
61
+ // auth counts attempts in these buckets; change the numbers with overrideBuckets, keep the names.
62
+ security({ clientIp: cloudflareIp(), buckets: overrideBuckets(AUTH_RATE_LIMIT_BUCKETS, { login: { limit: 100 } }) }),
63
63
  auth({
64
64
  routes: { afterLogin: "/dashboard" },
65
65
  password: { minLength: 12 },
@@ -87,7 +87,7 @@ export default config;
87
87
  | `legacySession` | `{ cookieName, tokenPattern }` | none | Sessions of the system the app took over (section 5, "Adopting existing sessions"). |
88
88
  | `registrationClosed` | `boolean` | `false` | Declared default of the `auth.registration_closed` switch. |
89
89
  | `roles` | `string[]` | `[]` | Role names the app checks besides `admin` (always declared): `a-z`, `0-9`, `_`, `-`, at most 32. |
90
- | `adminEmails` | `string[]` | `[]` | Initial admin list: while an email is listed, its account holds `admin`. Auth does not verify emails, so create these accounts before you deploy the list (section 4, "Roles"). |
90
+ | `adminEmails` | `string[] \| string` | `[]` | Initial admin list: while an email is listed, its account holds `admin`. Auth does not verify emails, so create these accounts before you deploy the list (section 4, "Roles"). A list refuses an entry that is not an email at config load. A string is the raw environment value (`adminEmails: process.env.ADMIN_EMAILS ?? ""`): entries split on commas and whitespace, trimmed and lowercased; one that is not an email is dropped with one log line naming its position and grants nothing. |
91
91
  | `onRegistered` | `(event, ctx) => Promise<void>` | none | Called after the account is created, inside the same transaction. |
92
92
  | `rewriteRedirect` | `(path, { config, searchParams? }) => string \| Promise<string>` | none | Rewrites the path of every auth redirect: the actions' (login, sign-up, password reset, logout), the login and register pages' redirect of a signed-in visitor and `requireUser`'s redirect to login, e.g. `tagRedirect` from `@softure-ai/analytics/next`, which keeps the channel tag. A page passes its own `searchParams` (`URLSearchParams`; `requireUser` hands over the ones the page gives it); an action passes none, and during a page's render the `Referer` is the page before, not the page itself. A result that is not a path on this app, or an error, leaves auth's own path. |
93
93
  | `passwordReset.send` | `(link, user, details) => Promise<void>` | none | Delivers reset links (section 4, "Password reset"). Without it password reset is off. |
@@ -108,7 +108,9 @@ that stack only.
108
108
  per client address, `login-account` 10 per email, `change-password` 10 per user,
109
109
  `password-reset` 10 (link requests) and `password-reset-confirm` 10 (new passwords) per client
110
110
  address, `password-reset-account` 3 per email (the mails one address can get), each per 15
111
- minutes. Attempts are counted before any password is hashed. A successful login forgets the
111
+ minutes. Each bucket declares what it counts by (`key: "ip"` or `"account"`, security README §3), so
112
+ `listRateLimitBuckets(config)` names the IP-keyed ones; `overrideBuckets(AUTH_RATE_LIMIT_BUCKETS, { login: { limit: 500 } })`
113
+ changes one threshold and keeps the rest. Attempts are counted before any password is hashed. A successful login forgets the
112
114
  email's failed attempts, not the address's: the per-address `login` bucket counts every login,
113
115
  successful or not, so a test suite that logs in many times from one address must raise `login`
114
116
  (or give each test its own address). `login-account` is a lockout by design: ten wrong
@@ -250,10 +252,17 @@ const guard = createAuthGuard(softureConfig, { protect: ["/"], exclude: ["/", "/
250
252
  ```
251
253
 
252
254
  In `exclude`, `"/"` is the home page only; any other entry matches whole segments like `protect`.
255
+ An app that keeps an exact allowlist instead lists the paths in `excludeExact`: `/pricing` there lets
256
+ `/pricing` and `/pricing/` through and guards `/pricing/plans`.
253
257
  Auth's own public pages (login, register, forgot and reset password) and `/api/auth/session` are
254
258
  never guarded, so `protect: ["/"]` cannot send the login page to itself. The change-password route
255
259
  stays guarded even under an excluded prefix.
256
260
 
261
+ A stack the config cannot list (an integration run on a random port, a host added at deploy time)
262
+ sets `redirect: "relative"`: the `Location` is the path only (`/login?next=%2Faccount`), so the browser
263
+ stays on the host and port it used and no request header is read. An app whose image serves hosts it
264
+ does not know in advance can instead set the config's `origins.trustRequestHost` (core README).
265
+
257
266
  **Roles.** A role is a declared name (`admin`, plus `auth({ roles: ["editor"] })`) held by an
258
267
  account: as a row in `auth.user_roles`, or, for `admin` only, through `adminEmails`. Nothing is
259
268
  granted by default: with no admin listed and no rows, every admin-only surface stays closed.
@@ -412,9 +421,9 @@ auth({
412
421
 
413
422
  **Tests.** `createTestAccount(db, { email, password, roles?, scrypt? })` from `@softure-ai/auth/testing`
414
423
  writes an account and its role rows in one transaction, hashed as registration hashes it, and returns
415
- the `AuthUser`. It is for tests that need an account but are not about registration: no `onRegistered`
416
- hook runs (no consent row) and no session is opened, so the test signs in through the login form.
417
- Pass the app's parameters, so the first login does not rehash:
424
+ the `AuthUser`. It is for tests that need an account but are not about registration: no session is
425
+ opened, so the test signs in through the login form. One password with one set of parameters is hashed
426
+ once per test run. Pass the app's parameters, so the first login does not rehash:
418
427
 
419
428
  ```ts
420
429
  import { getAuthOptions } from "@softure-ai/auth/server";
@@ -428,7 +437,24 @@ const user = await createTestAccount(handle.db, {
428
437
  });
429
438
  ```
430
439
 
431
- An invalid or taken email throws. The entry is server-only and never imported by the module itself.
440
+ A fixture account takes more, with a module context (`{ db, clock, config }`) instead of the database:
441
+
442
+ ```ts
443
+ const user = await createTestAccount(ctx, {
444
+ id: "0b9f5a0e-3c1d-4f6e-9a2b-7c8d9e0f1a2b",
445
+ email: "ada@example.com",
446
+ passwordHash: FIXTURE_HASH, // from hashPassword, stored as is: nothing is hashed
447
+ createdAt: new Date("2025-01-02T03:04:05Z"),
448
+ runHooks: true, // the app's onRegistered runs in the account's transaction
449
+ fields: { channel: "newsletter" }, // event.fields for the hook
450
+ });
451
+ ```
452
+
453
+ With a context and no `scrypt`, a `password` is hashed with the app's parameters. `runHooks` hands the
454
+ hook a consent accepted at `createdAt` (null when `requireConsent` is off); it needs the context and
455
+ throws with a bare database. An invalid or taken email, a `passwordHash` that is not a module hash or a
456
+ hook that throws rolls everything back and throws. The entry is server-only and never imported by the
457
+ module itself.
432
458
 
433
459
  ## 5. Migrations and tables
434
460
 
package/dist/index.d.ts CHANGED
@@ -16,30 +16,37 @@ export declare const AUTH_RATE_LIMIT_BUCKETS: {
16
16
  readonly register: {
17
17
  readonly limit: 5;
18
18
  readonly windowMinutes: 15;
19
+ readonly key: "ip";
19
20
  };
20
21
  readonly login: {
21
22
  readonly limit: 50;
22
23
  readonly windowMinutes: 15;
24
+ readonly key: "ip";
23
25
  };
24
26
  readonly "login-account": {
25
27
  readonly limit: 10;
26
28
  readonly windowMinutes: 15;
29
+ readonly key: "account";
27
30
  };
28
31
  readonly "change-password": {
29
32
  readonly limit: 10;
30
33
  readonly windowMinutes: 15;
34
+ readonly key: "account";
31
35
  };
32
36
  readonly "password-reset": {
33
37
  readonly limit: 10;
34
38
  readonly windowMinutes: 15;
39
+ readonly key: "ip";
35
40
  };
36
41
  readonly "password-reset-account": {
37
42
  readonly limit: 3;
38
43
  readonly windowMinutes: 15;
44
+ readonly key: "account";
39
45
  };
40
46
  readonly "password-reset-confirm": {
41
47
  readonly limit: 10;
42
48
  readonly windowMinutes: 15;
49
+ readonly key: "ip";
43
50
  };
44
51
  };
45
52
  /**
@@ -174,7 +181,7 @@ export declare const auth: import("@softure-ai/core").ModuleFactory<{
174
181
  requireConsent: import("zod").ZodDefault<import("zod").ZodBoolean>;
175
182
  registrationClosed: import("zod").ZodDefault<import("zod").ZodBoolean>;
176
183
  roles: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodString>>;
177
- adminEmails: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodEmail>>>;
184
+ adminEmails: import("zod").ZodDefault<import("zod").ZodUnion<readonly [import("zod").ZodArray<import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodEmail>>, import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodTransform<string[], string>>]>>;
178
185
  passwordReset: import("zod").ZodPrefault<import("zod").ZodObject<{
179
186
  send: import("zod").ZodOptional<import("zod").ZodCustom<import("./password-reset-sender.js").PasswordResetSender, import("./password-reset-sender.js").PasswordResetSender>>;
180
187
  ttlMinutes: import("zod").ZodDefault<import("zod").ZodNumber>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,SAAS,SAAS,CAAC;AAEhC,2DAA2D;AAC3D,eAAO,MAAM,0BAA0B,6BAA6B,CAAC;AAErE;;;GAGG;AACH,eAAO,MAAM,uBAAuB,4CAA4C,CAAC;AAEjF;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAQ1B,CAAC;AAEX;;;GAGG;AACH,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kCAwCf,CAAC;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AACxD,YAAY,EACV,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,QAAQ,EACR,UAAU,EACV,eAAe,EACf,QAAQ,GACT,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC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,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC3F,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC3I,OAAO,EAAE,0BAA0B,EAAE,KAAK,oBAAoB,EAAE,KAAK,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC7H,OAAO,EAAE,gBAAgB,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -21,13 +21,13 @@ export const REGISTRATION_CLOSED_ENV = "SOFTURE_SWITCH_AUTH_REGISTRATION_CLOSED"
21
21
  * and `password-reset-account` per email, which bounds the mails one address can receive.
22
22
  */
23
23
  export const AUTH_RATE_LIMIT_BUCKETS = {
24
- register: { limit: 5, windowMinutes: 15 },
25
- login: { limit: 50, windowMinutes: 15 },
26
- "login-account": { limit: 10, windowMinutes: 15 },
27
- "change-password": { limit: 10, windowMinutes: 15 },
28
- "password-reset": { limit: 10, windowMinutes: 15 },
29
- "password-reset-account": { limit: 3, windowMinutes: 15 },
30
- "password-reset-confirm": { limit: 10, windowMinutes: 15 },
24
+ register: { limit: 5, windowMinutes: 15, key: "ip" },
25
+ login: { limit: 50, windowMinutes: 15, key: "ip" },
26
+ "login-account": { limit: 10, windowMinutes: 15, key: "account" },
27
+ "change-password": { limit: 10, windowMinutes: 15, key: "account" },
28
+ "password-reset": { limit: 10, windowMinutes: 15, key: "ip" },
29
+ "password-reset-account": { limit: 3, windowMinutes: 15, key: "account" },
30
+ "password-reset-confirm": { limit: 10, windowMinutes: 15, key: "ip" },
31
31
  };
32
32
  /**
33
33
  * Enables accounts in `softure.config.ts` (next to `security({ ... })`):
@@ -36,7 +36,7 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
36
36
  export const auth = defineModule({
37
37
  manifest: {
38
38
  id: MODULE_ID,
39
- version: "0.1.11",
39
+ version: "0.1.12",
40
40
  dependsOn: { security: "^0.1.0", mailing: "^0.1.0?", ops: "^0.1.0?" },
41
41
  dbSchema: "auth",
42
42
  tables: ["users", "sessions", "user_roles", "password_resets"],
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,qIAAqI;AACrI,4EAA4E;AAC5E,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC;AAEhC,2DAA2D;AAC3D,MAAM,CAAC,MAAM,0BAA0B,GAAG,0BAA0B,CAAC;AAErE;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,yCAAyC,CAAC;AAEjF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,QAAQ,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,aAAa,EAAE,EAAE,EAAE;IACzC,KAAK,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE;IACvC,eAAe,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE;IACjD,iBAAiB,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa,E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iBAAiB,EAAE;SACpE;QACD,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE;KAC1C;IACD,QAAQ,EAAE,YAAY;IACtB,OAAO,EAAE,iBAAiB;IAC1B,UAAU,EAAE,EAAE,GAAG,EAAE,oBAAoB,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,gBAAgB,CAAC,EAAE;IAC5E,OAAO,EAAE,sBAAsB;IAC/B,MAAM,EAAE,eAAe;CACxB,CAAC,CAAC;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAWxD,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAqB,MAAM,qBAAqB,CAAC;AAE3F,OAAO,EAAE,0BAA0B,EAAuD,MAAM,4BAA4B,CAAC;AAC7H,OAAO,EAAE,gBAAgB,EAAsB,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC"}
package/dist/options.d.ts CHANGED
@@ -57,7 +57,7 @@ export declare const authOptionsSchema: z.ZodObject<{
57
57
  requireConsent: z.ZodDefault<z.ZodBoolean>;
58
58
  registrationClosed: z.ZodDefault<z.ZodBoolean>;
59
59
  roles: z.ZodDefault<z.ZodArray<z.ZodString>>;
60
- adminEmails: z.ZodDefault<z.ZodArray<z.ZodPipe<z.ZodString, z.ZodEmail>>>;
60
+ adminEmails: z.ZodDefault<z.ZodUnion<readonly [z.ZodArray<z.ZodPipe<z.ZodString, z.ZodEmail>>, z.ZodPipe<z.ZodString, z.ZodTransform<string[], string>>]>>;
61
61
  passwordReset: z.ZodPrefault<z.ZodObject<{
62
62
  send: z.ZodOptional<z.ZodCustom<PasswordResetSender, PasswordResetSender>>;
63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C,OAAO,YAAY,CAAC,CAAC"}
package/dist/options.js CHANGED
@@ -32,6 +32,29 @@ const scryptSchema = z.strictObject({
32
32
  /** p: parallelization. */
33
33
  parallelization: z.number().int().min(1).max(16).default(1),
34
34
  });
35
+ const adminEmailSchema = z.string().trim().toLowerCase().max(MAX_EMAIL_LENGTH).pipe(z.email("must be an email address"));
36
+ /**
37
+ * `adminEmails` given as the raw environment string: entries split on commas and whitespace, trimmed and
38
+ * lowercased. One bad entry must not stop the app, so entries that are not emails are dropped with one log
39
+ * line naming their positions (never their values) and grant nothing.
40
+ */
41
+ function parseAdminEmailList(raw) {
42
+ const entries = raw.split(/[\s,]+/).filter((entry) => entry !== "");
43
+ const emails = [];
44
+ const dropped = [];
45
+ entries.forEach((entry, index) => {
46
+ const parsed = adminEmailSchema.safeParse(entry);
47
+ if (parsed.success)
48
+ emails.push(parsed.data);
49
+ else
50
+ dropped.push(index + 1);
51
+ });
52
+ if (dropped.length > 0) {
53
+ const positions = dropped.join(", ");
54
+ console.warn(`@softure-ai/auth: adminEmails: ${String(dropped.length)} of ${String(entries.length)} entries are not email addresses and grant no role (positions ${positions})`);
55
+ }
56
+ return emails;
57
+ }
35
58
  export const authOptionsSchema = z.strictObject({
36
59
  password: z
37
60
  .strictObject({
@@ -92,7 +115,9 @@ export const authOptionsSchema = z.strictObject({
92
115
  * Initial admin list: while an email is listed, the account with that email holds `admin`.
93
116
  * Auth does not verify emails, so create these accounts before deploying the list.
94
117
  */
95
- adminEmails: z.array(z.string().trim().toLowerCase().max(MAX_EMAIL_LENGTH).pipe(z.email("must be an email address"))).default([]),
118
+ adminEmails: z
119
+ .union([z.array(adminEmailSchema), z.string().transform(parseAdminEmailList)], { error: "must be a list of email addresses or one string of them" })
120
+ .default([]),
96
121
  passwordReset: z
97
122
  .strictObject({
98
123
  /** Delivers reset links. Without it password reset is off: no link, and its pages are not found. */
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"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-7,6 +7,11 @@ export interface AuthGuardOptions {
7
7
  * public pages here). `"/"` here is the home page only. The change-password route stays guarded.
8
8
  */
9
9
  readonly exclude?: readonly string[];
10
+ /**
11
+ * Paths that never need a session, matched whole (`/pricing` and `/pricing/`, not `/pricing/plans`), for an app
12
+ * that protects everything except an exact allowlist. Compared decoded and lowercased, like the other lists.
13
+ */
14
+ readonly excludeExact?: readonly string[];
10
15
  /**
11
16
  * Origins besides `appOrigin` and the config's `origins.trustedOrigins` that the login redirect may stay on
12
17
  * (`https://example.com`). Prefer the config's block, which every module reads. The request's public origin
@@ -14,6 +19,12 @@ export interface AuthGuardOptions {
14
19
  * `appOrigin`.
15
20
  */
16
21
  readonly trustedOrigins?: readonly string[];
22
+ /**
23
+ * `"absolute"` (default): the login URL is built on the resolved origin (above). `"relative"`: the `Location` is
24
+ * the path only (`/login?next=…`), so the browser stays on whatever host and port it used; for a stack served on
25
+ * ports or hosts the config cannot list (an integration run on a random port).
26
+ */
27
+ readonly redirect?: "absolute" | "relative";
17
28
  }
18
29
  export type AuthGuard = (request: Request) => Response | null;
19
30
  /** A guard that redirects to the login page (with `?next=`) for protected paths without a session cookie. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/proxy/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAiC,KAAK,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAIrF,MAAM,WAAW,gBAAgB;IAC/B,kGAAkG;IAClG,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;;;;OAKG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAKD,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,QAAQ,GAAG,IAAI,CAAC;AAE9D,6GAA6G;AAC7G,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAgC3F"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/proxy/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAiC,KAAK,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAIrF,MAAM,WAAW,gBAAgB;IAC/B,kGAAkG;IAClG,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C;;;;;OAKG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;CAC7C;AAKD,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,QAAQ,GAAG,IAAI,CAAC;AAE9D,6GAA6G;AAC7G,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAoC3F"}
@@ -21,10 +21,13 @@ export function createAuthGuard(config, options) {
21
21
  // Auth's own public pages: guarding them would send a visitor from the login page to itself.
22
22
  const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE].map((path) => normalizePrefix(path, "excluded"));
23
23
  const excluded = (options.exclude ?? []).map((prefix) => normalizePrefix(prefix, "excluded"));
24
+ const exactExcluded = new Set((options.excludeExact ?? []).map((path) => normalizePrefix(path, "excluded")));
24
25
  const trustedOrigins = (options.trustedOrigins ?? []).map(normalizeOrigin);
25
26
  const isGuarded = (path) => {
26
27
  if (isUnder(path, changePassword))
27
28
  return true;
29
+ if (exactExcluded.has(normalizeTrailingSlash(path)))
30
+ return false;
28
31
  if ([...publicPaths, ...excluded].some((prefix) => isExcludedBy(path, prefix)))
29
32
  return false;
30
33
  return prefixes.some((prefix) => isUnder(path, prefix));
@@ -43,15 +46,20 @@ export function createAuthGuard(config, options) {
43
46
  // the request URL carries an internal host, and request headers alone are never trusted.
44
47
  const login = new URL(routes.login, resolveAppOrigin(config, request, { trustedOrigins }));
45
48
  login.searchParams.set("next", `${url.pathname}${url.search}`);
46
- return Response.redirect(login, 307);
49
+ if (options.redirect !== "relative")
50
+ return Response.redirect(login, 307);
51
+ // A path-only Location reads no request header at all; `Response.redirect` would need an absolute URL.
52
+ return new Response(null, { status: 307, headers: { location: `${login.pathname}${login.search}` } });
47
53
  };
48
54
  }
49
55
  function normalizePrefix(prefix, kind) {
50
56
  if (!prefix.startsWith("/")) {
51
57
  throw new Error(`createAuthGuard: ${kind} path "${prefix}" must start with /`);
52
58
  }
53
- const trimmed = prefix.length > 1 && prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
54
- return trimmed.toLowerCase();
59
+ return normalizeTrailingSlash(prefix).toLowerCase();
60
+ }
61
+ function normalizeTrailingSlash(path) {
62
+ return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
55
63
  }
56
64
  /** `entry` as an origin (`https://example.com`, a trailing `/` dropped); anything else is a config error. */
57
65
  function normalizeOrigin(entry) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/proxy/index.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,sDAAsD;AACtD,EAAE;AACF,6FAA6F;AAC7F,6FAA6F;AAC7F,mGAAmG;AACnG,mGAAmG;AACnG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAsB,MAAM,kBAAkB,CAAC;AACrF,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB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AAW,EAAE,CAAC;AACtD,CAAC;AAED,SAAS,sBAAsB,CAAC,IAAY;IAC1C,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1E,CAAC;AAED,6GAA6G;AAC7G,SAAS,eAAe,CAAC,KAAa;IACpC,MAAM,MAAM,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,oCAAoC,KAAK,yDAAyD,CAAC,CAAC;IACtH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,UAAU,CAAC,QAAgB;IAClC,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAC;IACpD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,6FAA6F;AAC7F,SAAS,YAAY,CAAC,QAAgB,EAAE,MAAc;IACpD,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AACvE,CAAC;AAED,SAAS,OAAO,CAAC,QAAgB,EAAE,MAAc;IAC/C,OAAO,MAAM,KAAK,GAAG,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,CAAC,CAAC;AACpF,CAAC"}
@@ -1,17 +1,39 @@
1
1
  import type { Queryable } from "@softure-ai/db";
2
2
  import type { AuthUser } from "../contract.js";
3
3
  import { type ScryptParams } from "../options.js";
4
- export interface TestAccountInput {
4
+ import type { AuthContext } from "../server/sessions.js";
5
+ interface TestAccountBase {
5
6
  readonly email: string;
6
- readonly password: string;
7
+ /** The row's id (a uuid); the database draws one when absent. */
8
+ readonly id?: string;
9
+ /** `created_at` and `password_changed_at`; now when absent. */
10
+ readonly createdAt?: Date;
7
11
  /** Rows of `auth.user_roles`, e.g. `["admin"]`. */
8
12
  readonly roles?: readonly string[];
9
- /** The app's hash parameters (`getAuthOptions(config).password.scrypt`), so its login does not rehash. */
13
+ /** Run the app's `onRegistered` hook in the account's transaction. Needs a module context as the first argument. */
14
+ readonly runHooks?: boolean;
15
+ /** `event.fields` for the hook, as the register form would send the app's `registrationFields`. */
16
+ readonly fields?: Readonly<Record<string, string>>;
17
+ }
18
+ /** An account with a password, hashed here (once per password and parameters). */
19
+ export interface TestAccountInput extends TestAccountBase {
20
+ readonly password: string;
21
+ /** Hash parameters; the app's (`getAuthOptions(config).password.scrypt`) when a module context is given, else auth's default. */
10
22
  readonly scrypt?: ScryptParams;
23
+ readonly passwordHash?: never;
24
+ }
25
+ /** An account with a ready hash, stored as is. */
26
+ export interface TestAccountHashInput extends TestAccountBase {
27
+ /** A ready hash from `hashPassword`, stored as is: nothing is hashed. */
28
+ readonly passwordHash: string;
29
+ readonly password?: never;
30
+ readonly scrypt?: never;
11
31
  }
12
32
  /**
13
33
  * Creates an account and its roles in one transaction and returns it. The email is normalized as
14
- * registration normalizes it. An invalid or taken email throws: in test setup it is a bug of the test.
34
+ * registration normalizes it. An invalid or taken email, a malformed `passwordHash` or a hook that
35
+ * throws rolls everything back and throws: in test setup it is a bug of the test.
15
36
  */
16
- export declare function createTestAccount(db: Queryable, input: TestAccountInput): Promise<AuthUser>;
37
+ export declare function createTestAccount(target: Queryable | AuthContext, input: TestAccountInput | TestAccountHashInput): Promise<AuthUser>;
38
+ export {};
17
39
  //# sourceMappingURL=account.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../src/testing/account.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAA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MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACpD;AAED,kFAAkF;AAClF,MAAM,WAAW,gBAAiB,SAAQ,eAAe;IACvD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,iIAAiI;IACjI,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,YAAY,CAAC,EAAE,KAAK,CAAC;CAC/B;AAED,kDAAkD;AAClD,MAAM,WAAW,oBAAqB,SAAQ,eAAe;IAC3D,yEAAyE;IACzE,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,QAAQ,CAAC,EAAE,KAAK,CAAC;IAC1B,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,SAAS,GAAG,WAAW,EAAE,KAAK,EAAE,gBAAgB,GAAG,oBAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4B1I"}
@@ -1,23 +1,32 @@
1
1
  import { DEFAULT_SCRYPT_COST } from "../options.js";
2
2
  import { userRoles, users } from "../schema.js";
3
- import { hashPassword } from "../server/password.js";
3
+ import { getAuthOptions } from "../server/options.js";
4
+ import { hashPassword, isPasswordHash } from "../server/password.js";
4
5
  import { parseEmail } from "../server/validation.js";
5
6
  /** Auth's own hash parameters when the app sets none (`password.scrypt` in `auth({ ... })`). */
6
7
  const DEFAULT_SCRYPT = { cost: DEFAULT_SCRYPT_COST, blockSize: 8, parallelization: 1 };
8
+ /** One hash per password and parameters for the whole test run: scrypt is the slow part of a big suite's setup. */
9
+ const hashCache = new Map();
7
10
  /**
8
11
  * Creates an account and its roles in one transaction and returns it. The email is normalized as
9
- * registration normalizes it. An invalid or taken email throws: in test setup it is a bug of the test.
12
+ * registration normalizes it. An invalid or taken email, a malformed `passwordHash` or a hook that
13
+ * throws rolls everything back and throws: in test setup it is a bug of the test.
10
14
  */
11
- export async function createTestAccount(db, input) {
15
+ export async function createTestAccount(target, input) {
16
+ const ctx = isModuleContext(target) ? target : null;
17
+ const db = isModuleContext(target) ? target.db : target;
12
18
  const email = parseEmail(input.email);
13
19
  if (!email.ok)
14
20
  throw new Error(`createTestAccount: "${input.email}" is not a valid email`);
15
- const passwordHash = await hashPassword(input.password, input.scrypt ?? DEFAULT_SCRYPT);
16
- const now = new Date();
21
+ if (input.runHooks === true && ctx === null) {
22
+ throw new Error("createTestAccount: runHooks needs a module context ({ db, clock, config }) instead of a database");
23
+ }
24
+ const passwordHash = await readPasswordHash(input, email.value, ctx);
25
+ const now = input.createdAt ?? new Date();
17
26
  return db.transaction(async (tx) => {
18
27
  const [row] = await tx
19
28
  .insert(users)
20
- .values({ email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
29
+ .values({ ...(input.id === undefined ? {} : { id: input.id }), email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
21
30
  .onConflictDoNothing({ target: users.email })
22
31
  .returning();
23
32
  if (row === undefined)
@@ -25,7 +34,33 @@ export async function createTestAccount(db, input) {
25
34
  const roles = input.roles ?? [];
26
35
  if (roles.length > 0)
27
36
  await tx.insert(userRoles).values(roles.map((role) => ({ userId: row.id, role, grantedAt: now })));
28
- return { id: row.id, email: row.email, createdAt: row.createdAt };
37
+ const user = { id: row.id, email: row.email, createdAt: row.createdAt };
38
+ if (input.runHooks === true && ctx !== null) {
39
+ const options = getAuthOptions(ctx.config);
40
+ const consent = options.requireConsent ? { acceptedAt: now } : null;
41
+ await options.onRegistered?.({ user, consent, fields: input.fields ?? {} }, { ...ctx, db: tx });
42
+ }
43
+ return user;
29
44
  });
30
45
  }
46
+ async function readPasswordHash(input, email, ctx) {
47
+ if (input.passwordHash !== undefined) {
48
+ if (!isPasswordHash(input.passwordHash))
49
+ throw new Error(`createTestAccount: the passwordHash for "${email}" is not a hash from hashPassword`);
50
+ return input.passwordHash;
51
+ }
52
+ const scrypt = input.scrypt ?? (ctx === null ? DEFAULT_SCRYPT : getAuthOptions(ctx.config).password.scrypt);
53
+ const key = JSON.stringify([scrypt.cost, scrypt.blockSize, scrypt.parallelization, input.password]);
54
+ let hash = hashCache.get(key);
55
+ if (hash === undefined) {
56
+ hash = hashPassword(input.password, scrypt);
57
+ hashCache.set(key, hash);
58
+ // A failed hash is not kept, so the next call tries again.
59
+ void hash.catch(() => hashCache.delete(key));
60
+ }
61
+ return hash;
62
+ }
63
+ function isModuleContext(target) {
64
+ return "config" in target && "clock" in target && "db" in target;
65
+ }
31
66
  //# sourceMappingURL=account.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"account.js","sourceRoot":"","sources":["../../src/testing/account.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAqB,MAAM,eAAe,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,gGAAgG;AAChG,MAAM,cAAc,GAAiB,EAAE,IAAI,EAAE,mBAAmB,EAAE,SAAS,EAAE,CAAC,EAAE,eAAe,EAAE,CAAC,EAAE,CAAC;AAWrG;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,EAAa,EAAE,KAAuB;IAC5E,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACtC,IAAI,CAAC,KAAK,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,KAAK,CAAC,KAAK,wBAAwB,CAAC,CAAC;IAC3F,MAAM,YAAY,GAAG,MAAM,YAAY,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,IAAI,cAAc,CAAC,CAAC;IACxF,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IAEvB,OAAO,EAAE,CAAC,WAAW,CAAC,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eAAe,CAAC,MAA+B;IACtD,OAAO,QAAQ,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC;AACnE,CAAC"}
@@ -1,2 +1,2 @@
1
- export { createTestAccount, type TestAccountInput } from "./account.js";
1
+ export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,mGAAmG;AACnG,OAAO,EAAE,iBAAiB,EAAyB,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,mGAAmG;AACnG,OAAO,EAAE,iBAAiB,EAAoD,MAAM,cAAc,CAAC"}
package/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "auth",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "dependsOn": { "security": "^0.1.0", "mailing": "^0.1.0?", "ops": "^0.1.0?" },
5
5
  "dbSchema": "auth",
6
6
  "tables": ["users", "sessions", "user_roles", "password_resets"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softure-ai/auth",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "SOFTURE AI auth module: users, scrypt passwords, database sessions, register with consent, login, logout, password change, roles, a proxy route guard, pages and forms for Next.js, and a password reset sender over @softure-ai/mailing.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -74,7 +74,7 @@
74
74
  "dependencies": {
75
75
  "@softure-ai/core": "^0.1.8",
76
76
  "@softure-ai/db": "^0.1.0",
77
- "@softure-ai/security": "^0.1.0",
77
+ "@softure-ai/security": "^0.1.8",
78
78
  "zod": "^4.6.5"
79
79
  },
80
80
  "peerDependencies": {
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // tables, and the development reset sender. Database work is in `@softure-ai/auth/server`, the Next.js adapter in `/next`, the route
3
3
  // guard in `/proxy`, the forms in `/ui` and the role scripts in `/scripts`.
4
4
  import { defineModule, resolveMigrationsDir } from "@softure-ai/core";
5
+ import type { RateLimitBucketInput } from "@softure-ai/security";
5
6
  import { authMessages } from "./messages/index.js";
6
7
  import { authOptionsSchema } from "./options.js";
7
8
  import { checkAuthTables } from "./server/health.js";
@@ -25,14 +26,14 @@ export const REGISTRATION_CLOSED_ENV = "SOFTURE_SWITCH_AUTH_REGISTRATION_CLOSED"
25
26
  * and `password-reset-account` per email, which bounds the mails one address can receive.
26
27
  */
27
28
  export const AUTH_RATE_LIMIT_BUCKETS = {
28
- register: { limit: 5, windowMinutes: 15 },
29
- login: { limit: 50, windowMinutes: 15 },
30
- "login-account": { limit: 10, windowMinutes: 15 },
31
- "change-password": { limit: 10, windowMinutes: 15 },
32
- "password-reset": { limit: 10, windowMinutes: 15 },
33
- "password-reset-account": { limit: 3, windowMinutes: 15 },
34
- "password-reset-confirm": { limit: 10, windowMinutes: 15 },
35
- } as const;
29
+ register: { limit: 5, windowMinutes: 15, key: "ip" },
30
+ login: { limit: 50, windowMinutes: 15, key: "ip" },
31
+ "login-account": { limit: 10, windowMinutes: 15, key: "account" },
32
+ "change-password": { limit: 10, windowMinutes: 15, key: "account" },
33
+ "password-reset": { limit: 10, windowMinutes: 15, key: "ip" },
34
+ "password-reset-account": { limit: 3, windowMinutes: 15, key: "account" },
35
+ "password-reset-confirm": { limit: 10, windowMinutes: 15, key: "ip" },
36
+ } as const satisfies Readonly<Record<string, RateLimitBucketInput>>;
36
37
 
37
38
  /**
38
39
  * Enables accounts in `softure.config.ts` (next to `security({ ... })`):
@@ -41,7 +42,7 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
41
42
  export const auth = defineModule({
42
43
  manifest: {
43
44
  id: MODULE_ID,
44
- version: "0.1.11",
45
+ version: "0.1.12",
45
46
  dependsOn: { security: "^0.1.0", mailing: "^0.1.0?", ops: "^0.1.0?" },
46
47
  dbSchema: "auth",
47
48
  tables: ["users", "sessions", "user_roles", "password_resets"],
package/src/options.ts CHANGED
@@ -63,6 +63,29 @@ const scryptSchema = z.strictObject({
63
63
  parallelization: z.number().int().min(1).max(16).default(1),
64
64
  });
65
65
 
66
+ const adminEmailSchema = z.string().trim().toLowerCase().max(MAX_EMAIL_LENGTH).pipe(z.email("must be an email address"));
67
+
68
+ /**
69
+ * `adminEmails` given as the raw environment string: entries split on commas and whitespace, trimmed and
70
+ * lowercased. One bad entry must not stop the app, so entries that are not emails are dropped with one log
71
+ * line naming their positions (never their values) and grant nothing.
72
+ */
73
+ function parseAdminEmailList(raw: string): string[] {
74
+ const entries = raw.split(/[\s,]+/).filter((entry) => entry !== "");
75
+ const emails: string[] = [];
76
+ const dropped: number[] = [];
77
+ entries.forEach((entry, index) => {
78
+ const parsed = adminEmailSchema.safeParse(entry);
79
+ if (parsed.success) emails.push(parsed.data);
80
+ else dropped.push(index + 1);
81
+ });
82
+ if (dropped.length > 0) {
83
+ const positions = dropped.join(", ");
84
+ console.warn(`@softure-ai/auth: adminEmails: ${String(dropped.length)} of ${String(entries.length)} entries are not email addresses and grant no role (positions ${positions})`);
85
+ }
86
+ return emails;
87
+ }
88
+
66
89
  export const authOptionsSchema = z.strictObject({
67
90
  password: z
68
91
  .strictObject({
@@ -128,7 +151,9 @@ export const authOptionsSchema = z.strictObject({
128
151
  * Initial admin list: while an email is listed, the account with that email holds `admin`.
129
152
  * Auth does not verify emails, so create these accounts before deploying the list.
130
153
  */
131
- adminEmails: z.array(z.string().trim().toLowerCase().max(MAX_EMAIL_LENGTH).pipe(z.email("must be an email address"))).default([]),
154
+ adminEmails: z
155
+ .union([z.array(adminEmailSchema), z.string().transform(parseAdminEmailList)], { error: "must be a list of email addresses or one string of them" })
156
+ .default([]),
132
157
  passwordReset: z
133
158
  .strictObject({
134
159
  /** Delivers reset links. Without it password reset is off: no link, and its pages are not found. */
@@ -19,6 +19,11 @@ export interface AuthGuardOptions {
19
19
  * public pages here). `"/"` here is the home page only. The change-password route stays guarded.
20
20
  */
21
21
  readonly exclude?: readonly string[];
22
+ /**
23
+ * Paths that never need a session, matched whole (`/pricing` and `/pricing/`, not `/pricing/plans`), for an app
24
+ * that protects everything except an exact allowlist. Compared decoded and lowercased, like the other lists.
25
+ */
26
+ readonly excludeExact?: readonly string[];
22
27
  /**
23
28
  * Origins besides `appOrigin` and the config's `origins.trustedOrigins` that the login redirect may stay on
24
29
  * (`https://example.com`). Prefer the config's block, which every module reads. The request's public origin
@@ -26,6 +31,12 @@ export interface AuthGuardOptions {
26
31
  * `appOrigin`.
27
32
  */
28
33
  readonly trustedOrigins?: readonly string[];
34
+ /**
35
+ * `"absolute"` (default): the login URL is built on the resolved origin (above). `"relative"`: the `Location` is
36
+ * the path only (`/login?next=…`), so the browser stays on whatever host and port it used; for a stack served on
37
+ * ports or hosts the config cannot list (an integration run on a random port).
38
+ */
39
+ readonly redirect?: "absolute" | "relative";
29
40
  }
30
41
 
31
42
  /** Mounted at a fixed path by the module (manifest `mount`); it answers `{ user: null }` without a session. */
@@ -44,10 +55,12 @@ export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions
44
55
  normalizePrefix(path, "excluded"),
45
56
  );
46
57
  const excluded = (options.exclude ?? []).map((prefix) => normalizePrefix(prefix, "excluded"));
58
+ const exactExcluded = new Set((options.excludeExact ?? []).map((path) => normalizePrefix(path, "excluded")));
47
59
  const trustedOrigins = (options.trustedOrigins ?? []).map(normalizeOrigin);
48
60
 
49
61
  const isGuarded = (path: string): boolean => {
50
62
  if (isUnder(path, changePassword)) return true;
63
+ if (exactExcluded.has(normalizeTrailingSlash(path))) return false;
51
64
  if ([...publicPaths, ...excluded].some((prefix) => isExcludedBy(path, prefix))) return false;
52
65
  return prefixes.some((prefix) => isUnder(path, prefix));
53
66
  };
@@ -64,7 +77,9 @@ export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions
64
77
  // the request URL carries an internal host, and request headers alone are never trusted.
65
78
  const login = new URL(routes.login, resolveAppOrigin(config, request, { trustedOrigins }));
66
79
  login.searchParams.set("next", `${url.pathname}${url.search}`);
67
- return Response.redirect(login, 307);
80
+ if (options.redirect !== "relative") return Response.redirect(login, 307);
81
+ // A path-only Location reads no request header at all; `Response.redirect` would need an absolute URL.
82
+ return new Response(null, { status: 307, headers: { location: `${login.pathname}${login.search}` } });
68
83
  };
69
84
  }
70
85
 
@@ -72,8 +87,11 @@ function normalizePrefix(prefix: string, kind: "protected" | "excluded"): string
72
87
  if (!prefix.startsWith("/")) {
73
88
  throw new Error(`createAuthGuard: ${kind} path "${prefix}" must start with /`);
74
89
  }
75
- const trimmed = prefix.length > 1 && prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
76
- return trimmed.toLowerCase();
90
+ return normalizeTrailingSlash(prefix).toLowerCase();
91
+ }
92
+
93
+ function normalizeTrailingSlash(path: string): string {
94
+ return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
77
95
  }
78
96
 
79
97
  /** `entry` as an origin (`https://example.com`, a trailing `/` dropped); anything else is a config error. */
@@ -1,43 +1,103 @@
1
- // An account written straight to auth's tables, hashed the way registration hashes it. No
2
- // `onRegistered` hook runs and no session is opened: the test signs in through the login form.
1
+ // An account written straight to auth's tables, hashed the way registration hashes it. No session
2
+ // is opened: the test signs in through the login form. The app's `onRegistered` hook runs only on
3
+ // request (`runHooks`), so fixture rows the app's hooks write (a profile, an entitlement) exist too.
3
4
  import type { Queryable } from "@softure-ai/db";
4
5
  import type { AuthUser } from "../contract.js";
5
6
  import { DEFAULT_SCRYPT_COST, type ScryptParams } from "../options.js";
6
7
  import { userRoles, users } from "../schema.js";
7
- import { hashPassword } from "../server/password.js";
8
+ import { getAuthOptions } from "../server/options.js";
9
+ import { hashPassword, isPasswordHash } from "../server/password.js";
10
+ import type { AuthContext } from "../server/sessions.js";
8
11
  import { parseEmail } from "../server/validation.js";
9
12
 
10
13
  /** Auth's own hash parameters when the app sets none (`password.scrypt` in `auth({ ... })`). */
11
14
  const DEFAULT_SCRYPT: ScryptParams = { cost: DEFAULT_SCRYPT_COST, blockSize: 8, parallelization: 1 };
12
15
 
13
- export interface TestAccountInput {
16
+ /** One hash per password and parameters for the whole test run: scrypt is the slow part of a big suite's setup. */
17
+ const hashCache = new Map<string, Promise<string>>();
18
+
19
+ interface TestAccountBase {
14
20
  readonly email: string;
15
- readonly password: string;
21
+ /** The row's id (a uuid); the database draws one when absent. */
22
+ readonly id?: string;
23
+ /** `created_at` and `password_changed_at`; now when absent. */
24
+ readonly createdAt?: Date;
16
25
  /** Rows of `auth.user_roles`, e.g. `["admin"]`. */
17
26
  readonly roles?: readonly string[];
18
- /** The app's hash parameters (`getAuthOptions(config).password.scrypt`), so its login does not rehash. */
27
+ /** Run the app's `onRegistered` hook in the account's transaction. Needs a module context as the first argument. */
28
+ readonly runHooks?: boolean;
29
+ /** `event.fields` for the hook, as the register form would send the app's `registrationFields`. */
30
+ readonly fields?: Readonly<Record<string, string>>;
31
+ }
32
+
33
+ /** An account with a password, hashed here (once per password and parameters). */
34
+ export interface TestAccountInput extends TestAccountBase {
35
+ readonly password: string;
36
+ /** Hash parameters; the app's (`getAuthOptions(config).password.scrypt`) when a module context is given, else auth's default. */
19
37
  readonly scrypt?: ScryptParams;
38
+ readonly passwordHash?: never;
39
+ }
40
+
41
+ /** An account with a ready hash, stored as is. */
42
+ export interface TestAccountHashInput extends TestAccountBase {
43
+ /** A ready hash from `hashPassword`, stored as is: nothing is hashed. */
44
+ readonly passwordHash: string;
45
+ readonly password?: never;
46
+ readonly scrypt?: never;
20
47
  }
21
48
 
22
49
  /**
23
50
  * Creates an account and its roles in one transaction and returns it. The email is normalized as
24
- * registration normalizes it. An invalid or taken email throws: in test setup it is a bug of the test.
51
+ * registration normalizes it. An invalid or taken email, a malformed `passwordHash` or a hook that
52
+ * throws rolls everything back and throws: in test setup it is a bug of the test.
25
53
  */
26
- export async function createTestAccount(db: Queryable, input: TestAccountInput): Promise<AuthUser> {
54
+ export async function createTestAccount(target: Queryable | AuthContext, input: TestAccountInput | TestAccountHashInput): Promise<AuthUser> {
55
+ const ctx = isModuleContext(target) ? target : null;
56
+ const db = isModuleContext(target) ? target.db : target;
27
57
  const email = parseEmail(input.email);
28
58
  if (!email.ok) throw new Error(`createTestAccount: "${input.email}" is not a valid email`);
29
- const passwordHash = await hashPassword(input.password, input.scrypt ?? DEFAULT_SCRYPT);
30
- const now = new Date();
59
+ if (input.runHooks === true && ctx === null) {
60
+ throw new Error("createTestAccount: runHooks needs a module context ({ db, clock, config }) instead of a database");
61
+ }
62
+ const passwordHash = await readPasswordHash(input, email.value, ctx);
63
+ const now = input.createdAt ?? new Date();
31
64
 
32
65
  return db.transaction(async (tx) => {
33
66
  const [row] = await tx
34
67
  .insert(users)
35
- .values({ email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
68
+ .values({ ...(input.id === undefined ? {} : { id: input.id }), email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
36
69
  .onConflictDoNothing({ target: users.email })
37
70
  .returning();
38
71
  if (row === undefined) throw new Error(`createTestAccount: an account with the email "${email.value}" already exists`);
39
72
  const roles = input.roles ?? [];
40
73
  if (roles.length > 0) await tx.insert(userRoles).values(roles.map((role) => ({ userId: row.id, role, grantedAt: now })));
41
- return { id: row.id, email: row.email, createdAt: row.createdAt };
74
+ const user = { id: row.id, email: row.email, createdAt: row.createdAt };
75
+ if (input.runHooks === true && ctx !== null) {
76
+ const options = getAuthOptions(ctx.config);
77
+ const consent = options.requireConsent ? { acceptedAt: now } : null;
78
+ await options.onRegistered?.({ user, consent, fields: input.fields ?? {} }, { ...ctx, db: tx });
79
+ }
80
+ return user;
42
81
  });
43
82
  }
83
+
84
+ async function readPasswordHash(input: TestAccountInput | TestAccountHashInput, email: string, ctx: AuthContext | null): Promise<string> {
85
+ if (input.passwordHash !== undefined) {
86
+ if (!isPasswordHash(input.passwordHash)) throw new Error(`createTestAccount: the passwordHash for "${email}" is not a hash from hashPassword`);
87
+ return input.passwordHash;
88
+ }
89
+ const scrypt = input.scrypt ?? (ctx === null ? DEFAULT_SCRYPT : getAuthOptions(ctx.config).password.scrypt);
90
+ const key = JSON.stringify([scrypt.cost, scrypt.blockSize, scrypt.parallelization, input.password]);
91
+ let hash = hashCache.get(key);
92
+ if (hash === undefined) {
93
+ hash = hashPassword(input.password, scrypt);
94
+ hashCache.set(key, hash);
95
+ // A failed hash is not kept, so the next call tries again.
96
+ void hash.catch(() => hashCache.delete(key));
97
+ }
98
+ return hash;
99
+ }
100
+
101
+ function isModuleContext(target: Queryable | AuthContext): target is AuthContext {
102
+ return "config" in target && "clock" in target && "db" in target;
103
+ }
@@ -1,3 +1,3 @@
1
1
  // Test helpers of @softure-ai/auth: accounts created directly in the database, for tests that need
2
2
  // a user but are not about registration. Server-only; never imported by the module's runtime code.
3
- export { createTestAccount, type TestAccountInput } from "./account.js";
3
+ export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";