@jskit-ai/auth-provider-local-core 0.2.10 → 0.2.11

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
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - The first account of a production server needs a one-time setup code. While local auth has no account, each start of a production server makes a new code, writes it in the log (a warning with `firstAccountSetupCode` and `firstAccountSetupCodeFile`) and in `first-account-setup-code` in `AUTH_LOCAL_STORE_DIR` (mode 600), and keeps only its hash; registering without it is refused with 403 `auth.local.setup.codeRequired`, with a wrong one with 403 `auth.local.setup.codeInvalid`, and an OAuth sign-in cannot create that account. Once an account exists the code stops working and its file is deleted. Development needs no code, and servers that already have accounts are unchanged. `getCapabilities()` says `features.firstAccountSetupCode` while it waits. `AuthLocalProvider` checks for an account as it starts, and `createLocalAuthService()` takes the started `firstAccountSetup` (by default it checks on first use). New exports `createFirstAccountSetup` and `SETUP_CODE_FILE`; new message keys `jskit.auth.local.setup.codeRequired` and `jskit.auth.local.setup.codeInvalid`.
6
+ - Upgrading: a custom `auth.local.backend` implements `users.hasAny()`.
7
+ - A hosting tool may supply the first account's setup code in `AUTH_LOCAL_SETUP_CODE` (production only; at least 20 letters and digits, or startup stops naming the variable) and show it to the operator itself. The server then asks for that code at every start and on every server, writes no `first-account-setup-code` file (it deletes one left behind), and logs only that the code is in `AUTH_LOCAL_SETUP_CODE` (`firstAccountSetupCodeEnv`), never the code. New export `SETUP_CODE_ENV`. The refusal and sign-in texts name the server's log or its hosting service.
8
+ - Registration confirms the email address, on by default in every environment; `AUTH_LOCAL_EMAIL_CONFIRMATION=false` turns it off. Registering keeps the registration waiting, with no account, profile or session, and answers `requiresEmailConfirmation: true`; the link's code is random, kept only as a hash, works once, expires after a day and is replaced by registering again or `resendRegisterConfirmation`. `confirmRegistration({ token })` creates the account and signs the person in, and the register hook runs then. Signing in with the right password while the registration waits is refused with 403 `auth.login.emailUnconfirmed`. The optional `auth.local.confirmation-sender` (`({ email, confirmationUrl }) => Promise<void>`, which needs `APP_PUBLIC_URL`) emails the link; in development without one, the link is in the answer's `confirmationUrl` and the log; in production without one, startup stops, naming both ways out. Existing accounts are confirmed. New message keys: `jskit.auth.local.register.confirmationInvalid` and `jskit.auth.local.register.confirmationResent`.
9
+ - Upgrading: a production app installs an `auth.local.confirmation-sender` or sets `AUTH_LOCAL_EMAIL_CONFIRMATION=false`. Tests that register and expect a session confirm with `confirmationUrl` or set `AUTH_LOCAL_EMAIL_CONFIRMATION=false`. A custom `auth.local.backend` implements the `registrations` collection (`save`, `findByEmail`, `findByTokenHash`, `delete`, `deleteExpired`); the file backend keeps it in `registrations.passwd`, and `@jskit-ai/auth-provider-local-db-core` in the table `auth_local_registrations`, created by its migration `auth_local_db_protection` (run `npm run db:migrate`). `resolveLocalAuthConfig()` takes `emailConfirmationSender`, and `createLocalAuthService()` requires `confirmationSender`: the installed sender, or `createLoggedConfirmationSender(logger)` when there is none.
10
+ - A production server (`NODE_ENV=production`) with `AUTH_LOCAL_RECOVERY_DEV_OUTPUT` set refuses to start and names the setting to remove, instead of quietly ignoring it; production recovery stays email only. Upgrading: remove `AUTH_LOCAL_RECOVERY_DEV_OUTPUT` from production environments.
11
+ - Failed sign-ins slow down the account they name, existing or not: after `AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT` (5) failures in a row the email waits `AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS` (30) before its next attempt, and each further failure doubles the wait up to `AUTH_LOCAL_SIGN_IN_MAX_WAIT_SECONDS` (3600). While it waits, sign-in is refused, even with the right password, with status 429, the code `auth.local.login.locked` (`params.count` minutes, `params.retryAfterSeconds`) and `Retry-After`. A successful sign-in or a completed password reset forgets the failures, and so does a day without one, so a wait is never permanent and recovery always lets the owner back in.
12
+ - `AUTH_LOCAL_PASSWORD_MIN_LENGTH` (default 8, from 8 to 64) sets the shortest password accepted on registration, reset and change.
13
+ - Upgrading: a custom `auth.local.backend` implements the new `signInFailures` collection (`find`, `save`, `clear`, `deleteBefore`); the file backend keeps it in `sign-in-failures.passwd`, and `@jskit-ai/auth-provider-local-db-core` in the table `auth_local_sign_in_failures`, which its migration `auth_local_db_protection` creates (run `npm run db:migrate`). `validatePasswordInput(password, minLength)` takes the minimum length.
14
+ - New message key: `jskit.auth.local.login.locked`.
15
+
3
16
  ## 0.2.0 - 2026-10-29
4
17
 
5
18
  - Translation ready: every user-visible text is a message key with its English in `locales/en.json`, so an app translates it by supplying translation files only. With no translations, texts and behaviour are unchanged. See the guide "Translating a JSKIT app".
package/locales/en.json CHANGED
@@ -11,7 +11,16 @@
11
11
  "changed": "Password updated."
12
12
  },
13
13
  "register": {
14
- "emailTaken": "An account already exists for this email."
14
+ "emailTaken": "An account already exists for this email.",
15
+ "confirmationInvalid": "This confirmation link is invalid or has expired. Register again to get a new one.",
16
+ "confirmationResent": "If a registration is waiting for that email, a new confirmation link has been sent."
17
+ },
18
+ "setup": {
19
+ "codeRequired": "This app has no account yet. Its first account needs the setup code from the server's log or its hosting service.",
20
+ "codeInvalid": "That is not this app's setup code. Copy it again from the server's log or its hosting service."
21
+ },
22
+ "login": {
23
+ "locked": "Too many failed sign-ins for this account. Try again in {count} minute. | Too many failed sign-ins for this account. Try again in {count} minutes."
15
24
  },
16
25
  "recovery": {
17
26
  "notConfigured": "Password recovery is not configured.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -48,11 +48,11 @@
48
48
  },
49
49
  {
50
50
  "subpath": "./server/lib/index",
51
- "summary": "Exports the local auth service and its configuration (createLocalAuthService, resolveLocalAuthConfig), the file backend, the password strategy helpers (scryptPasswordStrategy, normalizePasswordStrategy, hashPassword, verifyPassword), the logged recovery sender (createLoggedRecoverySender), and local auth register hook decorators. Google, Microsoft and GitHub sign-in turn on from AUTH_GOOGLE_*, AUTH_MICROSOFT_* and AUTH_GITHUB_* client id and secret pairs."
51
+ "summary": "Exports the local auth service and its configuration (createLocalAuthService, resolveLocalAuthConfig), the file backend, the password strategy helpers (scryptPasswordStrategy, normalizePasswordStrategy, hashPassword, verifyPassword), the logged recovery and confirmation senders (createLoggedRecoverySender, createLoggedConfirmationSender), the first account's setup code (createFirstAccountSetup, SETUP_CODE_FILE, SETUP_CODE_ENV), and local auth register hook decorators. Google, Microsoft and GitHub sign-in turn on from AUTH_GOOGLE_*, AUTH_MICROSOFT_* and AUTH_GITHUB_* client id and secret pairs."
52
52
  },
53
53
  {
54
54
  "subpath": "./server/types",
55
- "summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy and auth.local.recovery-sender capabilities, and of the configuration, passwords and sessions local auth's modules share."
55
+ "summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy, auth.local.recovery-sender and auth.local.confirmation-sender capabilities, and of the configuration, passwords and sessions local auth's modules share."
56
56
  }
57
57
  ],
58
58
  "extensionCapabilities": [
@@ -60,13 +60,14 @@
60
60
  "auth.local.backend",
61
61
  "auth.local.password-strategy",
62
62
  "auth.profile.projector",
63
- "auth.local.recovery-sender"
63
+ "auth.local.recovery-sender",
64
+ "auth.local.confirmation-sender"
64
65
  ]
65
66
  }
66
67
  }
67
68
  },
68
69
  "peerDependencies": {
69
- "@jskit-ai/auth-core": "0.2.8",
70
- "@jskit-ai/kernel": "0.2.8"
70
+ "@jskit-ai/auth-core": "0.2.9",
71
+ "@jskit-ai/kernel": "0.2.9"
71
72
  }
72
73
  }
@@ -1,12 +1,10 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
- import {
3
- AUTH_PASSWORD_MAX_LENGTH,
4
- AUTH_PASSWORD_MIN_LENGTH
5
- } from "@jskit-ai/auth-core/shared/authConstraints";
2
+ import { AUTH_PASSWORD_MAX_LENGTH } from "@jskit-ai/auth-core/shared/authConstraints";
6
3
  import { ensureDevAuthExchangeAvailable, isDevAuthBootstrapEnabled } from "@jskit-ai/auth-core/server/devAuth";
7
4
  import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
8
5
  import { AUTH_TEXTS, authFieldErrorDetails, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
9
6
  import { DEV_AUTH_SESSION_PURPOSE, buildAuthPayload, buildAuthResult, findExistingAppProfile } from "./authPayloads.js";
7
+ import { forgottenFailuresBefore, recordSignInFailure, signInLockedError, signInWaitMs } from "./signInThrottle.js";
10
8
  import { createId } from "./tokens.js";
11
9
 
12
10
  /** An account created through a provider has no password until recovery sets one. */
@@ -29,19 +27,23 @@ function hasPassword(user) {
29
27
  return record && typeof record === "object" ? Boolean(record.hash) : Boolean(record);
30
28
  }
31
29
 
32
- function validatePasswordInput(password) {
30
+ /**
31
+ * Refuses a password shorter than `minLength` (the configured
32
+ * AUTH_LOCAL_PASSWORD_MIN_LENGTH) or longer than local auth stores.
33
+ * @param {unknown} password
34
+ * @param {number} minLength
35
+ */
36
+ function validatePasswordInput(password, minLength) {
33
37
  const normalizedPassword = String(password || "");
34
- if (
35
- normalizedPassword.length < AUTH_PASSWORD_MIN_LENGTH ||
36
- normalizedPassword.length > AUTH_PASSWORD_MAX_LENGTH
37
- ) {
38
- const params = { min: AUTH_PASSWORD_MIN_LENGTH };
39
- throw new AppError(400, "Password must be at least 8 characters.", {
38
+ if (normalizedPassword.length < minLength || normalizedPassword.length > AUTH_PASSWORD_MAX_LENGTH) {
39
+ const params = { min: minLength };
40
+ const message = `Password must be at least ${minLength} characters.`;
41
+ throw new AppError(400, message, {
40
42
  code: "auth.local.password.tooShort",
41
43
  params,
42
44
  details: {
43
45
  fieldErrors: {
44
- password: "Password must be at least 8 characters."
46
+ password: message
45
47
  },
46
48
  fieldErrorCodes: {
47
49
  password: { code: "auth.local.password.tooShort", params }
@@ -99,40 +101,63 @@ function normalizeInvitationInput(value) {
99
101
  }
100
102
 
101
103
  /**
102
- * The accounts of local auth: registering one, signing in with its password
103
- * or as a dev user, and renaming it.
104
+ * The profile options an invitation gives a new account: none without one.
105
+ * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} invitationContextResolver
106
+ * @param {unknown} invitationInput
107
+ * @param {string} email
108
+ */
109
+ async function resolveRegistrationProfileOptions(invitationContextResolver, invitationInput, email) {
110
+ const invitation = normalizeInvitationInput(invitationInput);
111
+ if (!invitation) {
112
+ return {};
113
+ }
114
+ const resolvedInvitation = await invitationContextResolver.resolveInvitationContext({ ...invitation, email });
115
+ return {
116
+ source: resolvedInvitation?.source || "workspace-invite",
117
+ invitation: resolvedInvitation
118
+ };
119
+ }
120
+
121
+ /**
122
+ * The accounts of local auth: registering one (which waits for its email to
123
+ * be confirmed while config.emailConfirmation is on), signing in with its
124
+ * password (failures slow the account down, as config.signInThrottle says) or
125
+ * as a dev user, and renaming it.
104
126
  * @param {object} dependencies
105
127
  * @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
106
128
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
107
129
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
130
+ * @param {ReturnType<typeof import("./emailConfirmation.js").createLocalEmailConfirmation>} dependencies.emailConfirmation
131
+ * @param {import("../types.js").AuthLocalFirstAccountSetup} dependencies.firstAccountSetup
108
132
  * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
109
133
  * @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
110
134
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
111
135
  * @param {import("../types.js").AuthLocalSessions} dependencies.sessions
112
136
  */
113
- function createLocalAccounts({ appProfileProjection, backend, config, invitationContextResolver, passwords, profileProjector, sessions }) {
137
+ function createLocalAccounts({
138
+ appProfileProjection,
139
+ backend,
140
+ config,
141
+ emailConfirmation,
142
+ firstAccountSetup,
143
+ invitationContextResolver,
144
+ passwords,
145
+ profileProjector,
146
+ sessions
147
+ }) {
114
148
  const { devAuth } = config;
115
149
 
116
- async function resolveProfileOptionsForRegistration(input, email) {
117
- const invitation = normalizeInvitationInput(input.invitation);
118
- if (!invitation) {
119
- return {};
120
- }
121
-
122
- const resolvedInvitation = await invitationContextResolver.resolveInvitationContext({ ...invitation, email });
123
-
124
- return {
125
- source: resolvedInvitation?.source || "workspace-invite",
126
- invitation: resolvedInvitation
127
- };
128
- }
129
-
130
150
  async function register(input) {
131
151
  const email = validateEmailInput(input.email);
132
- validatePasswordInput(input.password);
152
+ validatePasswordInput(input.password, config.passwordMinLength);
133
153
  const displayName = normalizeDisplayName(input.displayName, email);
134
- const profileOptions = await resolveProfileOptionsForRegistration(input, email);
154
+ await firstAccountSetup.admitRegistration(input.setupCode);
155
+ // Checked now, so a registration with an invitation it cannot use is refused at once.
156
+ const profileOptions = await resolveRegistrationProfileOptions(invitationContextResolver, input.invitation, email);
135
157
  const password = await passwords.hashPassword(input.password);
158
+ if (config.emailConfirmation) {
159
+ return emailConfirmation.begin({ email, displayName, password, invitation: normalizeInvitationInput(input.invitation) });
160
+ }
136
161
  const result = await backend.withTransaction(async (tx) => {
137
162
  const existing = await tx.users.findByEmail(email);
138
163
  if (existing) {
@@ -149,6 +174,7 @@ function createLocalAccounts({ appProfileProjection, backend, config, invitation
149
174
  session: await sessions.createSessionForUser(tx, user)
150
175
  };
151
176
  });
177
+ firstAccountSetup.accountCreated();
152
178
  return {
153
179
  ...(await buildAuthPayload({
154
180
  user: result.user,
@@ -160,17 +186,50 @@ function createLocalAccounts({ appProfileProjection, backend, config, invitation
160
186
  };
161
187
  }
162
188
 
189
+ /**
190
+ * Signs in with a password. Each account's failures are counted, whether or
191
+ * not the account exists, so the wait they cause says nothing about which
192
+ * accounts exist; while an account waits its password is not checked. A
193
+ * successful sign-in, or a password reset, forgets the failures.
194
+ */
163
195
  async function login(input) {
164
196
  const email = validateEmailInput(input.email);
165
197
  const password = String(input.password || "");
166
- return backend.withTransaction(async (tx) => {
198
+ const outcome = await backend.withTransaction(async (tx) => {
199
+ const now = Date.now();
200
+ const failures = await tx.signInFailures.find(email);
201
+ const waitMs = signInWaitMs(failures, now);
202
+ if (waitMs > 0) {
203
+ return { waitMs };
204
+ }
167
205
  const user = await tx.users.findByEmail(email);
206
+ if (!user && config.emailConfirmation &&
207
+ (await emailConfirmation.isWaitingWithPassword(tx, email, (registration) =>
208
+ passwords.verifyPassword(password, registration.password)))) {
209
+ return { unconfirmed: true };
210
+ }
168
211
  if (!user || user.disabled || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
169
- throw createAuthError(AUTH_TEXTS.invalidCredentials);
212
+ await tx.signInFailures.deleteBefore(forgottenFailuresBefore(now));
213
+ await tx.signInFailures.save(recordSignInFailure(config.signInThrottle, failures, email, now));
214
+ return { failed: true };
215
+ }
216
+ if (failures) {
217
+ await tx.signInFailures.clear(email);
170
218
  }
171
219
  const session = await sessions.createSessionForUser(tx, user);
172
- return buildAuthPayload({ user, session, profileProjector });
220
+ return { payload: await buildAuthPayload({ user, session, profileProjector }) };
173
221
  });
222
+ // Refused after the transaction, so the failure it records is kept.
223
+ if (outcome.waitMs) {
224
+ throw signInLockedError(outcome.waitMs);
225
+ }
226
+ if (outcome.failed) {
227
+ throw createAuthError(AUTH_TEXTS.invalidCredentials);
228
+ }
229
+ if (outcome.unconfirmed) {
230
+ throw createAuthError(AUTH_TEXTS.emailUnconfirmed);
231
+ }
232
+ return outcome.payload;
174
233
  }
175
234
 
176
235
  function devAuthBootstrapEnabled() {
@@ -239,6 +298,7 @@ export {
239
298
  createLocalAccounts,
240
299
  hasPassword,
241
300
  normalizeDisplayName,
301
+ resolveRegistrationProfileOptions,
242
302
  validateEmailInput,
243
303
  validatePasswordInput
244
304
  };
@@ -3,7 +3,12 @@ import { assertDevAuthPolicy, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth
3
3
  import { randomBytes } from "node:crypto";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
+ import { AUTH_PASSWORD_MIN_LENGTH } from "@jskit-ai/auth-core/shared/authConstraints";
7
+ import { parsePositiveInteger } from "@jskit-ai/kernel/server/runtime";
8
+ import { assertDevelopmentOnlySettings } from "@jskit-ai/kernel/server/runtime/runtimeMode";
9
+ import { SETUP_CODE_ENV, SETUP_CODE_MIN_CHARACTERS, normalizedSetupCode } from "./firstAccountSetup.js";
6
10
  import { resolveOAuthProviders } from "./oauth.js";
11
+ import { resolveSignInThrottle } from "./signInThrottle.js";
7
12
 
8
13
  const DEFAULT_STORE_DIR = ".jskit/auth";
9
14
 
@@ -41,15 +46,34 @@ function resolveSessionSecret(env, { storeDir, isProduction }) {
41
46
  }
42
47
 
43
48
  /**
44
- * APP_PUBLIC_URL, from which recovery links and OAuth redirect addresses are
45
- * built. Email recovery and OAuth sign-in require it.
49
+ * AUTH_LOCAL_SETUP_CODE: the first account's setup code when a hosting tool
50
+ * supplies it, so that every start and every server asks for the same code.
51
+ * Only production asks for a setup code; elsewhere the variable is ignored.
46
52
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
47
- * @param {{ emailRecovery: boolean, oauthEnabled: boolean }} options
53
+ * @param {{ isProduction: boolean }} options
48
54
  */
49
- function resolveAppPublicUrl(env, { emailRecovery, oauthEnabled }) {
55
+ function resolveSetupCode(env, { isProduction }) {
56
+ const code = String(env[SETUP_CODE_ENV] || "").trim();
57
+ if (!isProduction || !code) return "";
58
+ if (normalizedSetupCode(code).length < SETUP_CODE_MIN_CHARACTERS) {
59
+ throw new Error(`${SETUP_CODE_ENV} must have at least ${SETUP_CODE_MIN_CHARACTERS} letters and digits.`);
60
+ }
61
+ return code;
62
+ }
63
+
64
+ /**
65
+ * APP_PUBLIC_URL, from which recovery and confirmation links and OAuth
66
+ * redirect addresses are built. Emailed links and OAuth sign-in require it.
67
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
68
+ * @param {{ emailRecovery: boolean, emailedConfirmation: boolean, oauthEnabled: boolean }} options
69
+ */
70
+ function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEnabled }) {
50
71
  const configured = String(env.APP_PUBLIC_URL || "").trim();
51
72
  if (!configured) {
52
73
  if (emailRecovery) throw new Error("APP_PUBLIC_URL is required when local auth email recovery is configured.");
74
+ if (emailedConfirmation) {
75
+ throw new Error("APP_PUBLIC_URL is required when local auth emails confirmation links.");
76
+ }
53
77
  if (oauthEnabled) throw new Error("APP_PUBLIC_URL is required when local auth OAuth sign-in is configured.");
54
78
  return "http://localhost:5173";
55
79
  }
@@ -69,7 +93,8 @@ function resolveAppPublicUrl(env, { emailRecovery, oauthEnabled }) {
69
93
  * How a password recovery link reaches the person: by email through the
70
94
  * installed recovery sender; otherwise, outside production, in the log or in
71
95
  * the response (AUTH_LOCAL_RECOVERY_DEV_OUTPUT=response). In production without
72
- * a sender, recovery is disabled.
96
+ * a sender, recovery is disabled, and AUTH_LOCAL_RECOVERY_DEV_OUTPUT stops
97
+ * startup (resolveLocalAuthConfig).
73
98
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
74
99
  * @param {{ emailRecovery: boolean, isProduction: boolean }} options
75
100
  * @returns {"email" | "disabled" | "dev-response" | "dev-log"}
@@ -81,6 +106,45 @@ function resolveRecoveryDelivery(env, { emailRecovery, isProduction }) {
81
106
  return devOutput === "response" ? "dev-response" : "dev-log";
82
107
  }
83
108
 
109
+ /**
110
+ * Whether a registration waits for its email to be confirmed
111
+ * (AUTH_LOCAL_EMAIL_CONFIRMATION, on unless set to false), and how its link
112
+ * reaches the person: by email through the installed confirmation sender, or,
113
+ * in development without one, in the registration's response (the sign-in
114
+ * screen shows it) and the log. Production without a sender stops startup,
115
+ * because nobody could confirm.
116
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
117
+ * @param {{ emailConfirmationSender: boolean, isProduction: boolean }} options
118
+ * @returns {"email" | "dev-response" | "off"}
119
+ */
120
+ function resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction }) {
121
+ if (!parseBooleanFlag(env.AUTH_LOCAL_EMAIL_CONFIRMATION, true)) return "off";
122
+ if (emailConfirmationSender) return "email";
123
+ if (isProduction) {
124
+ throw new Error(
125
+ "Local auth confirms each new account's email address in production, and no auth.local.confirmation-sender " +
126
+ "is installed to email the confirmation links. Install one, or set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
127
+ "to let accounts register without confirming their email."
128
+ );
129
+ }
130
+ return "dev-response";
131
+ }
132
+
133
+ /**
134
+ * The shortest password local auth accepts: AUTH_LOCAL_PASSWORD_MIN_LENGTH, or 8.
135
+ * It can be raised, up to 64, but not lowered below 8.
136
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
137
+ */
138
+ function resolvePasswordMinLength(env) {
139
+ const raw = String(env.AUTH_LOCAL_PASSWORD_MIN_LENGTH ?? "").trim();
140
+ if (!raw) return AUTH_PASSWORD_MIN_LENGTH;
141
+ const value = parsePositiveInteger(raw);
142
+ if (value === null || value < AUTH_PASSWORD_MIN_LENGTH || value > 64) {
143
+ throw new Error(`AUTH_LOCAL_PASSWORD_MIN_LENGTH must be a whole number from ${AUTH_PASSWORD_MIN_LENGTH} to 64.`);
144
+ }
145
+ return value;
146
+ }
147
+
84
148
  /**
85
149
  * The local auth configuration, resolved and checked once from the environment.
86
150
  * Production is worked out once, by auth-core's dev auth policy, so local auth
@@ -91,8 +155,9 @@ function resolveRecoveryDelivery(env, { emailRecovery, isProduction }) {
91
155
  * @param {boolean} input.fileBackend True when local auth keeps its records in files, because no
92
156
  * `auth.local.backend` is installed.
93
157
  * @param {boolean} input.emailRecovery True when an `auth.local.recovery-sender` is installed.
158
+ * @param {boolean} [input.emailConfirmationSender] True when an `auth.local.confirmation-sender` is installed.
94
159
  */
95
- function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery }) {
160
+ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender = false }) {
96
161
  const devAuth = resolveDevAuthPolicyFromEnv(env);
97
162
  const { isProduction } = devAuth;
98
163
  const storeDir = resolveStoreDir(env, appRoot);
@@ -100,18 +165,29 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery }) {
100
165
  throw new Error("AUTH_LOCAL_FILE_PRODUCTION_ACK is required to use the local file auth backend in production.");
101
166
  }
102
167
  assertDevAuthPolicy(devAuth);
168
+ assertDevelopmentOnlySettings(env, ["AUTH_LOCAL_RECOVERY_DEV_OUTPUT"]);
103
169
  const oauthProviders = resolveOAuthProviders(env);
104
170
  const oauthEnabled = oauthProviders.length > 0;
105
171
  const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery, isProduction });
172
+ const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction });
106
173
  return Object.freeze({
107
174
  storeDir,
108
175
  isProduction,
109
- appPublicUrl: resolveAppPublicUrl(env, { emailRecovery, oauthEnabled }),
176
+ appPublicUrl: resolveAppPublicUrl(env, {
177
+ emailRecovery,
178
+ emailedConfirmation: confirmationDelivery === "email",
179
+ oauthEnabled
180
+ }),
110
181
  oauthProviders,
111
182
  oauthEnabled,
112
183
  sessionSecret: resolveSessionSecret(env, { storeDir, isProduction }),
184
+ setupCode: resolveSetupCode(env, { isProduction }),
113
185
  recoveryDelivery,
114
186
  recoveryEnabled: recoveryDelivery !== "disabled",
187
+ confirmationDelivery,
188
+ emailConfirmation: confirmationDelivery !== "off",
189
+ passwordMinLength: resolvePasswordMinLength(env),
190
+ signInThrottle: resolveSignInThrottle(env),
115
191
  devAuth
116
192
  });
117
193
  }
@@ -0,0 +1,188 @@
1
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { resolveRegistrationProfileOptions, validateEmailInput } from "./accounts.js";
3
+ import { buildAuthPayload } from "./authPayloads.js";
4
+ import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url } from "./tokens.js";
5
+
6
+ const CONFIRMATION_TOKEN_TTL_SECONDS = 24 * 60 * 60;
7
+
8
+ /**
9
+ * The confirmation sender while no `auth.local.confirmation-sender` is
10
+ * installed: it logs each link, which development also shows on the sign-in screen.
11
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
12
+ * @returns {import("../types.js").AuthLocalConfirmationSender}
13
+ */
14
+ function createLoggedConfirmationSender(logger) {
15
+ return async function logConfirmationLink({ email, confirmationUrl }) {
16
+ logger.info({ email, confirmationUrl }, "Local auth email confirmation URL created.");
17
+ };
18
+ }
19
+
20
+ function emailTakenError() {
21
+ return new AppError(409, "An account already exists for this email.", { code: "auth.local.register.emailTaken" });
22
+ }
23
+
24
+ function confirmationInvalidError() {
25
+ return new AppError(400, "This confirmation link is invalid or has expired. Register again to get a new one.", {
26
+ code: "auth.local.register.confirmationInvalid"
27
+ });
28
+ }
29
+
30
+ /**
31
+ * Registration with email confirmation: registering keeps the account waiting,
32
+ * with no account, profile or session, until the link sent to its email is
33
+ * opened, which creates the account and signs the person in. The link's code is stored only as a hash, works once and expires
34
+ * after a day; registering again or asking for a new link replaces it.
35
+ * @param {object} dependencies
36
+ * @param {import("../types.js").AuthLocalBackend} dependencies.backend
37
+ * @param {import("../types.js").AuthLocalConfig} dependencies.config
38
+ * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
39
+ * @param {import("../types.js").AuthLocalFirstAccountSetup} dependencies.firstAccountSetup
40
+ * @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
41
+ * `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender;
42
+ * in development without a sender, links also go in the response.
43
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
44
+ * @param {import("../types.js").AuthLocalSessions} dependencies.sessions
45
+ */
46
+ function createLocalEmailConfirmation({
47
+ backend,
48
+ config,
49
+ confirmationSender,
50
+ firstAccountSetup,
51
+ invitationContextResolver,
52
+ profileProjector,
53
+ sessions
54
+ }) {
55
+ const { confirmationDelivery } = config;
56
+
57
+ function newConfirmation() {
58
+ const token = randomToken(32);
59
+ return {
60
+ token,
61
+ tokenHash: sha256Base64url(token),
62
+ expiresAt: isoFromNow(CONFIRMATION_TOKEN_TTL_SECONDS)
63
+ };
64
+ }
65
+
66
+ // Development without a sender also shows the link, so it can be opened
67
+ // without an email.
68
+ async function deliver(email, token) {
69
+ const confirmationUrl = `${config.appPublicUrl}/auth/login?confirmation_token=${encodeURIComponent(token)}`;
70
+ await confirmationSender({ email, confirmationUrl });
71
+ return confirmationDelivery === "dev-response" ? { confirmationUrl } : {};
72
+ }
73
+
74
+ /**
75
+ * Keeps a registration, already validated and with its password hashed,
76
+ * until its email is confirmed.
77
+ * @param {{ email: string, displayName: string, password: object, invitation: object | null }} registration
78
+ */
79
+ async function begin({ email, displayName, password, invitation }) {
80
+ const { token, tokenHash, expiresAt } = newConfirmation();
81
+ await backend.withTransaction(async (tx) => {
82
+ if (await tx.users.findByEmail(email)) {
83
+ throw emailTakenError();
84
+ }
85
+ const now = new Date().toISOString();
86
+ await tx.registrations.deleteExpired(now);
87
+ await tx.registrations.save({ email, displayName, password, invitation, tokenHash, createdAt: now, expiresAt });
88
+ });
89
+ return {
90
+ actor: null,
91
+ session: null,
92
+ requiresEmailConfirmation: true,
93
+ email,
94
+ ...(await deliver(email, token))
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Creates the account a registration was waiting to create, from its link's
100
+ * code, and signs the person in.
101
+ * @param {{ token: string }} input
102
+ */
103
+ async function confirm(input) {
104
+ const tokenHash = sha256Base64url(String(input.token || "").trim());
105
+ const waiting = await backend.withTransaction((tx) => tx.registrations.findByTokenHash(tokenHash));
106
+ if (!waiting || isExpiredIso(waiting.expiresAt)) {
107
+ throw confirmationInvalidError();
108
+ }
109
+ const profileOptions = await resolveRegistrationProfileOptions(
110
+ invitationContextResolver,
111
+ waiting.invitation,
112
+ waiting.email
113
+ );
114
+ const outcome = await backend.withTransaction(async (tx) => {
115
+ const registration = await tx.registrations.findByTokenHash(tokenHash);
116
+ if (!registration || isExpiredIso(registration.expiresAt)) {
117
+ return { invalid: true };
118
+ }
119
+ await tx.registrations.delete(registration.email);
120
+ if (await tx.users.findByEmail(registration.email)) {
121
+ return { taken: true };
122
+ }
123
+ const user = await tx.users.create({
124
+ id: createId("usr"),
125
+ email: registration.email,
126
+ displayName: registration.displayName,
127
+ password: registration.password
128
+ });
129
+ return { user, session: await sessions.createSessionForUser(tx, user) };
130
+ });
131
+ // Refused after the transaction, so a used-up registration stays deleted.
132
+ if (outcome.invalid) {
133
+ throw confirmationInvalidError();
134
+ }
135
+ if (outcome.taken) {
136
+ throw emailTakenError();
137
+ }
138
+ firstAccountSetup.accountCreated();
139
+ return buildAuthPayload({ user: outcome.user, session: outcome.session, profileProjector, profileOptions });
140
+ }
141
+
142
+ /**
143
+ * Sends a waiting registration a new link, which replaces the old one. The
144
+ * answer is the same whether or not a registration waits for that email.
145
+ * @param {{ email: string }} input
146
+ */
147
+ async function resend(input) {
148
+ const email = validateEmailInput(input.email);
149
+ const { token, tokenHash, expiresAt } = newConfirmation();
150
+ const renewed = await backend.withTransaction(async (tx) => {
151
+ const registration = await tx.registrations.findByEmail(email);
152
+ if (!registration) {
153
+ return false;
154
+ }
155
+ await tx.registrations.save({ ...registration, tokenHash, expiresAt });
156
+ return true;
157
+ });
158
+ return {
159
+ ok: true,
160
+ message: "If a registration is waiting for that email, a new confirmation link has been sent.",
161
+ messageCode: "auth.local.register.confirmationResent",
162
+ messageParams: {},
163
+ ...(renewed ? await deliver(email, token) : {})
164
+ };
165
+ }
166
+
167
+ /**
168
+ * True when a registration still waits for this email and the password is
169
+ * the one it chose, so the sign-in is refused as unconfirmed; a wrong
170
+ * password stays an ordinary failed sign-in.
171
+ * @param {import("../types.js").AuthLocalBackendTransaction} tx
172
+ * @param {string} email
173
+ * @param {(registration: import("../types.js").AuthLocalRegistration) => Promise<boolean>} passwordMatches
174
+ */
175
+ async function isWaitingWithPassword(tx, email, passwordMatches) {
176
+ const registration = await tx.registrations.findByEmail(email);
177
+ return Boolean(registration && !isExpiredIso(registration.expiresAt) && (await passwordMatches(registration)));
178
+ }
179
+
180
+ return Object.freeze({
181
+ begin,
182
+ confirm,
183
+ resend,
184
+ isWaitingWithPassword
185
+ });
186
+ }
187
+
188
+ export { CONFIRMATION_TOKEN_TTL_SECONDS, createLocalEmailConfirmation, createLoggedConfirmationSender };