@jskit-ai/auth-provider-local-core 0.2.35 → 0.2.37
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 +7 -0
- package/locales/en.json +9 -1
- package/package.json +8 -6
- package/src/server/lib/accounts.js +41 -11
- package/src/server/lib/config.js +70 -51
- package/src/server/lib/deliveries.js +4 -2
- package/src/server/lib/emailChange.js +183 -0
- package/src/server/lib/emailConfirmation.js +5 -22
- package/src/server/lib/fileBackend.js +40 -2
- package/src/server/lib/fileRecords.js +17 -7
- package/src/server/lib/firstAccountSetup.js +4 -4
- package/src/server/lib/index.js +2 -0
- package/src/server/lib/oauthFlows.js +18 -7
- package/src/server/lib/passSignIn.js +16 -6
- package/src/server/lib/passwordFlows.js +7 -23
- package/src/server/lib/registerHookDecorator.js +4 -4
- package/src/server/lib/service.js +30 -9
- package/src/server/lib/sessions.js +97 -19
- package/src/server/providers/AuthLocalProvider.js +64 -16
- package/src/server/types.js +75 -10
- package/test/accountEnumeration.test.js +12 -3
- package/test/codedTexts.test.js +1 -1
- package/test/cookieSameSite.test.js +1 -1
- package/test/emailChange.test.js +37 -0
- package/test/firstAccountSetup.test.js +6 -6
- package/test/oauthSignIn.test.js +14 -2
- package/test/passSignIn.test.js +1 -1
- package/test/providerRuntime.test.js +250 -95
- package/test/secondFactor.test.js +6 -6
- package/test/sessionMetadata.test.js +38 -0
- package/test/signInEvents.test.js +206 -0
- package/test/signInThrottle.test.js +1 -1
- package/test-support/emailChangeScenario.js +139 -0
- package/test-support/localService.js +10 -4
- package/test-support/passSignInScenario.js +10 -4
- package/test-support/sessionMetadataScenario.js +76 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Email change: the signed-in person asks for a new email with their password (`requestEmailChange(request, { email, password })`), or the application asks for an account it chose, such as an operator's change for a person who lost their old address (`requestEmailChangeForUser({ userId, email })`, who may ask being the application's decision). The account keeps the address as its waiting change (`pendingEmail`) and the new address is sent a link to `/auth/email-change?token=`, signed with the session secret and working for a day; a newer request replaces the waiting change, so an earlier link stops working. Using it (`confirmEmailChange({ token })`) changes the email, which the link proves, ends the password resets sent to the old address and sends the old address a notice; the account's sessions stay signed in. Refusals: `auth.local.emailChange.passwordInvalid` (400), `sameEmail` (400), `emailTaken` (409, also when an account took the address since the link was sent), `linkInvalid` (400, a used, replaced, expired or altered link) and `accountNotFound` (404), each with its message key under `jskit.auth.local.emailChange`. The links and notices go through the new optional `auth.local.email-change-sender` capability (`AuthLocalEmailChangeSender`: `{ type: "confirmation", email, currentEmail, confirmationUrl }` or `{ type: "notice", email, newEmail }`) after the request has answered, through the local deliveries, and send as `APP_ENV` says, like the recovery and confirmation senders (production to each address, staging only to `STAGING_EMAIL_TO` with `originalEmail`, development and test to the log). Without one, development and test log them (`createLoggedEmailChangeSender`, new), and a staging or production server has no email change (`features.emailChange` false, the operations `AUTH_OPERATION_UNSUPPORTED`). A sender needs `APP_PUBLIC_URL`, which its links name.
|
|
6
|
+
- Upgrading: `createLocalAuthService()` takes `emailChangeSender`, and `resolveLocalAuthConfig()` takes `emailChangeSender: true` when one is installed (`config.emailChangeDelivery` is `email`, `dev-log` or `off`); a custom `auth.local.backend` keeps a user's `pendingEmail` and implements `users.updatePendingEmail(userId, pendingEmail)` and `users.updateEmail(userId, email)`, which refuses an email another account has with `auth.local.accounts.exists` and clears the waiting change. The file backend adds `pendingEmail` to each line of `users.passwd` and reads the lines it wrote before as having none.
|
|
7
|
+
- Each sign-in and each refused one is an event for the new optional `auth.local.sign-in-events` capability (`AuthLocalSignInEvent`, `AuthLocalSignInEvents`, also `createLocalAuthService({ signInEvents })`), for an application's list of an account's sign-ins or its audit log: `signedIn` or `failed`, the `method` (`password`, `registration`, `confirmation`, `recovery`, `pass`, or `provider` with the provider's id), a refusal's `reason` (`invalidCredentials`, `locked`, `unconfirmed`, `disabled`), the account's `userId` ("" when the email names none), the `email`, the request's `ip` and `userAgent`, and the time `at`; never a password, secret or token. It is given each event after the request has answered, through the deliveries the emails use, so a refused sign-in takes the same time whatever the recorder does; a recorder that fails is logged (`Sending the sign-in event failed.`), and a stopping server waits for the events still being handed over, as for the emails. Without one, local auth logs each event (`createLoggedSignInEvents`, new). A pass that names no account, and a provider callback refused before it names one, are not events.
|
|
8
|
+
- Upgrading: `createLocalAuthService()` takes `signInEvents` and refuses, with a `TypeError`, to be made without it; pass `createLoggedSignInEvents(logger)` for the logging the provider uses by default.
|
|
9
|
+
- A session keeps where and when it was last seen: `ip` (the request's address), `userAgent` (its `User-Agent`, at most 512 characters) and `lastSeenAt`, each "" when unknown. Signing in sets them from the request that signs in (`login`, `register`, `confirmRegistration`, `completePasswordRecovery` and `signInWithPass` take it as their second parameter, as `oauthComplete` and `devLoginAs` already did; auth-core's actions pass it), and authenticating a request that finds the session more than five minutes after it was last seen sets them again, so most requests write nothing; a request that does not say where it comes from keeps the address and browser. `authenticateRequest` still reads the session once. `createLocalAuthRegisterHookDecorator` passes the request on. Upgrading: a custom `auth.local.backend` keeps a session's `ip`, `userAgent` and `lastSeenAt` from `sessions.create` and implements `sessions.touch(sessionId, { lastSeenAt, ip, userAgent })`, which keeps the old `ip` or `userAgent` when the new one is ""; the file backend adds them to each line of `sessions.passwd` and reads the lines it wrote before as never seen; an application's own auth service decorator around `login`, `register`, `confirmRegistration` or `completePasswordRecovery` passes the request on, or its sessions keep no address.
|
|
10
|
+
- A disabled account's sign-in that proves who it is is told the account is disabled, with the application's own message when it gave one: the right password, a linked provider's sign-in or a one-time pass is refused with 403 `auth.local.login.disabled` (new message key `jskit.auth.local.login.disabled`, "This account is disabled.") and the account's `disabledMessage` as its text when it has one, which the sign-in page shows as written. Before, the right password answered "Invalid email or password.", a provider "This account can't sign in." (`auth.local.oauth.accountUnavailable`, still the answer for an identity whose account is missing) and a pass `auth.pass.unmapped` (still the answer for a pass that names no account), so a suspended person could not be told why. A wrong password for a disabled account is still an ordinary failed sign-in, counted by the sign-in throttle, so only someone who could sign in learns that the account is disabled. A backend's users carry `disabledMessage`; the file backend keeps none. `@jskit-ai/auth-provider-local-db-core`'s `auth.local.accounts.disable` and `enable` set and clear it.
|
|
11
|
+
- **Breaking:** an installed `auth.local.confirmation-sender` or `auth.local.recovery-sender` sends as `APP_ENV` says, through the kernel's `deliverMessage`: production sends each email to its address; staging sends it only to `STAGING_EMAIL_TO`, calling the sender with that address as `email` and the person's address as the new `originalEmail` (show it, for example with `markStagingEmail`), and logs it, link included, when `STAGING_EMAIL_TO` is unset; development and test log it. This replaces the simulated senders a test copy used, and `createSimulatedConfirmationSender` and `createSimulatedRecoverySender` are gone. Staging and production (`APP_ENV`), not `NODE_ENV=production`, require `AUTH_LOCAL_SESSION_SECRET`, ask for the first account's setup code, refuse `AUTH_LOCAL_RECOVERY_DEV_OUTPUT` (`… is for development only and APP_ENV is staging. Remove it from the staging environment.`) and need a confirmation sender while anyone may register.
|
|
5
12
|
- Security: asking for a password reset (`requestPasswordReset`) or a new confirmation link (`resendRegisterConfirmation`) no longer tells, by how long it takes, which emails have an account or a waiting registration. Both answered the same text for any email, but only for one with an account did they write a new link and wait for the sender, so the time of the answer showed whether the account existed, and a sender's failure reached only an account's requester. Each now validates the email, answers at once, and then looks the account up, writes the link and calls the sender; a sender's rejection is logged as an error with the address (never the link) instead of answered. The email is still sent, rate limits and texts are unchanged, and a stopping server (`AuthLocalProvider` now has a shutdown) waits up to 10 seconds for the emails still being sent. Development's `AUTH_LOCAL_RECOVERY_DEV_OUTPUT=response` and a confirmation link shown in development's answer still find the account first, since their answer carries the link; a new registration's link is still sent before its answer, which already says whether the email is taken. Upgrading: an application whose recovery sender reported delivery failures to the requester (a 502 or 503 from `requestPasswordReset`) now has them only in its log; a test that composes `createLocalAuthService()` and reads the sent email waits for it, passing `deliveries: createLocalDeliveries({ logger })` (new export) and awaiting `deliveries.settled()`.
|
|
6
13
|
- Security: a failed sign-in takes as long whether or not its email has a password to check. A sign-in for an unknown email, a disabled account or one created through a provider checked no password, while one for an account with a password ran the password strategy's check (scrypt by default), so its time showed which emails had accounts. It now checks the password against a record made once from a random password, through the application's password strategy. Answers, the sign-in throttle and successful sign-ins are unchanged.
|
|
7
14
|
|
package/locales/en.json
CHANGED
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
"email": {
|
|
6
6
|
"invalid": "Enter a valid email address."
|
|
7
7
|
},
|
|
8
|
+
"emailChange": {
|
|
9
|
+
"passwordInvalid": "That is not your password.",
|
|
10
|
+
"sameEmail": "That is already your email address.",
|
|
11
|
+
"emailTaken": "An account already exists for this email.",
|
|
12
|
+
"linkInvalid": "This email change link is invalid, used or expired. Ask for the change again.",
|
|
13
|
+
"accountNotFound": "There is no such account."
|
|
14
|
+
},
|
|
8
15
|
"password": {
|
|
9
16
|
"tooShort": "Password must be at least {min} characters.",
|
|
10
17
|
"currentInvalid": "Current password is invalid.",
|
|
@@ -25,7 +32,8 @@
|
|
|
25
32
|
"codeInvalid": "That is not this app's setup code. Copy it again from the server's log or its hosting service."
|
|
26
33
|
},
|
|
27
34
|
"login": {
|
|
28
|
-
"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."
|
|
35
|
+
"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.",
|
|
36
|
+
"disabled": "This account is disabled."
|
|
29
37
|
},
|
|
30
38
|
"recovery": {
|
|
31
39
|
"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.
|
|
3
|
+
"version": "0.2.37",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"./locales/en.json": "./locales/en.json"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@jskit-ai/auth-pass": "0.1.
|
|
15
|
+
"@jskit-ai/auth-pass": "0.1.1",
|
|
16
16
|
"openid-client": "6.8.8"
|
|
17
17
|
},
|
|
18
18
|
"description": "Local auth provider with a file backend default, no database requirement, and optional Google, Microsoft and GitHub sign-in.",
|
|
@@ -49,11 +49,11 @@
|
|
|
49
49
|
},
|
|
50
50
|
{
|
|
51
51
|
"subpath": "./server/lib/index",
|
|
52
|
-
"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
|
|
52
|
+
"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, confirmation and email change senders (createLoggedRecoverySender, createLoggedConfirmationSender, createLoggedEmailChangeSender), the first account's setup code (createFirstAccountSetup, SETUP_CODE_FILE, SETUP_CODE_ENV), the logged second factor events (createLoggedSecondFactorEvents), the logged sign-in events (createLoggedSignInEvents), 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."
|
|
53
53
|
},
|
|
54
54
|
{
|
|
55
55
|
"subpath": "./server/types",
|
|
56
|
-
"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, auth.local.confirmation-sender, auth.local.confirmation-mode, auth.local.second-factor-events and auth.local.pass-identity capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
56
|
+
"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, auth.local.confirmation-sender, auth.local.email-change-sender, auth.local.confirmation-mode, auth.local.second-factor-events, auth.local.sign-in-events and auth.local.pass-identity capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
57
57
|
}
|
|
58
58
|
],
|
|
59
59
|
"extensionCapabilities": [
|
|
@@ -63,15 +63,17 @@
|
|
|
63
63
|
"auth.profile.projector",
|
|
64
64
|
"auth.local.recovery-sender",
|
|
65
65
|
"auth.local.confirmation-sender",
|
|
66
|
+
"auth.local.email-change-sender",
|
|
66
67
|
"auth.local.confirmation-mode",
|
|
67
68
|
"auth.local.second-factor-events",
|
|
69
|
+
"auth.local.sign-in-events",
|
|
68
70
|
"auth.local.pass-identity"
|
|
69
71
|
]
|
|
70
72
|
}
|
|
71
73
|
}
|
|
72
74
|
},
|
|
73
75
|
"peerDependencies": {
|
|
74
|
-
"@jskit-ai/auth-core": "0.2.
|
|
75
|
-
"@jskit-ai/kernel": "0.2.
|
|
76
|
+
"@jskit-ai/auth-core": "0.2.31",
|
|
77
|
+
"@jskit-ai/kernel": "0.2.27"
|
|
76
78
|
}
|
|
77
79
|
}
|
|
@@ -54,6 +54,16 @@ function validatePasswordInput(password, minLength) {
|
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The refusal of a disabled account's sign-in that proved who it is (its password, its provider or a pass): what the
|
|
59
|
+
* application wrote when it disabled the account, or a plain sentence when it wrote nothing. Without that proof a
|
|
60
|
+
* sign-in of a disabled account fails as any other does, so the refusal tells no one else the account exists.
|
|
61
|
+
* @param {{ disabledMessage?: string }} user
|
|
62
|
+
*/
|
|
63
|
+
function accountDisabledError(user) {
|
|
64
|
+
return new AppError(403, user.disabledMessage || "This account is disabled.", { code: "auth.local.login.disabled" });
|
|
65
|
+
}
|
|
66
|
+
|
|
57
67
|
function validateEmailInput(email) {
|
|
58
68
|
const normalized = normalizeEmail(email);
|
|
59
69
|
if (!normalized || !normalized.includes("@")) {
|
|
@@ -167,7 +177,7 @@ function createLocalAccounts({
|
|
|
167
177
|
return invitation.expiresAt == null || new Date(invitation.expiresAt).getTime() > Date.now();
|
|
168
178
|
}
|
|
169
179
|
|
|
170
|
-
async function register(input) {
|
|
180
|
+
async function register(input, request = null) {
|
|
171
181
|
const email = validateEmailInput(input.email);
|
|
172
182
|
validatePasswordInput(input.password, config.passwordMinLength);
|
|
173
183
|
const displayName = normalizeDisplayName(input.displayName, email);
|
|
@@ -195,10 +205,11 @@ function createLocalAccounts({
|
|
|
195
205
|
});
|
|
196
206
|
return {
|
|
197
207
|
user,
|
|
198
|
-
session: await sessions.createSessionForUser(tx, user)
|
|
208
|
+
session: await sessions.createSessionForUser(tx, user, { request })
|
|
199
209
|
};
|
|
200
210
|
});
|
|
201
211
|
firstAccountSetup.accountCreated();
|
|
212
|
+
sessions.recordSignInEvent("signedIn", { method: "registration", userId: result.user.id, email: result.user.email }, request);
|
|
202
213
|
return {
|
|
203
214
|
...(await buildAuthPayload({
|
|
204
215
|
user: result.user,
|
|
@@ -226,11 +237,14 @@ function createLocalAccounts({
|
|
|
226
237
|
* not the account exists, so the wait they cause says nothing about which
|
|
227
238
|
* accounts exist; while an account waits its password is not checked. Nor
|
|
228
239
|
* does a failure's time: a sign-in whose email has no password to check (no
|
|
229
|
-
* account,
|
|
230
|
-
*
|
|
231
|
-
*
|
|
240
|
+
* account, or one created through a provider) checks the password against one
|
|
241
|
+
* nobody knows, as long as checking a wrong one takes. A successful sign-in,
|
|
242
|
+
* or a password reset, forgets the failures. A disabled account's right
|
|
243
|
+
* password is refused with the account's message; its wrong one is an
|
|
244
|
+
* ordinary failure. The sign-in, or its refusal with the reason, is a
|
|
245
|
+
* sign-in event.
|
|
232
246
|
*/
|
|
233
|
-
async function login(input) {
|
|
247
|
+
async function login(input, request = null) {
|
|
234
248
|
const email = validateEmailInput(input.email);
|
|
235
249
|
const password = String(input.password || "");
|
|
236
250
|
const outcome = await backend.withTransaction(async (tx) => {
|
|
@@ -238,7 +252,8 @@ function createLocalAccounts({
|
|
|
238
252
|
const failures = await tx.signInFailures.find(email);
|
|
239
253
|
const waitMs = signInWaitMs(failures, now);
|
|
240
254
|
if (waitMs > 0) {
|
|
241
|
-
|
|
255
|
+
// Only for the sign-in event: the password is not checked.
|
|
256
|
+
return { waitMs, userId: (await tx.users.findByEmail(email))?.id || "" };
|
|
242
257
|
}
|
|
243
258
|
let checked = false;
|
|
244
259
|
const passwordMatches = (record) => {
|
|
@@ -251,29 +266,42 @@ function createLocalAccounts({
|
|
|
251
266
|
passwordMatches(registration.password)))) {
|
|
252
267
|
return { unconfirmed: true };
|
|
253
268
|
}
|
|
254
|
-
if (!user ||
|
|
269
|
+
if (!user || !hasPassword(user) || !(await passwordMatches(user.password))) {
|
|
255
270
|
if (!checked) {
|
|
256
271
|
await passwords.verifyPassword(password, await unmatchableRecord());
|
|
257
272
|
}
|
|
258
273
|
await tx.signInFailures.deleteBefore(forgottenFailuresBefore(now));
|
|
259
274
|
await tx.signInFailures.save(recordSignInFailure(config.signInThrottle, failures, email, now));
|
|
260
|
-
return { failed: true };
|
|
275
|
+
return { failed: true, userId: user?.id || "" };
|
|
276
|
+
}
|
|
277
|
+
if (user.disabled) {
|
|
278
|
+
return { disabled: user };
|
|
261
279
|
}
|
|
262
280
|
if (failures) {
|
|
263
281
|
await tx.signInFailures.clear(email);
|
|
264
282
|
}
|
|
265
|
-
return { user, session: await sessions.createSessionForUser(tx, user) };
|
|
283
|
+
return { user, session: await sessions.createSessionForUser(tx, user, { request }) };
|
|
266
284
|
});
|
|
267
285
|
// Refused after the transaction, so the failure it records is kept.
|
|
286
|
+
const refused = (reason, userId = "") =>
|
|
287
|
+
sessions.recordSignInEvent("failed", { method: "password", reason, userId, email }, request);
|
|
268
288
|
if (outcome.waitMs) {
|
|
289
|
+
refused("locked", outcome.userId);
|
|
269
290
|
throw signInLockedError(outcome.waitMs);
|
|
270
291
|
}
|
|
271
292
|
if (outcome.failed) {
|
|
293
|
+
refused("invalidCredentials", outcome.userId);
|
|
272
294
|
throw createAuthError(AUTH_TEXTS.invalidCredentials);
|
|
273
295
|
}
|
|
274
296
|
if (outcome.unconfirmed) {
|
|
297
|
+
refused("unconfirmed");
|
|
275
298
|
throw createAuthError(AUTH_TEXTS.emailUnconfirmed);
|
|
276
299
|
}
|
|
300
|
+
if (outcome.disabled) {
|
|
301
|
+
refused("disabled", outcome.disabled.id);
|
|
302
|
+
throw accountDisabledError(outcome.disabled);
|
|
303
|
+
}
|
|
304
|
+
sessions.recordSignInEvent("signedIn", { method: "password", userId: outcome.user.id, email: outcome.user.email }, request);
|
|
277
305
|
// After the transaction, as register does: the profile projector works in transactions of its own, so a sign-in
|
|
278
306
|
// that synchronized the profile inside this one held two database connections at once.
|
|
279
307
|
return buildAuthPayload({ user: outcome.user, session: outcome.session, profileProjector });
|
|
@@ -309,7 +337,8 @@ function createLocalAccounts({
|
|
|
309
337
|
throw devLoginAsUserNotFound({ email, userId });
|
|
310
338
|
}
|
|
311
339
|
const session = await backend.withTransaction((tx) => sessions.createSessionForUser(tx, user, {
|
|
312
|
-
purpose: DEV_AUTH_SESSION_PURPOSE
|
|
340
|
+
purpose: DEV_AUTH_SESSION_PURPOSE,
|
|
341
|
+
request
|
|
313
342
|
}));
|
|
314
343
|
return buildAuthResult({ user, session, appProfile });
|
|
315
344
|
}
|
|
@@ -344,6 +373,7 @@ function createLocalAccounts({
|
|
|
344
373
|
|
|
345
374
|
export {
|
|
346
375
|
NO_PASSWORD,
|
|
376
|
+
accountDisabledError,
|
|
347
377
|
createLocalAccounts,
|
|
348
378
|
hasPassword,
|
|
349
379
|
normalizeDisplayName,
|
package/src/server/lib/config.js
CHANGED
|
@@ -7,7 +7,7 @@ import path from "node:path";
|
|
|
7
7
|
import { AUTH_PASSWORD_MIN_LENGTH } from "@jskit-ai/auth-core/shared/authConstraints";
|
|
8
8
|
import { resolveAuthCookieSameSite } from "@jskit-ai/auth-core/server/utils";
|
|
9
9
|
import { parsePositiveInteger } from "@jskit-ai/kernel/server/runtime";
|
|
10
|
-
import { assertDevelopmentOnlySettings } from "@jskit-ai/kernel/server/runtime/
|
|
10
|
+
import { assertDevelopmentOnlySettings } from "@jskit-ai/kernel/server/runtime/appEnvironment";
|
|
11
11
|
import { SETUP_CODE_ENV, SETUP_CODE_MIN_CHARACTERS, normalizedSetupCode } from "./firstAccountSetup.js";
|
|
12
12
|
import { resolveOAuthProviders } from "./oauth.js";
|
|
13
13
|
import { resolveSignInThrottle } from "./signInThrottle.js";
|
|
@@ -24,15 +24,15 @@ function resolveStoreDir(env, appRoot) {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
* AUTH_LOCAL_SESSION_SECRET, or
|
|
28
|
-
* directory, generated on first use.
|
|
27
|
+
* AUTH_LOCAL_SESSION_SECRET, or in development and test a secret kept in the
|
|
28
|
+
* store directory, generated on first use.
|
|
29
29
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
30
|
-
* @param {{ storeDir: string,
|
|
30
|
+
* @param {{ storeDir: string, isDeployed: boolean }} options
|
|
31
31
|
*/
|
|
32
|
-
function resolveSessionSecret(env, { storeDir,
|
|
32
|
+
function resolveSessionSecret(env, { storeDir, isDeployed }) {
|
|
33
33
|
const explicit = String(env.AUTH_LOCAL_SESSION_SECRET || "").trim();
|
|
34
34
|
if (explicit) return explicit;
|
|
35
|
-
if (
|
|
35
|
+
if (isDeployed) throw new Error("AUTH_LOCAL_SESSION_SECRET is required for local auth in staging and production.");
|
|
36
36
|
|
|
37
37
|
const secretPath = path.join(storeDir, "session.secret");
|
|
38
38
|
try {
|
|
@@ -53,13 +53,13 @@ const SECOND_FACTOR_KEY_MIN_CHARACTERS = 32;
|
|
|
53
53
|
/**
|
|
54
54
|
* AUTH_LOCAL_SECOND_FACTOR_KEY: the application's key, from which local auth
|
|
55
55
|
* derives the keys that seal authenticator secrets and hash recovery codes.
|
|
56
|
-
*
|
|
57
|
-
* without it has no second factor (""); one shorter than 32
|
|
58
|
-
* startup.
|
|
56
|
+
* In development and test the session secret stands in for it. A staging or
|
|
57
|
+
* production server without it has no second factor (""); one shorter than 32
|
|
58
|
+
* characters stops startup.
|
|
59
59
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
60
|
-
* @param {{
|
|
60
|
+
* @param {{ isDeployed: boolean, sessionSecret: string }} options
|
|
61
61
|
*/
|
|
62
|
-
function resolveSecondFactorKey(env, {
|
|
62
|
+
function resolveSecondFactorKey(env, { isDeployed, sessionSecret }) {
|
|
63
63
|
const key = String(env.AUTH_LOCAL_SECOND_FACTOR_KEY || "").trim();
|
|
64
64
|
if (key) {
|
|
65
65
|
if (key.length < SECOND_FACTOR_KEY_MIN_CHARACTERS) {
|
|
@@ -67,19 +67,19 @@ function resolveSecondFactorKey(env, { isProduction, sessionSecret }) {
|
|
|
67
67
|
}
|
|
68
68
|
return key;
|
|
69
69
|
}
|
|
70
|
-
return
|
|
70
|
+
return isDeployed ? "" : sessionSecret;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
/**
|
|
74
74
|
* AUTH_LOCAL_SETUP_CODE: the first account's setup code when a hosting tool
|
|
75
75
|
* supplies it, so that every start and every server asks for the same code.
|
|
76
|
-
* Only production
|
|
76
|
+
* Only staging and production ask for a setup code; elsewhere the variable is ignored.
|
|
77
77
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
78
|
-
* @param {{
|
|
78
|
+
* @param {{ isDeployed: boolean }} options
|
|
79
79
|
*/
|
|
80
|
-
function resolveSetupCode(env, {
|
|
80
|
+
function resolveSetupCode(env, { isDeployed }) {
|
|
81
81
|
const code = String(env[SETUP_CODE_ENV] || "").trim();
|
|
82
|
-
if (!
|
|
82
|
+
if (!isDeployed || !code) return "";
|
|
83
83
|
if (normalizedSetupCode(code).length < SETUP_CODE_MIN_CHARACTERS) {
|
|
84
84
|
throw new Error(`${SETUP_CODE_ENV} must have at least ${SETUP_CODE_MIN_CHARACTERS} letters and digits.`);
|
|
85
85
|
}
|
|
@@ -87,22 +87,23 @@ function resolveSetupCode(env, { isProduction }) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
* APP_PUBLIC_URL, from which recovery and
|
|
91
|
-
* redirect addresses are built, and whose host authenticator apps show
|
|
92
|
-
* a second factor's codes. Emailed links, OAuth sign-in and a
|
|
90
|
+
* APP_PUBLIC_URL, from which recovery, confirmation and email change links and
|
|
91
|
+
* OAuth redirect addresses are built, and whose host authenticator apps show
|
|
92
|
+
* beside a second factor's codes. Emailed links, OAuth sign-in and a deployed
|
|
93
93
|
* server's second factor require it.
|
|
94
94
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
95
|
-
* @param {{ emailRecovery: boolean, emailedConfirmation: boolean, oauthEnabled: boolean,
|
|
95
|
+
* @param {{ emailRecovery: boolean, emailedConfirmation: boolean, emailedChange: boolean, oauthEnabled: boolean, deployedSecondFactor: boolean }} options
|
|
96
96
|
*/
|
|
97
|
-
function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEnabled,
|
|
97
|
+
function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, emailedChange, oauthEnabled, deployedSecondFactor }) {
|
|
98
98
|
const configured = String(env.APP_PUBLIC_URL || "").trim();
|
|
99
99
|
if (!configured) {
|
|
100
100
|
if (emailRecovery) throw new Error("APP_PUBLIC_URL is required when local auth email recovery is configured.");
|
|
101
|
+
if (emailedChange) throw new Error("APP_PUBLIC_URL is required when local auth emails email change links.");
|
|
101
102
|
if (emailedConfirmation) {
|
|
102
103
|
throw new Error("APP_PUBLIC_URL is required when local auth emails confirmation links.");
|
|
103
104
|
}
|
|
104
105
|
if (oauthEnabled) throw new Error("APP_PUBLIC_URL is required when local auth OAuth sign-in is configured.");
|
|
105
|
-
if (
|
|
106
|
+
if (deployedSecondFactor) {
|
|
106
107
|
throw new Error("APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set: authenticator apps show its host.");
|
|
107
108
|
}
|
|
108
109
|
return "http://localhost:5173";
|
|
@@ -121,17 +122,17 @@ function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEna
|
|
|
121
122
|
|
|
122
123
|
/**
|
|
123
124
|
* How a password recovery link reaches the person: by email through the
|
|
124
|
-
* installed recovery sender; otherwise,
|
|
125
|
-
* the response (AUTH_LOCAL_RECOVERY_DEV_OUTPUT=response). In
|
|
126
|
-
* a sender, recovery is disabled, and
|
|
127
|
-
* startup (resolveLocalAuthConfig).
|
|
125
|
+
* installed recovery sender; otherwise, in development and test, in the log or
|
|
126
|
+
* in the response (AUTH_LOCAL_RECOVERY_DEV_OUTPUT=response). In staging and
|
|
127
|
+
* production without a sender, recovery is disabled, and
|
|
128
|
+
* AUTH_LOCAL_RECOVERY_DEV_OUTPUT stops startup (resolveLocalAuthConfig).
|
|
128
129
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
129
|
-
* @param {{ emailRecovery: boolean,
|
|
130
|
+
* @param {{ emailRecovery: boolean, isDeployed: boolean }} options
|
|
130
131
|
* @returns {"email" | "disabled" | "dev-response" | "dev-log"}
|
|
131
132
|
*/
|
|
132
|
-
function resolveRecoveryDelivery(env, { emailRecovery,
|
|
133
|
+
function resolveRecoveryDelivery(env, { emailRecovery, isDeployed }) {
|
|
133
134
|
if (emailRecovery) return "email";
|
|
134
|
-
if (
|
|
135
|
+
if (isDeployed) return "disabled";
|
|
135
136
|
const devOutput = String(env.AUTH_LOCAL_RECOVERY_DEV_OUTPUT || "").trim().toLowerCase();
|
|
136
137
|
return devOutput === "response" ? "dev-response" : "dev-log";
|
|
137
138
|
}
|
|
@@ -140,22 +141,23 @@ function resolveRecoveryDelivery(env, { emailRecovery, isProduction }) {
|
|
|
140
141
|
* Whether a registration waits for its email to be confirmed
|
|
141
142
|
* (AUTH_LOCAL_EMAIL_CONFIRMATION, on unless set to false), and how its link
|
|
142
143
|
* reaches the person: by email through the installed confirmation sender, or,
|
|
143
|
-
* in development without one, in the registration's response (the
|
|
144
|
-
* screen shows it) and the log. Confirmation guards self-registration:
|
|
145
|
-
* production without a sender, startup stops while anyone may
|
|
146
|
-
* because nobody could confirm, and with self-registration off
|
|
147
|
-
* accounts and the first one, admitted by its setup code) nothing is
|
|
144
|
+
* in development and test without one, in the registration's response (the
|
|
145
|
+
* sign-in screen shows it) and the log. Confirmation guards self-registration:
|
|
146
|
+
* in staging and production without a sender, startup stops while anyone may
|
|
147
|
+
* register, because nobody could confirm, and with self-registration off
|
|
148
|
+
* (invited accounts and the first one, admitted by its setup code) nothing is
|
|
149
|
+
* confirmed.
|
|
148
150
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
149
|
-
* @param {{ emailConfirmationSender: boolean,
|
|
151
|
+
* @param {{ emailConfirmationSender: boolean, isDeployed: boolean, selfRegistration: boolean }} options
|
|
150
152
|
* @returns {"email" | "dev-response" | "off"}
|
|
151
153
|
*/
|
|
152
|
-
function resolveConfirmationDelivery(env, { emailConfirmationSender,
|
|
154
|
+
function resolveConfirmationDelivery(env, { emailConfirmationSender, isDeployed, selfRegistration }) {
|
|
153
155
|
if (!parseBooleanFlag(env.AUTH_LOCAL_EMAIL_CONFIRMATION, true)) return "off";
|
|
154
156
|
if (emailConfirmationSender) return "email";
|
|
155
|
-
if (
|
|
157
|
+
if (isDeployed) {
|
|
156
158
|
if (!selfRegistration) return "off";
|
|
157
159
|
throw new Error(
|
|
158
|
-
"Local auth confirms each new account's email address in production, and no auth.local.confirmation-sender " +
|
|
160
|
+
"Local auth confirms each new account's email address in staging and production, and no auth.local.confirmation-sender " +
|
|
159
161
|
"is installed to email the confirmation links. Install one, set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
|
|
160
162
|
"to let accounts register without confirming their email, or set AUTH_LOCAL_SELF_REGISTRATION=false " +
|
|
161
163
|
"when accounts are only invited."
|
|
@@ -164,6 +166,19 @@ function resolveConfirmationDelivery(env, { emailConfirmationSender, isProductio
|
|
|
164
166
|
return "dev-response";
|
|
165
167
|
}
|
|
166
168
|
|
|
169
|
+
/**
|
|
170
|
+
* How an email change's link and the notice to the old address reach the
|
|
171
|
+
* person: by email through the installed email-change sender; otherwise, in
|
|
172
|
+
* development and test, in the log. A deployed server (staging or production)
|
|
173
|
+
* without a sender has no email change.
|
|
174
|
+
* @param {{ emailChangeSender: boolean, isDeployed: boolean }} options
|
|
175
|
+
* @returns {"email" | "dev-log" | "off"}
|
|
176
|
+
*/
|
|
177
|
+
function resolveEmailChangeDelivery({ emailChangeSender, isDeployed }) {
|
|
178
|
+
if (emailChangeSender) return "email";
|
|
179
|
+
return isDeployed ? "off" : "dev-log";
|
|
180
|
+
}
|
|
181
|
+
|
|
167
182
|
/**
|
|
168
183
|
* The shortest password local auth accepts: AUTH_LOCAL_PASSWORD_MIN_LENGTH, or 8.
|
|
169
184
|
* It can be raised, up to 64, but not lowered below 8.
|
|
@@ -181,8 +196,8 @@ function resolvePasswordMinLength(env) {
|
|
|
181
196
|
|
|
182
197
|
/**
|
|
183
198
|
* The local auth configuration, resolved and checked once from the environment.
|
|
184
|
-
*
|
|
185
|
-
* and its dev sign-in agree on it.
|
|
199
|
+
* Whether it is deployed (APP_ENV staging or production) is worked out once, by
|
|
200
|
+
* auth-core's dev auth policy, so local auth and its dev sign-in agree on it.
|
|
186
201
|
* @param {object} input
|
|
187
202
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} input.appRoot
|
|
188
203
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} input.env
|
|
@@ -190,34 +205,37 @@ function resolvePasswordMinLength(env) {
|
|
|
190
205
|
* `auth.local.backend` is installed.
|
|
191
206
|
* @param {boolean} input.emailRecovery True when an `auth.local.recovery-sender` is installed.
|
|
192
207
|
* @param {boolean} [input.emailConfirmationSender] True when an `auth.local.confirmation-sender` is installed.
|
|
208
|
+
* @param {boolean} [input.emailChangeSender] True when an `auth.local.email-change-sender` is installed.
|
|
193
209
|
*/
|
|
194
|
-
function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender = false }) {
|
|
210
|
+
function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender = false, emailChangeSender = false }) {
|
|
195
211
|
const devAuth = resolveDevAuthPolicyFromEnv(env);
|
|
196
|
-
const {
|
|
212
|
+
const { isDeployed } = devAuth;
|
|
197
213
|
const storeDir = resolveStoreDir(env, appRoot);
|
|
198
|
-
if (fileBackend &&
|
|
199
|
-
throw new Error("AUTH_LOCAL_FILE_PRODUCTION_ACK is required to use the local file auth backend in production.");
|
|
214
|
+
if (fileBackend && isDeployed && !parseBooleanFlag(env.AUTH_LOCAL_FILE_PRODUCTION_ACK, false)) {
|
|
215
|
+
throw new Error("AUTH_LOCAL_FILE_PRODUCTION_ACK is required to use the local file auth backend in staging and production.");
|
|
200
216
|
}
|
|
201
217
|
assertDevAuthPolicy(devAuth);
|
|
202
218
|
assertDevelopmentOnlySettings(env, ["AUTH_LOCAL_RECOVERY_DEV_OUTPUT"]);
|
|
203
219
|
const oauthProviders = resolveOAuthProviders(env);
|
|
204
220
|
const oauthEnabled = oauthProviders.length > 0;
|
|
205
|
-
const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery,
|
|
221
|
+
const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery, isDeployed });
|
|
206
222
|
// AUTH_LOCAL_SELF_REGISTRATION, on unless set to false: off, an account registers only by an invitation a feature
|
|
207
223
|
// resolves, or as the first account.
|
|
208
224
|
const selfRegistration = parseBooleanFlag(env.AUTH_LOCAL_SELF_REGISTRATION, true);
|
|
209
|
-
const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender,
|
|
210
|
-
const sessionSecret = resolveSessionSecret(env, { storeDir,
|
|
211
|
-
const secondFactorKey = resolveSecondFactorKey(env, {
|
|
225
|
+
const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isDeployed, selfRegistration });
|
|
226
|
+
const sessionSecret = resolveSessionSecret(env, { storeDir, isDeployed });
|
|
227
|
+
const secondFactorKey = resolveSecondFactorKey(env, { isDeployed, sessionSecret });
|
|
228
|
+
const emailChangeDelivery = resolveEmailChangeDelivery({ emailChangeSender, isDeployed });
|
|
212
229
|
const appPublicUrl = resolveAppPublicUrl(env, {
|
|
213
230
|
emailRecovery,
|
|
214
231
|
emailedConfirmation: confirmationDelivery === "email",
|
|
232
|
+
emailedChange: emailChangeDelivery === "email",
|
|
215
233
|
oauthEnabled,
|
|
216
|
-
|
|
234
|
+
deployedSecondFactor: isDeployed && Boolean(secondFactorKey)
|
|
217
235
|
});
|
|
218
236
|
return Object.freeze({
|
|
219
237
|
storeDir,
|
|
220
|
-
|
|
238
|
+
isDeployed,
|
|
221
239
|
// The SameSite of every local auth cookie: AUTH_COOKIE_SAME_SITE, "lax" unless set to "strict".
|
|
222
240
|
cookieSameSite: resolveAuthCookieSameSite(env),
|
|
223
241
|
appPublicUrl,
|
|
@@ -226,12 +244,13 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
|
|
|
226
244
|
sessionSecret,
|
|
227
245
|
// "" when the server has no second factor.
|
|
228
246
|
secondFactorKey,
|
|
229
|
-
setupCode: resolveSetupCode(env, {
|
|
247
|
+
setupCode: resolveSetupCode(env, { isDeployed }),
|
|
230
248
|
recoveryDelivery,
|
|
231
249
|
recoveryEnabled: recoveryDelivery !== "disabled",
|
|
232
250
|
selfRegistration,
|
|
233
251
|
confirmationDelivery,
|
|
234
252
|
emailConfirmation: confirmationDelivery !== "off",
|
|
253
|
+
emailChangeDelivery,
|
|
235
254
|
passwordMinLength: resolvePasswordMinLength(env),
|
|
236
255
|
signInThrottle: resolveSignInThrottle(env),
|
|
237
256
|
// The trusted issuer's key, audience and resource of one-time pass sign-in (AUTH_PASS_*), or null while it is off.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* How long a stopping server waits for the emails local auth is still sending,
|
|
2
|
+
* How long a stopping server waits for the emails local auth is still sending, and the sign-in events it is still
|
|
3
|
+
* handing over, before it stops anyway.
|
|
3
4
|
*/
|
|
4
5
|
const DELIVERY_SHUTDOWN_WAIT_MS = 10_000;
|
|
5
6
|
|
|
@@ -9,7 +10,8 @@ const DELIVERY_SHUTDOWN_WAIT_MS = 10_000;
|
|
|
9
10
|
* answer must not wait on work done only when it has one: looking it up and writing a new link differ in time, and
|
|
10
11
|
* the sender's own time and failures differ most. That work runs here instead, once the request has answered. Each
|
|
11
12
|
* piece starts at once; its failure is logged, never the link it carries, and is not the requester's to see. A
|
|
12
|
-
* stopping server waits for the emails still being sent (settled).
|
|
13
|
+
* stopping server waits for the emails still being sent (settled). Each sign-in event goes the same way, so a refused
|
|
14
|
+
* sign-in answers in the same time whatever the application's recorder takes.
|
|
13
15
|
* @param {object} dependencies
|
|
14
16
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
15
17
|
*/
|