@jskit-ai/auth-provider-local-core 0.2.24 → 0.2.26
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 +4 -0
- package/locales/en.json +10 -0
- package/package.json +8 -6
- package/src/server/lib/accounts.js +5 -3
- package/src/server/lib/config.js +43 -9
- package/src/server/lib/emailConfirmation.js +37 -1
- package/src/server/lib/fileBackend.js +72 -3
- package/src/server/lib/fileRecords.js +56 -3
- package/src/server/lib/index.js +1 -0
- package/src/server/lib/secondFactor.js +408 -0
- package/src/server/lib/secondFactorCrypto.js +239 -0
- package/src/server/lib/securityStatus.js +11 -3
- package/src/server/lib/service.js +38 -4
- package/src/server/lib/sessions.js +7 -1
- package/src/server/lib/signInThrottle.js +34 -11
- package/src/server/providers/AuthLocalProvider.js +31 -5
- package/src/server/types.js +72 -3
- package/test/codedTexts.test.js +28 -0
- package/test/providerRuntime.test.js +151 -0
- package/test/secondFactor.test.js +128 -0
- package/test-support/localService.js +3 -1
- package/test-support/secondFactorScenario.js +262 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- **Second factor: authenticator-app codes (TOTP, RFC 6238) with recovery codes**, one per account, in the file backend and through the backend contract. Setting up shows the secret once (as text and in an `otpauth://` address for a QR code, whose issuer is `APP_PUBLIC_URL`'s host) and a first code confirms it, answering ten single-use recovery codes once. A code is six digits of a 30-second step, accepted within one step either side of the server's clock and only once: no code of an accepted step or an earlier one passes again. The secret is sealed with AES-256-GCM, bound to its account, under a key derived from `AUTH_LOCAL_SECOND_FACTOR_KEY`; recovery codes are kept as keyed hashes. An accepted code or recovery code marks the request's session with the time (`secondFactorAt`, which `authenticate` returns for the auth policy); removing the authenticator clears it from every session of the account. Wrong codes make the account wait as wrong passwords do (five, then 30 seconds doubling to an hour), refused with 429 `auth.local.secondFactor.locked`. New refusals, each with its message key under `jskit.auth.local.secondFactor`: `notSetUp`, `alreadySetUp`, `setupNotStarted`, `proofRequired`, `codeInvalid`, `codeUsed`, `recoveryCodeInvalid` and `locked`.
|
|
6
|
+
- Every second-factor change and failed attempt (setup started or confirmed, verified, failed with its reason, recovery codes replaced, removed, reset) is an event, with the account id, the request's address and the time and never a secret or a code, for the optional `auth.local.second-factor-events` capability (`AuthLocalSecondFactorEvent`), an application's audit log; without one, local auth logs each event. `listSecondFactors({ userIds })` and `resetSecondFactor({ userId, byUserId })` serve an application's own owner screens.
|
|
7
|
+
- Upgrading: a production server has a second factor only with `AUTH_LOCAL_SECOND_FACTOR_KEY` set (at least 32 characters, which then also requires `APP_PUBLIC_URL`); outside production the session secret stands in for it. Keep the key: a factor sealed under one key does not open under another, and verifying one then fails as a server error. A custom `auth.local.backend` implements the `secondFactors` collection (`find`, `findMany`, `save`, `delete`) and `sessions.markSecondFactorProved` / `sessions.clearSecondFactorForUser`, and keeps a session's `secondFactorAt`; the file backend keeps the factors in `second-factors.passwd`.
|
|
8
|
+
- An application can confirm a new account at once, without a link, when it chooses to, for example while its email isn't set up: it installs the optional `auth.local.confirmation-mode` capability, a function that receives `{ email }` for each registration that would wait for its link and answers `"link"` (send it, as before) or `"without-link"` (create the account and sign the person in at once, with an address nobody proved, and run the register hook). Only that exact answer skips the link; any other answer means a link and logs a warning. The mode sends nothing, so a test copy (`SIDE_EFFECTS` is not `live`) keeps it and registers exactly as the live copy does, while an installed sender is still replaced by the simulated one there, whatever it does: a test copy never sends real email. A production server still needs a sender (or `AUTH_LOCAL_EMAIL_CONFIRMATION=false`). Before, the only way to confirm at once was code that confirmed with the link the application's own sender was given; in a test copy that sender never runs, so the code got no link and registering failed with 500 (`Invalid URL`). Such code moves to `auth.local.confirmation-mode`. Applications without one are unchanged. For direct library composition, `createLocalAuthService()` takes it as `confirmationMode`.
|
|
5
9
|
- A test copy (`SIDE_EFFECTS` is not `live`) sends no email: with an installed sender, confirmation and password-reset emails are logged as simulated (with their links) instead of sent. A logged (development) sender is unchanged. Tests that prove an installed sender set `SIDE_EFFECTS: "live"`.
|
|
6
10
|
- With email confirmation on, two registrations whose email is already proven sign in at once instead of waiting for a link: one through an invitation a feature's invitation context resolver resolved, still pending, that names the registering email (letter case does not matter) and has not expired (`expiresAt`), whose link reached that address; and the app's first account, admitted by the production setup code only the server's operator can read (`firstAccountSetup.admitRegistration` answers true for it). An invitation passed through as given (no resolver installed), or one whose context names no email, another email or an expiry that has passed, proves nothing: that registration still waits, as does every other sign-up, and development's first account, which needs no code. Signing in with a waiting registration's password is refused as unconfirmed (403 `auth.login.emailUnconfirmed`) whatever `AUTH_LOCAL_EMAIL_CONFIRMATION` says now, where with it off such a sign-in was an ordinary failed one; registering again with it off creates the account.
|
|
7
11
|
- Completing a password reset consumes the user's other password resets (`rec_…` tokens) only, leaving an app's own kinds of recovery token, such as sign-in links, open: the backend contract's `recovery.consumeForUser(userId, { idPrefix })` takes the kind it consumes, and the file backend requires it as the database backend does.
|
package/locales/en.json
CHANGED
|
@@ -47,6 +47,16 @@
|
|
|
47
47
|
"identityTaken": "This {provider} account is already linked to another account.",
|
|
48
48
|
"notLinked": "{provider} is not linked to this account.",
|
|
49
49
|
"lastMethod": "Add a password or link another sign-in method before removing this one."
|
|
50
|
+
},
|
|
51
|
+
"secondFactor": {
|
|
52
|
+
"notSetUp": "No authenticator is set up for this account.",
|
|
53
|
+
"alreadySetUp": "An authenticator is already set up for this account. Remove it before setting up another.",
|
|
54
|
+
"setupNotStarted": "Start setting up the authenticator again.",
|
|
55
|
+
"proofRequired": "Enter a code from your authenticator app or one of your recovery codes.",
|
|
56
|
+
"codeInvalid": "That code is not right. Enter the code your authenticator app shows now.",
|
|
57
|
+
"codeUsed": "That code was already used. Wait for the next code from your authenticator app.",
|
|
58
|
+
"recoveryCodeInvalid": "That recovery code is not right, or it was already used.",
|
|
59
|
+
"locked": "Too many wrong codes. Try again in {count} minute. | Too many wrong codes. Try again in {count} minutes."
|
|
50
60
|
}
|
|
51
61
|
}
|
|
52
62
|
}
|
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.26",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -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 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."
|
|
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), the logged second factor events (createLoggedSecondFactorEvents), 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, auth.local.recovery-sender
|
|
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, auth.local.confirmation-sender, auth.local.confirmation-mode and auth.local.second-factor-events capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
56
56
|
}
|
|
57
57
|
],
|
|
58
58
|
"extensionCapabilities": [
|
|
@@ -61,13 +61,15 @@
|
|
|
61
61
|
"auth.local.password-strategy",
|
|
62
62
|
"auth.profile.projector",
|
|
63
63
|
"auth.local.recovery-sender",
|
|
64
|
-
"auth.local.confirmation-sender"
|
|
64
|
+
"auth.local.confirmation-sender",
|
|
65
|
+
"auth.local.confirmation-mode",
|
|
66
|
+
"auth.local.second-factor-events"
|
|
65
67
|
]
|
|
66
68
|
}
|
|
67
69
|
}
|
|
68
70
|
},
|
|
69
71
|
"peerDependencies": {
|
|
70
|
-
"@jskit-ai/auth-core": "0.2.
|
|
71
|
-
"@jskit-ai/kernel": "0.2.
|
|
72
|
+
"@jskit-ai/auth-core": "0.2.22",
|
|
73
|
+
"@jskit-ai/kernel": "0.2.22"
|
|
72
74
|
}
|
|
73
75
|
}
|
|
@@ -122,7 +122,8 @@ async function resolveRegistrationProfileOptions(invitationContextResolver, invi
|
|
|
122
122
|
/**
|
|
123
123
|
* The accounts of local auth: registering one (which waits for its email to
|
|
124
124
|
* be confirmed while config.emailConfirmation is on, unless an invitation sent
|
|
125
|
-
* to that email or the first account's setup code admits it
|
|
125
|
+
* to that email or the first account's setup code admits it, or the
|
|
126
|
+
* application's confirmation mode confirms it without a link), signing in with its
|
|
126
127
|
* password (failures slow the account down, as config.signInThrottle says) or
|
|
127
128
|
* as a dev user, and renaming it.
|
|
128
129
|
* @param {object} dependencies
|
|
@@ -175,9 +176,10 @@ function createLocalAccounts({
|
|
|
175
176
|
const profileOptions = await resolveRegistrationProfileOptions(invitationContextResolver, input.invitation, email);
|
|
176
177
|
if (!config.selfRegistration) await admitClosedRegistration(profileOptions);
|
|
177
178
|
const password = await passwords.hashPassword(input.password);
|
|
178
|
-
// The first account, admitted by the setup code only the operator can read, and an invited person need no link
|
|
179
|
+
// The first account, admitted by the setup code only the operator can read, and an invited person need no link,
|
|
180
|
+
// nor does a registration the application's confirmation mode chose to confirm without one.
|
|
179
181
|
const emailProven = firstAccount || invitationProvesEmail(profileOptions.invitation, email);
|
|
180
|
-
if (config.emailConfirmation && !emailProven) {
|
|
182
|
+
if (config.emailConfirmation && !emailProven && !(await emailConfirmation.confirmsWithoutLink(email))) {
|
|
181
183
|
return emailConfirmation.begin({ email, displayName, password, invitation: normalizeInvitationInput(input.invitation) });
|
|
182
184
|
}
|
|
183
185
|
const result = await backend.withTransaction(async (tx) => {
|
package/src/server/lib/config.js
CHANGED
|
@@ -45,6 +45,29 @@ function resolveSessionSecret(env, { storeDir, isProduction }) {
|
|
|
45
45
|
return generated;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/** The fewest characters AUTH_LOCAL_SECOND_FACTOR_KEY may have. */
|
|
49
|
+
const SECOND_FACTOR_KEY_MIN_CHARACTERS = 32;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* AUTH_LOCAL_SECOND_FACTOR_KEY: the application's key, from which local auth
|
|
53
|
+
* derives the keys that seal authenticator secrets and hash recovery codes.
|
|
54
|
+
* Outside production the session secret stands in for it. A production server
|
|
55
|
+
* without it has no second factor (""); one shorter than 32 characters stops
|
|
56
|
+
* startup.
|
|
57
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
58
|
+
* @param {{ isProduction: boolean, sessionSecret: string }} options
|
|
59
|
+
*/
|
|
60
|
+
function resolveSecondFactorKey(env, { isProduction, sessionSecret }) {
|
|
61
|
+
const key = String(env.AUTH_LOCAL_SECOND_FACTOR_KEY || "").trim();
|
|
62
|
+
if (key) {
|
|
63
|
+
if (key.length < SECOND_FACTOR_KEY_MIN_CHARACTERS) {
|
|
64
|
+
throw new Error(`AUTH_LOCAL_SECOND_FACTOR_KEY must have at least ${SECOND_FACTOR_KEY_MIN_CHARACTERS} characters.`);
|
|
65
|
+
}
|
|
66
|
+
return key;
|
|
67
|
+
}
|
|
68
|
+
return isProduction ? "" : sessionSecret;
|
|
69
|
+
}
|
|
70
|
+
|
|
48
71
|
/**
|
|
49
72
|
* AUTH_LOCAL_SETUP_CODE: the first account's setup code when a hosting tool
|
|
50
73
|
* supplies it, so that every start and every server asks for the same code.
|
|
@@ -63,11 +86,13 @@ function resolveSetupCode(env, { isProduction }) {
|
|
|
63
86
|
|
|
64
87
|
/**
|
|
65
88
|
* APP_PUBLIC_URL, from which recovery and confirmation links and OAuth
|
|
66
|
-
* redirect addresses are built
|
|
89
|
+
* redirect addresses are built, and whose host authenticator apps show beside
|
|
90
|
+
* a second factor's codes. Emailed links, OAuth sign-in and a production
|
|
91
|
+
* server's second factor require it.
|
|
67
92
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
68
|
-
* @param {{ emailRecovery: boolean, emailedConfirmation: boolean, oauthEnabled: boolean }} options
|
|
93
|
+
* @param {{ emailRecovery: boolean, emailedConfirmation: boolean, oauthEnabled: boolean, productionSecondFactor: boolean }} options
|
|
69
94
|
*/
|
|
70
|
-
function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEnabled }) {
|
|
95
|
+
function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEnabled, productionSecondFactor }) {
|
|
71
96
|
const configured = String(env.APP_PUBLIC_URL || "").trim();
|
|
72
97
|
if (!configured) {
|
|
73
98
|
if (emailRecovery) throw new Error("APP_PUBLIC_URL is required when local auth email recovery is configured.");
|
|
@@ -75,6 +100,9 @@ function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEna
|
|
|
75
100
|
throw new Error("APP_PUBLIC_URL is required when local auth emails confirmation links.");
|
|
76
101
|
}
|
|
77
102
|
if (oauthEnabled) throw new Error("APP_PUBLIC_URL is required when local auth OAuth sign-in is configured.");
|
|
103
|
+
if (productionSecondFactor) {
|
|
104
|
+
throw new Error("APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set: authenticator apps show its host.");
|
|
105
|
+
}
|
|
78
106
|
return "http://localhost:5173";
|
|
79
107
|
}
|
|
80
108
|
let parsed;
|
|
@@ -177,17 +205,23 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
|
|
|
177
205
|
// resolves, or as the first account.
|
|
178
206
|
const selfRegistration = parseBooleanFlag(env.AUTH_LOCAL_SELF_REGISTRATION, true);
|
|
179
207
|
const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction, selfRegistration });
|
|
208
|
+
const sessionSecret = resolveSessionSecret(env, { storeDir, isProduction });
|
|
209
|
+
const secondFactorKey = resolveSecondFactorKey(env, { isProduction, sessionSecret });
|
|
210
|
+
const appPublicUrl = resolveAppPublicUrl(env, {
|
|
211
|
+
emailRecovery,
|
|
212
|
+
emailedConfirmation: confirmationDelivery === "email",
|
|
213
|
+
oauthEnabled,
|
|
214
|
+
productionSecondFactor: isProduction && Boolean(secondFactorKey)
|
|
215
|
+
});
|
|
180
216
|
return Object.freeze({
|
|
181
217
|
storeDir,
|
|
182
218
|
isProduction,
|
|
183
|
-
appPublicUrl
|
|
184
|
-
emailRecovery,
|
|
185
|
-
emailedConfirmation: confirmationDelivery === "email",
|
|
186
|
-
oauthEnabled
|
|
187
|
-
}),
|
|
219
|
+
appPublicUrl,
|
|
188
220
|
oauthProviders,
|
|
189
221
|
oauthEnabled,
|
|
190
|
-
sessionSecret
|
|
222
|
+
sessionSecret,
|
|
223
|
+
// "" when the server has no second factor.
|
|
224
|
+
secondFactorKey,
|
|
191
225
|
setupCode: resolveSetupCode(env, { isProduction }),
|
|
192
226
|
recoveryDelivery,
|
|
193
227
|
recoveryEnabled: recoveryDelivery !== "disabled",
|
|
@@ -5,6 +5,17 @@ import { buildAuthPayload } from "./authPayloads.js";
|
|
|
5
5
|
import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url } from "./tokens.js";
|
|
6
6
|
|
|
7
7
|
const CONFIRMATION_TOKEN_TTL_SECONDS = 24 * 60 * 60;
|
|
8
|
+
const CONFIRM_BY_LINK = "link";
|
|
9
|
+
const CONFIRM_WITHOUT_LINK = "without-link";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The confirmation mode while no `auth.local.confirmation-mode` is installed:
|
|
13
|
+
* every registration waits for its link.
|
|
14
|
+
* @type {import("../types.js").AuthLocalConfirmationMode}
|
|
15
|
+
*/
|
|
16
|
+
async function confirmEveryRegistrationByLink() {
|
|
17
|
+
return CONFIRM_BY_LINK;
|
|
18
|
+
}
|
|
8
19
|
|
|
9
20
|
/**
|
|
10
21
|
* The confirmation sender while no `auth.local.confirmation-sender` is
|
|
@@ -64,15 +75,19 @@ function confirmationPasswordInvalidError() {
|
|
|
64
75
|
* after a day; asking for a new link replaces it, and registering the email again replaces the waiting registration
|
|
65
76
|
* whole, so a waiting registration never keeps the email from its owner. Confirming needs the link and the waiting
|
|
66
77
|
* registration's password: the link proves the email and the password proves the registration, so whoever registered
|
|
67
|
-
* an email, in whatever order, the account its link creates has a password the person confirming chose.
|
|
78
|
+
* an email, in whatever order, the account its link creates has a password the person confirming chose. The
|
|
79
|
+
* application's confirmation mode may instead confirm a registration without a link (confirmsWithoutLink).
|
|
68
80
|
* @param {object} dependencies
|
|
69
81
|
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
70
82
|
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
83
|
+
* @param {import("../types.js").AuthLocalConfirmationMode} dependencies.confirmationMode The
|
|
84
|
+
* `auth.local.confirmation-mode`, or confirmEveryRegistrationByLink.
|
|
71
85
|
* @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
|
|
72
86
|
* @param {import("../types.js").AuthLocalFirstAccountSetup} dependencies.firstAccountSetup
|
|
73
87
|
* @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
|
|
74
88
|
* `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender;
|
|
75
89
|
* in development without a sender, links also go in the response.
|
|
90
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
76
91
|
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
77
92
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
78
93
|
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
@@ -80,9 +95,11 @@ function confirmationPasswordInvalidError() {
|
|
|
80
95
|
function createLocalEmailConfirmation({
|
|
81
96
|
backend,
|
|
82
97
|
config,
|
|
98
|
+
confirmationMode,
|
|
83
99
|
confirmationSender,
|
|
84
100
|
firstAccountSetup,
|
|
85
101
|
invitationContextResolver,
|
|
102
|
+
logger,
|
|
86
103
|
passwords,
|
|
87
104
|
profileProjector,
|
|
88
105
|
sessions
|
|
@@ -106,6 +123,23 @@ function createLocalEmailConfirmation({
|
|
|
106
123
|
return confirmationDelivery === "dev-response" ? { confirmationUrl } : {};
|
|
107
124
|
}
|
|
108
125
|
|
|
126
|
+
/**
|
|
127
|
+
* True when the application's confirmation mode answers exactly "without-link" for this registration: it chose to
|
|
128
|
+
* create the account without proof of the address. Any other answer is a link; one that is neither answer is
|
|
129
|
+
* logged, since the application meant something else.
|
|
130
|
+
* @param {string} email
|
|
131
|
+
*/
|
|
132
|
+
async function confirmsWithoutLink(email) {
|
|
133
|
+
const mode = await confirmationMode({ email });
|
|
134
|
+
if (mode !== CONFIRM_BY_LINK && mode !== CONFIRM_WITHOUT_LINK) {
|
|
135
|
+
logger.warn(
|
|
136
|
+
{ mode: typeof mode === "string" ? mode : typeof mode },
|
|
137
|
+
'auth.local.confirmation-mode answered neither "link" nor "without-link", so the registration waits for its link.'
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
return mode === CONFIRM_WITHOUT_LINK;
|
|
141
|
+
}
|
|
142
|
+
|
|
109
143
|
/**
|
|
110
144
|
* Keeps a registration, already validated and with its password hashed,
|
|
111
145
|
* until its email is confirmed. It replaces a registration already waiting
|
|
@@ -221,6 +255,7 @@ function createLocalEmailConfirmation({
|
|
|
221
255
|
}
|
|
222
256
|
|
|
223
257
|
return Object.freeze({
|
|
258
|
+
confirmsWithoutLink,
|
|
224
259
|
begin,
|
|
225
260
|
confirm,
|
|
226
261
|
resend,
|
|
@@ -230,6 +265,7 @@ function createLocalEmailConfirmation({
|
|
|
230
265
|
|
|
231
266
|
export {
|
|
232
267
|
CONFIRMATION_TOKEN_TTL_SECONDS,
|
|
268
|
+
confirmEveryRegistrationByLink,
|
|
233
269
|
createLocalEmailConfirmation,
|
|
234
270
|
createLoggedConfirmationSender,
|
|
235
271
|
createSimulatedConfirmationSender
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
parseOAuthAttempts,
|
|
7
7
|
parseRecovery,
|
|
8
8
|
parseRegistrations,
|
|
9
|
+
parseSecondFactors,
|
|
9
10
|
parseSessions,
|
|
10
11
|
parseSignInFailures,
|
|
11
12
|
parseUsers,
|
|
@@ -13,6 +14,7 @@ import {
|
|
|
13
14
|
serializeOAuthAttempts,
|
|
14
15
|
serializeRecovery,
|
|
15
16
|
serializeRegistrations,
|
|
17
|
+
serializeSecondFactors,
|
|
16
18
|
serializeSessions,
|
|
17
19
|
serializeSignInFailures,
|
|
18
20
|
serializeUsers
|
|
@@ -25,6 +27,7 @@ const IDENTITY_FILE = "identities.passwd";
|
|
|
25
27
|
const OAUTH_ATTEMPT_FILE = "oauth-attempts.passwd";
|
|
26
28
|
const SIGN_IN_FAILURE_FILE = "sign-in-failures.passwd";
|
|
27
29
|
const REGISTRATION_FILE = "registrations.passwd";
|
|
30
|
+
const SECOND_FACTOR_FILE = "second-factors.passwd";
|
|
28
31
|
const LOCK_FILE = "store.lock";
|
|
29
32
|
const JOURNAL_FILE = "transaction.journal";
|
|
30
33
|
const LOCK_STALE_MS = 30_000;
|
|
@@ -81,7 +84,16 @@ function parseJournal(content) {
|
|
|
81
84
|
}
|
|
82
85
|
return parsed.files.map((entry) => {
|
|
83
86
|
const name = String(entry?.name || "").trim();
|
|
84
|
-
const files = [
|
|
87
|
+
const files = [
|
|
88
|
+
USER_FILE,
|
|
89
|
+
SESSION_FILE,
|
|
90
|
+
RECOVERY_FILE,
|
|
91
|
+
IDENTITY_FILE,
|
|
92
|
+
OAUTH_ATTEMPT_FILE,
|
|
93
|
+
SIGN_IN_FAILURE_FILE,
|
|
94
|
+
REGISTRATION_FILE,
|
|
95
|
+
SECOND_FACTOR_FILE
|
|
96
|
+
];
|
|
85
97
|
if (!files.includes(name)) {
|
|
86
98
|
throw new Error("Invalid local auth transaction journal file.");
|
|
87
99
|
}
|
|
@@ -252,7 +264,8 @@ function createTx(state, touched) {
|
|
|
252
264
|
...clone(input),
|
|
253
265
|
purpose: input.purpose || "normal",
|
|
254
266
|
createdAt: input.createdAt || nowIso(),
|
|
255
|
-
revokedAt: input.revokedAt || ""
|
|
267
|
+
revokedAt: input.revokedAt || "",
|
|
268
|
+
secondFactorAt: input.secondFactorAt || ""
|
|
256
269
|
};
|
|
257
270
|
state.sessions.push(session);
|
|
258
271
|
mark("sessions");
|
|
@@ -286,6 +299,28 @@ function createTx(state, touched) {
|
|
|
286
299
|
mark("sessions");
|
|
287
300
|
}
|
|
288
301
|
return count;
|
|
302
|
+
},
|
|
303
|
+
async markSecondFactorProved(sessionId, secondFactorAt) {
|
|
304
|
+
const session = state.sessions.find((entry) => entry.id === sessionId);
|
|
305
|
+
if (!session) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
session.secondFactorAt = secondFactorAt;
|
|
309
|
+
mark("sessions");
|
|
310
|
+
return clone(session);
|
|
311
|
+
},
|
|
312
|
+
async clearSecondFactorForUser(userId) {
|
|
313
|
+
let count = 0;
|
|
314
|
+
for (const session of state.sessions) {
|
|
315
|
+
if (session.userId === userId && session.secondFactorAt) {
|
|
316
|
+
session.secondFactorAt = "";
|
|
317
|
+
count += 1;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (count > 0) {
|
|
321
|
+
mark("sessions");
|
|
322
|
+
}
|
|
323
|
+
return count;
|
|
289
324
|
}
|
|
290
325
|
}),
|
|
291
326
|
recovery: Object.freeze({
|
|
@@ -421,6 +456,33 @@ function createTx(state, touched) {
|
|
|
421
456
|
return count;
|
|
422
457
|
}
|
|
423
458
|
}),
|
|
459
|
+
secondFactors: Object.freeze({
|
|
460
|
+
// The store lock holds every record until the transaction ends.
|
|
461
|
+
async find(userId) {
|
|
462
|
+
return clone(state.secondFactors.find((record) => record.userId === userId) || null);
|
|
463
|
+
},
|
|
464
|
+
async findMany(userIds) {
|
|
465
|
+
const wanted = new Set(userIds);
|
|
466
|
+
return clone(state.secondFactors.filter((record) => wanted.has(record.userId)));
|
|
467
|
+
},
|
|
468
|
+
async save(record) {
|
|
469
|
+
state.secondFactors = [
|
|
470
|
+
...state.secondFactors.filter((entry) => entry.userId !== record.userId),
|
|
471
|
+
clone(record)
|
|
472
|
+
];
|
|
473
|
+
mark("secondFactors");
|
|
474
|
+
return clone(record);
|
|
475
|
+
},
|
|
476
|
+
async delete(userId) {
|
|
477
|
+
const before = state.secondFactors.length;
|
|
478
|
+
state.secondFactors = state.secondFactors.filter((entry) => entry.userId !== userId);
|
|
479
|
+
const count = before - state.secondFactors.length;
|
|
480
|
+
if (count > 0) {
|
|
481
|
+
mark("secondFactors");
|
|
482
|
+
}
|
|
483
|
+
return count;
|
|
484
|
+
}
|
|
485
|
+
}),
|
|
424
486
|
registrations: Object.freeze({
|
|
425
487
|
async save(record) {
|
|
426
488
|
state.registrations = [
|
|
@@ -473,7 +535,8 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
473
535
|
identities: parseIdentities(await readText(path.join(resolvedStoreDir, IDENTITY_FILE))),
|
|
474
536
|
oauthAttempts: parseOAuthAttempts(await readText(path.join(resolvedStoreDir, OAUTH_ATTEMPT_FILE))),
|
|
475
537
|
signInFailures: parseSignInFailures(await readText(path.join(resolvedStoreDir, SIGN_IN_FAILURE_FILE))),
|
|
476
|
-
registrations: parseRegistrations(await readText(path.join(resolvedStoreDir, REGISTRATION_FILE)))
|
|
538
|
+
registrations: parseRegistrations(await readText(path.join(resolvedStoreDir, REGISTRATION_FILE))),
|
|
539
|
+
secondFactors: parseSecondFactors(await readText(path.join(resolvedStoreDir, SECOND_FACTOR_FILE)))
|
|
477
540
|
};
|
|
478
541
|
const touched = new Set();
|
|
479
542
|
const result = await callback(createTx(state, touched));
|
|
@@ -520,6 +583,12 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
520
583
|
content: serializeRegistrations(state.registrations)
|
|
521
584
|
});
|
|
522
585
|
}
|
|
586
|
+
if (touched.has("secondFactors")) {
|
|
587
|
+
commitEntries.push({
|
|
588
|
+
name: SECOND_FACTOR_FILE,
|
|
589
|
+
content: serializeSecondFactors(state.secondFactors)
|
|
590
|
+
});
|
|
591
|
+
}
|
|
523
592
|
if (commitEntries.length > 0) {
|
|
524
593
|
await writeCommitJournal(resolvedStoreDir, commitEntries);
|
|
525
594
|
for (const entry of commitEntries) {
|
|
@@ -68,7 +68,8 @@ function parseSessions(content) {
|
|
|
68
68
|
const sessions = [];
|
|
69
69
|
for (const line of String(content || "").split("\n").filter(Boolean)) {
|
|
70
70
|
const parts = splitLine(line, "session");
|
|
71
|
-
|
|
71
|
+
// A session written before second factors has no tenth field: it has not proved one.
|
|
72
|
+
if (parts.length !== 9 && parts.length !== 10) {
|
|
72
73
|
throw new Error("Invalid session record field count.");
|
|
73
74
|
}
|
|
74
75
|
sessions.push({
|
|
@@ -78,7 +79,8 @@ function parseSessions(content) {
|
|
|
78
79
|
purpose: parts[5] || "normal",
|
|
79
80
|
createdAt: decodeField(parts[6]),
|
|
80
81
|
expiresAt: decodeField(parts[7]),
|
|
81
|
-
revokedAt: decodeField(parts[8] || "")
|
|
82
|
+
revokedAt: decodeField(parts[8] || ""),
|
|
83
|
+
secondFactorAt: decodeField(parts[9] || "")
|
|
82
84
|
});
|
|
83
85
|
}
|
|
84
86
|
return sessions;
|
|
@@ -97,7 +99,8 @@ function serializeSessions(sessions) {
|
|
|
97
99
|
session.purpose || "normal",
|
|
98
100
|
encodeField(session.createdAt),
|
|
99
101
|
encodeField(session.expiresAt),
|
|
100
|
-
encodeField(session.revokedAt || "")
|
|
102
|
+
encodeField(session.revokedAt || ""),
|
|
103
|
+
encodeField(session.secondFactorAt || "")
|
|
101
104
|
].join(":")
|
|
102
105
|
)
|
|
103
106
|
.join("\n") + (sessions.length > 0 ? "\n" : "");
|
|
@@ -254,6 +257,54 @@ function serializeSignInFailures(records) {
|
|
|
254
257
|
.join("\n") + (records.length > 0 ? "\n" : "");
|
|
255
258
|
}
|
|
256
259
|
|
|
260
|
+
// An account's second factor: its sealed authenticator secret, when the first code confirmed it ("" while it is being
|
|
261
|
+
// set up), the step of the last code accepted, the hashes of its unused recovery codes (comma-separated), and its
|
|
262
|
+
// failed attempts as sign-in failures count them.
|
|
263
|
+
function parseSecondFactors(content) {
|
|
264
|
+
const records = [];
|
|
265
|
+
for (const line of String(content || "").split("\n").filter(Boolean)) {
|
|
266
|
+
const parts = splitLine(line, "second_factor");
|
|
267
|
+
if (parts.length !== 12) {
|
|
268
|
+
throw new Error("Invalid second factor record field count.");
|
|
269
|
+
}
|
|
270
|
+
records.push({
|
|
271
|
+
userId: parts[2],
|
|
272
|
+
secretSealed: parts[3],
|
|
273
|
+
confirmedAt: decodeField(parts[4]),
|
|
274
|
+
lastUsedStep: Number(parts[5]),
|
|
275
|
+
recoveryCodes: parts[6] ? parts[6].split(",") : [],
|
|
276
|
+
failures: Number(parts[7]),
|
|
277
|
+
lastFailedAt: decodeField(parts[8]),
|
|
278
|
+
lockedUntil: decodeField(parts[9]),
|
|
279
|
+
createdAt: decodeField(parts[10]),
|
|
280
|
+
updatedAt: decodeField(parts[11])
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
return records;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function serializeSecondFactors(records) {
|
|
287
|
+
return [...records]
|
|
288
|
+
.sort((left, right) => String(left.userId).localeCompare(String(right.userId)))
|
|
289
|
+
.map((record) =>
|
|
290
|
+
[
|
|
291
|
+
"second_factor",
|
|
292
|
+
"v1",
|
|
293
|
+
record.userId,
|
|
294
|
+
record.secretSealed,
|
|
295
|
+
encodeField(record.confirmedAt || ""),
|
|
296
|
+
String(record.lastUsedStep || 0),
|
|
297
|
+
record.recoveryCodes.join(","),
|
|
298
|
+
String(record.failures || 0),
|
|
299
|
+
encodeField(record.lastFailedAt || ""),
|
|
300
|
+
encodeField(record.lockedUntil || ""),
|
|
301
|
+
encodeField(record.createdAt),
|
|
302
|
+
encodeField(record.updatedAt)
|
|
303
|
+
].join(":")
|
|
304
|
+
)
|
|
305
|
+
.join("\n") + (records.length > 0 ? "\n" : "");
|
|
306
|
+
}
|
|
307
|
+
|
|
257
308
|
// A registration waiting for its email to be confirmed; the invitation fields
|
|
258
309
|
// are empty when it came without one.
|
|
259
310
|
function parseRegistrations(content) {
|
|
@@ -310,6 +361,7 @@ export {
|
|
|
310
361
|
parseOAuthAttempts,
|
|
311
362
|
parseRecovery,
|
|
312
363
|
parseRegistrations,
|
|
364
|
+
parseSecondFactors,
|
|
313
365
|
parseSessions,
|
|
314
366
|
parseSignInFailures,
|
|
315
367
|
parseUsers,
|
|
@@ -317,6 +369,7 @@ export {
|
|
|
317
369
|
serializeOAuthAttempts,
|
|
318
370
|
serializeRecovery,
|
|
319
371
|
serializeRegistrations,
|
|
372
|
+
serializeSecondFactors,
|
|
320
373
|
serializeSessions,
|
|
321
374
|
serializeSignInFailures,
|
|
322
375
|
serializeUsers
|
package/src/server/lib/index.js
CHANGED
|
@@ -3,6 +3,7 @@ export { resolveLocalAuthConfig } from "./config.js";
|
|
|
3
3
|
export { createLoggedConfirmationSender } from "./emailConfirmation.js";
|
|
4
4
|
export { createLoggedRecoverySender } from "./passwordFlows.js";
|
|
5
5
|
export { createLocalFileBackend } from "./fileBackend.js";
|
|
6
|
+
export { createLoggedSecondFactorEvents } from "./secondFactor.js";
|
|
6
7
|
export { SETUP_CODE_ENV, SETUP_CODE_FILE, createFirstAccountSetup } from "./firstAccountSetup.js";
|
|
7
8
|
export {
|
|
8
9
|
LOCAL_AUTH_USER_REGISTERED_EVENT,
|