@jskit-ai/auth-provider-local-core 0.2.16 → 0.2.18
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 -1
- package/locales/en.json +4 -0
- package/package.json +3 -3
- package/src/server/lib/emailConfirmation.js +32 -7
- package/src/server/lib/fileBackend.js +8 -4
- package/src/server/lib/passwordFlows.js +15 -8
- package/src/server/lib/service.js +1 -0
- package/src/server/types.js +9 -5
- package/test/codedTexts.test.js +11 -0
- package/test/emailConfirmation.test.js +7 -2
- package/test/firstAccountSetup.test.js +1 -1
- package/test/oauthSignIn.test.js +2 -2
- package/test/profileSync.test.js +2 -2
- package/test/providerRuntime.test.js +29 -3
- package/test-support/emailConfirmationScenario.js +70 -24
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- 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.
|
|
6
|
+
- Security: confirming a registration takes the password it was registered with as well as its link's code, `confirmRegistration({ token, password })`. A missing or wrong password creates nothing, keeps the registration and its link, and is refused with 400 `auth.local.register.confirmationPasswordInvalid` (on the `password` field; new message key `jskit.auth.local.register.confirmationPasswordInvalid`). Registering an email again replaces its waiting registration whole, password, display name and invitation included, and a new link from `resendRegisterConfirmation` keeps the registration's password and is no longer sent for an expired registration. So whoever registers an email, before its owner or after, the account its link creates has the password of the person who confirmed it: before, a registration that waited kept its password when the email's owner registered later, so whoever registered first could sign in to the account the owner then confirmed, and the owner's link created no account they could tell apart.
|
|
7
|
+
- The file backend refuses a second account with a taken id or email with a `ConflictError` (409) coded `auth.local.accounts.exists` ("An account with this id or email already exists."), where it threw a plain `Error` with no code, so a caller that retries on a duplicate can recognise it.
|
|
5
8
|
- The local file backend takes over a store lock left by a crashed process (older than 30 s, its process gone) at its first attempt, instead of after waiting out the 2 s lock timeout. A lock whose process is alive is still never removed, however old.
|
|
6
9
|
- A request authenticates once. The route's auth policy and the handlers it runs (`getSecurityStatus`, `updateDisplayName`, `changePassword`, `signOutOtherSessions`, `startProviderLink`, `unlinkProvider`, an OAuth link) share the first `authenticateRequest()` answer for the same request object, instead of reading the session, the user and the app profile again each time. A display name change updates that answer's actor. `logout`, `signOutOtherSessions` and `resetPassword` forget it, so a later check in the same request reads the sessions again. Every new request still reads its session and user, so sign-out, revocation and disabling take effect from the next request. A failed authentication is not remembered, and a `syncProfile: false` check is never shared.
|
|
7
10
|
- An ordinary request synchronizes the app profile only when it is missing or its email or display name no longer matches the user (`onlyWhenChanged`); its session and user are still read on every request, so sign-out, revocation and disabling take effect at once. Sign-in, registration and a session refresh (every 15 minutes, when the access token has expired) synchronize in full, which also re-runs workspace provisioning. Measured in apps, every signed-in request ran a second transaction for the sync: GET /api/session 8 statements, GET /api/settings 21 (two authentications), PATCH /api/settings/profile 52. Visible difference: a personal workspace, owner membership or settings row deleted while someone is signed in comes back at their next refresh or sign-in instead of their next request.
|
|
@@ -11,7 +14,7 @@
|
|
|
11
14
|
- 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`.
|
|
12
15
|
- Upgrading: a custom `auth.local.backend` implements `users.hasAny()`.
|
|
13
16
|
- 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.
|
|
14
|
-
- 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`.
|
|
17
|
+
- 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, password })` 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`.
|
|
15
18
|
- 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.
|
|
16
19
|
- 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.
|
|
17
20
|
- 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.
|
package/locales/en.json
CHANGED
|
@@ -10,10 +10,14 @@
|
|
|
10
10
|
"currentInvalid": "Current password is invalid.",
|
|
11
11
|
"changed": "Password updated."
|
|
12
12
|
},
|
|
13
|
+
"accounts": {
|
|
14
|
+
"exists": "An account with this id or email already exists."
|
|
15
|
+
},
|
|
13
16
|
"register": {
|
|
14
17
|
"emailTaken": "An account already exists for this email.",
|
|
15
18
|
"closed": "This app's accounts are by invitation only.",
|
|
16
19
|
"confirmationInvalid": "This confirmation link is invalid or has expired. Register again to get a new one.",
|
|
20
|
+
"confirmationPasswordInvalid": "That is not the password this registration was made with. Enter the password you registered with, or register again.",
|
|
17
21
|
"confirmationResent": "If a registration is waiting for that email, a new confirmation link has been sent."
|
|
18
22
|
},
|
|
19
23
|
"setup": {
|
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.18",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
}
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"@jskit-ai/auth-core": "0.2.
|
|
71
|
-
"@jskit-ai/kernel": "0.2.
|
|
70
|
+
"@jskit-ai/auth-core": "0.2.15",
|
|
71
|
+
"@jskit-ai/kernel": "0.2.15"
|
|
72
72
|
}
|
|
73
73
|
}
|
|
@@ -27,11 +27,26 @@ function confirmationInvalidError() {
|
|
|
27
27
|
});
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
function confirmationPasswordInvalidError() {
|
|
31
|
+
const code = "auth.local.register.confirmationPasswordInvalid";
|
|
32
|
+
const message = "That is not the password this registration was made with. Enter the password you registered with, or register again.";
|
|
33
|
+
return new AppError(400, message, {
|
|
34
|
+
code,
|
|
35
|
+
details: {
|
|
36
|
+
fieldErrors: { password: message },
|
|
37
|
+
fieldErrorCodes: { password: { code, params: {} } }
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
30
42
|
/**
|
|
31
43
|
* Registration with email confirmation: registering keeps the account waiting,
|
|
32
44
|
* with no account, profile or session, until the link sent to its email is
|
|
33
45
|
* 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;
|
|
46
|
+
* after a day; asking for a new link replaces it, and registering the email again replaces the waiting registration
|
|
47
|
+
* whole, so a waiting registration never keeps the email from its owner. Confirming needs the link and the waiting
|
|
48
|
+
* registration's password: the link proves the email and the password proves the registration, so whoever registered
|
|
49
|
+
* an email, in whatever order, the account its link creates has a password the person confirming chose.
|
|
35
50
|
* @param {object} dependencies
|
|
36
51
|
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
37
52
|
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
@@ -40,6 +55,7 @@ function confirmationInvalidError() {
|
|
|
40
55
|
* @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
|
|
41
56
|
* `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender;
|
|
42
57
|
* in development without a sender, links also go in the response.
|
|
58
|
+
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
43
59
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
44
60
|
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
45
61
|
*/
|
|
@@ -49,6 +65,7 @@ function createLocalEmailConfirmation({
|
|
|
49
65
|
confirmationSender,
|
|
50
66
|
firstAccountSetup,
|
|
51
67
|
invitationContextResolver,
|
|
68
|
+
passwords,
|
|
52
69
|
profileProjector,
|
|
53
70
|
sessions
|
|
54
71
|
}) {
|
|
@@ -73,7 +90,8 @@ function createLocalEmailConfirmation({
|
|
|
73
90
|
|
|
74
91
|
/**
|
|
75
92
|
* Keeps a registration, already validated and with its password hashed,
|
|
76
|
-
* until its email is confirmed.
|
|
93
|
+
* until its email is confirmed. It replaces a registration already waiting
|
|
94
|
+
* for that email, and that registration's link.
|
|
77
95
|
* @param {{ email: string, displayName: string, password: object, invitation: object | null }} registration
|
|
78
96
|
*/
|
|
79
97
|
async function begin({ email, displayName, password, invitation }) {
|
|
@@ -97,8 +115,9 @@ function createLocalEmailConfirmation({
|
|
|
97
115
|
|
|
98
116
|
/**
|
|
99
117
|
* Creates the account a registration was waiting to create, from its link's
|
|
100
|
-
* code, and signs the person in.
|
|
101
|
-
*
|
|
118
|
+
* code and the password it registered with, and signs the person in. A wrong
|
|
119
|
+
* password creates nothing and keeps the registration and its link.
|
|
120
|
+
* @param {{ token: string, password: string }} input
|
|
102
121
|
*/
|
|
103
122
|
async function confirm(input) {
|
|
104
123
|
const tokenHash = sha256Base64url(String(input.token || "").trim());
|
|
@@ -106,12 +125,16 @@ function createLocalEmailConfirmation({
|
|
|
106
125
|
if (!waiting || isExpiredIso(waiting.expiresAt)) {
|
|
107
126
|
throw confirmationInvalidError();
|
|
108
127
|
}
|
|
128
|
+
if (!(await passwords.verifyPassword(String(input.password || ""), waiting.password))) {
|
|
129
|
+
throw confirmationPasswordInvalidError();
|
|
130
|
+
}
|
|
109
131
|
const profileOptions = await resolveRegistrationProfileOptions(
|
|
110
132
|
invitationContextResolver,
|
|
111
133
|
waiting.invitation,
|
|
112
134
|
waiting.email
|
|
113
135
|
);
|
|
114
136
|
const outcome = await backend.withTransaction(async (tx) => {
|
|
137
|
+
// Every save gives a registration a new link code, so the one this code still finds has the password just checked.
|
|
115
138
|
const registration = await tx.registrations.findByTokenHash(tokenHash);
|
|
116
139
|
if (!registration || isExpiredIso(registration.expiresAt)) {
|
|
117
140
|
return { invalid: true };
|
|
@@ -140,8 +163,10 @@ function createLocalEmailConfirmation({
|
|
|
140
163
|
}
|
|
141
164
|
|
|
142
165
|
/**
|
|
143
|
-
* Sends a waiting registration a new link, which replaces the old one
|
|
144
|
-
*
|
|
166
|
+
* Sends a waiting registration a new link, which replaces the old one; the
|
|
167
|
+
* registration, its password included, stays as it is. An expired
|
|
168
|
+
* registration no longer waits: it registers again. The answer is the same
|
|
169
|
+
* whether or not a registration waits for that email.
|
|
145
170
|
* @param {{ email: string }} input
|
|
146
171
|
*/
|
|
147
172
|
async function resend(input) {
|
|
@@ -149,7 +174,7 @@ function createLocalEmailConfirmation({
|
|
|
149
174
|
const { token, tokenHash, expiresAt } = newConfirmation();
|
|
150
175
|
const renewed = await backend.withTransaction(async (tx) => {
|
|
151
176
|
const registration = await tx.registrations.findByEmail(email);
|
|
152
|
-
if (!registration) {
|
|
177
|
+
if (!registration || isExpiredIso(registration.expiresAt)) {
|
|
153
178
|
return false;
|
|
154
179
|
}
|
|
155
180
|
await tx.registrations.save({ ...registration, tokenHash, expiresAt });
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { ConflictError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
3
4
|
import {
|
|
4
5
|
parseIdentities,
|
|
5
6
|
parseOAuthAttempts,
|
|
@@ -201,7 +202,7 @@ function createTx(state, touched) {
|
|
|
201
202
|
users: Object.freeze({
|
|
202
203
|
async create(input) {
|
|
203
204
|
if (state.users.some((user) => user.id === input.id || user.email === input.email)) {
|
|
204
|
-
throw new
|
|
205
|
+
throw new ConflictError("An account with this id or email already exists.", { code: "auth.local.accounts.exists" });
|
|
205
206
|
}
|
|
206
207
|
const user = {
|
|
207
208
|
...clone(input),
|
|
@@ -304,16 +305,19 @@ function createTx(state, touched) {
|
|
|
304
305
|
async consume(tokenId) {
|
|
305
306
|
const record = state.recovery.find((entry) => entry.id === tokenId);
|
|
306
307
|
if (!record || record.usedAt) {
|
|
307
|
-
return
|
|
308
|
+
return null;
|
|
308
309
|
}
|
|
309
310
|
record.usedAt = nowIso();
|
|
310
311
|
mark("recovery");
|
|
311
312
|
return clone(record);
|
|
312
313
|
},
|
|
313
|
-
async consumeForUser(userId) {
|
|
314
|
+
async consumeForUser(userId, { idPrefix } = {}) {
|
|
315
|
+
if (typeof idPrefix !== "string" || !idPrefix) {
|
|
316
|
+
throw new TypeError("recovery.consumeForUser() takes the idPrefix of the tokens it consumes, such as \"rec_\".");
|
|
317
|
+
}
|
|
314
318
|
let count = 0;
|
|
315
319
|
for (const record of state.recovery) {
|
|
316
|
-
if (record.userId === userId && !record.usedAt) {
|
|
320
|
+
if (record.userId === userId && !record.usedAt && record.id.startsWith(idPrefix)) {
|
|
317
321
|
record.usedAt = nowIso();
|
|
318
322
|
count += 1;
|
|
319
323
|
}
|
|
@@ -6,6 +6,9 @@ import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url, verif
|
|
|
6
6
|
|
|
7
7
|
const RECOVERY_SESSION_TTL_SECONDS = 15 * 60;
|
|
8
8
|
const RECOVERY_TOKEN_TTL_SECONDS = 60 * 60;
|
|
9
|
+
// A password reset's recovery tokens have ids starting `rec_`, which tells them from an app's own kinds (such as a
|
|
10
|
+
// sign-in link's): completing a reset consumes the user's other resets and leaves the other kinds open.
|
|
11
|
+
const RESET_TOKEN_KIND = "rec";
|
|
9
12
|
|
|
10
13
|
/**
|
|
11
14
|
* The `auth.local.recovery-sender` default when no feature provides one: outside
|
|
@@ -49,7 +52,7 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
|
|
|
49
52
|
const token = randomToken(32);
|
|
50
53
|
recoveryUrl = `${config.appPublicUrl.replace(/\/$/, "")}/auth/reset-password?token=${encodeURIComponent(token)}&type=recovery`;
|
|
51
54
|
await tx.recovery.create({
|
|
52
|
-
id: createId(
|
|
55
|
+
id: createId(RESET_TOKEN_KIND),
|
|
53
56
|
userId: user.id,
|
|
54
57
|
tokenHash: sha256Base64url(token),
|
|
55
58
|
expiresAt: isoFromNow(RECOVERY_TOKEN_TTL_SECONDS)
|
|
@@ -71,20 +74,24 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
|
|
|
71
74
|
if (!recoveryEnabled) {
|
|
72
75
|
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
73
76
|
}
|
|
77
|
+
// Only the emailed token itself: the hash this provider stores of it never opens an account.
|
|
74
78
|
const token = String(input.code || input.token || "").trim();
|
|
75
|
-
|
|
76
|
-
if (!tokenHash) {
|
|
79
|
+
if (!token) {
|
|
77
80
|
throw createAuthError(AUTH_TEXTS.recoveryTokenRequired);
|
|
78
81
|
}
|
|
82
|
+
const tokenInvalid = () => new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
|
|
79
83
|
return backend.withTransaction(async (tx) => {
|
|
80
|
-
const recovery = await tx.recovery.findByTokenHash(
|
|
84
|
+
const recovery = await tx.recovery.findByTokenHash(sha256Base64url(token));
|
|
81
85
|
if (!recovery || recovery.usedAt || isExpiredIso(recovery.expiresAt)) {
|
|
82
|
-
throw
|
|
86
|
+
throw tokenInvalid();
|
|
87
|
+
}
|
|
88
|
+
// Of two completions with one token at once, only the one that consumes it opens a session.
|
|
89
|
+
if (!await tx.recovery.consume(recovery.id)) {
|
|
90
|
+
throw tokenInvalid();
|
|
83
91
|
}
|
|
84
|
-
await tx.recovery.consume(recovery.id);
|
|
85
92
|
const user = await tx.users.findById(recovery.userId);
|
|
86
93
|
if (!user || user.disabled) {
|
|
87
|
-
throw
|
|
94
|
+
throw tokenInvalid();
|
|
88
95
|
}
|
|
89
96
|
const session = await sessions.createSessionForUser(tx, user, {
|
|
90
97
|
purpose: "recovery",
|
|
@@ -111,7 +118,7 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
|
|
|
111
118
|
}
|
|
112
119
|
const user = await tx.users.updatePassword(String(payload.sub), password);
|
|
113
120
|
await tx.sessions.revokeForUser(String(payload.sub));
|
|
114
|
-
await tx.recovery.consumeForUser(String(payload.sub));
|
|
121
|
+
await tx.recovery.consumeForUser(String(payload.sub), { idPrefix: `${RESET_TOKEN_KIND}_` });
|
|
115
122
|
// Recovery is the way back in for an account that failed sign-ins keep waiting.
|
|
116
123
|
if (user) {
|
|
117
124
|
await tx.signInFailures.clear(user.email);
|
package/src/server/types.js
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* One transaction of a local auth backend. A find answers null when nothing
|
|
6
|
-
* matches; a bulk change answers how many records it changed.
|
|
6
|
+
* matches; a bulk change answers how many records it changed. A recovery
|
|
7
|
+
* token's kind is the start of its id (a password reset's is `rec_`), and
|
|
8
|
+
* `consumeForUser` consumes the user's unused tokens of the kind its idPrefix
|
|
9
|
+
* names, never their others.
|
|
7
10
|
* @typedef {object} AuthLocalBackendTransaction
|
|
8
11
|
* @property {{
|
|
9
12
|
* create(input: object): Promise<object>,
|
|
@@ -23,8 +26,8 @@
|
|
|
23
26
|
* @property {{
|
|
24
27
|
* create(input: object): Promise<object>,
|
|
25
28
|
* findByTokenHash(tokenHash: string): Promise<object | null>,
|
|
26
|
-
* consume(tokenId: string): Promise<object | null>,
|
|
27
|
-
* consumeForUser(userId: string): Promise<number>
|
|
29
|
+
* consume(tokenId: string): Promise<object | null>, the consumed token, or null when it is missing or already used
|
|
30
|
+
* consumeForUser(userId: string, options: { idPrefix: string }): Promise<number>
|
|
28
31
|
* }} recovery
|
|
29
32
|
* @property {{
|
|
30
33
|
* create(input: object): Promise<object>,
|
|
@@ -42,8 +45,9 @@
|
|
|
42
45
|
* save(record: AuthLocalSignInFailures): Promise<AuthLocalSignInFailures>,
|
|
43
46
|
* clear(email: string): Promise<number>,
|
|
44
47
|
* deleteBefore(lastFailedAt: string): Promise<number>
|
|
45
|
-
* }} signInFailures One record per account email, existing or not; `
|
|
46
|
-
*
|
|
48
|
+
* }} signInFailures One record per account email, existing or not; `find` holds the email's record until the
|
|
49
|
+
* transaction ends, so concurrent failures count one after another, `save` replaces the email's record and
|
|
50
|
+
* `deleteBefore` removes those whose last failure is older.
|
|
47
51
|
* @property {{
|
|
48
52
|
* save(record: AuthLocalRegistration): Promise<AuthLocalRegistration>,
|
|
49
53
|
* findByEmail(email: string): Promise<AuthLocalRegistration | null>,
|
package/test/codedTexts.test.js
CHANGED
|
@@ -51,9 +51,20 @@ test("local auth errors carry codes whose English is the thrown message", async
|
|
|
51
51
|
(error) => assertCoded(error, "auth.recovery.tokenRequired"));
|
|
52
52
|
await assert.rejects(() => service.completePasswordRecovery({ token: "unknown" }),
|
|
53
53
|
(error) => assertCoded(error, "auth.local.recovery.tokenInvalid"));
|
|
54
|
+
// A stored token hash is not the token: it never completes a recovery.
|
|
55
|
+
await assert.rejects(() => service.completePasswordRecovery({ tokenHash: "stored-hash" }),
|
|
56
|
+
(error) => assertCoded(error, "auth.recovery.tokenRequired"));
|
|
54
57
|
await assert.rejects(() => service.updateDisplayName({ cookies: {} }, { displayName: "Ada" }),
|
|
55
58
|
(error) => assertCoded(error, "auth.session.required"));
|
|
56
59
|
|
|
60
|
+
const confirming = await createService(t, { AUTH_LOCAL_EMAIL_CONFIRMATION: "" });
|
|
61
|
+
const waiting = await confirming.register({ email: "ada@example.com", password: "correct horse" });
|
|
62
|
+
const token = new URL(waiting.confirmationUrl).searchParams.get("confirmation_token");
|
|
63
|
+
await assert.rejects(() => confirming.confirmRegistration({ token: "unknown", password: "correct horse" }),
|
|
64
|
+
(error) => assertCoded(error, "auth.local.register.confirmationInvalid"));
|
|
65
|
+
await assert.rejects(() => confirming.confirmRegistration({ token, password: "wrong password" }),
|
|
66
|
+
(error) => assertCoded(error, "auth.local.register.confirmationPasswordInvalid"));
|
|
67
|
+
|
|
57
68
|
const disabled = await createService(t, { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" });
|
|
58
69
|
await assert.rejects(() => disabled.requestPasswordReset({ email: "ada@example.com" }),
|
|
59
70
|
(error) => assertCoded(error, "auth.local.recovery.notConfigured"));
|
|
@@ -6,7 +6,7 @@ import test from "node:test";
|
|
|
6
6
|
import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
|
|
7
7
|
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
8
8
|
import { localServiceOptions } from "../test-support/localService.js";
|
|
9
|
-
import { exerciseEmailConfirmation } from "../test-support/emailConfirmationScenario.js";
|
|
9
|
+
import { exerciseEmailConfirmation, exerciseRegistrationTakeover } from "../test-support/emailConfirmationScenario.js";
|
|
10
10
|
|
|
11
11
|
const PASSWORD = "correct horse battery staple";
|
|
12
12
|
|
|
@@ -30,6 +30,11 @@ test("registration waits for its email to be confirmed, with a hashed, single-us
|
|
|
30
30
|
fs.readFile(path.join(storeDir, "registrations.passwd"), "utf8").catch(() => ""));
|
|
31
31
|
});
|
|
32
32
|
|
|
33
|
+
test("registering an email before or after its owner never gives its account someone else's password (file backend)", async (t) => {
|
|
34
|
+
const { service } = await startService(t);
|
|
35
|
+
await exerciseRegistrationTakeover(service);
|
|
36
|
+
});
|
|
37
|
+
|
|
33
38
|
test("AUTH_LOCAL_EMAIL_CONFIRMATION=false registers and signs in at once, and confirming is unsupported", async (t) => {
|
|
34
39
|
const { service } = await startService(t, { env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
|
|
35
40
|
const registered = await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
@@ -72,6 +77,6 @@ test("an invitation is checked on registering and given to the account its confi
|
|
|
72
77
|
});
|
|
73
78
|
assert.deepEqual(synced, []);
|
|
74
79
|
const token = new URL(registered.confirmationUrl).searchParams.get("confirmation_token");
|
|
75
|
-
await service.confirmRegistration({ token });
|
|
80
|
+
await service.confirmRegistration({ token, password: PASSWORD });
|
|
76
81
|
assert.deepEqual(synced, [{ email: "guest@example.com", source: "workspace-invite", token: "invite-1" }]);
|
|
77
82
|
});
|
|
@@ -130,7 +130,7 @@ test("with email confirmation, the code admits the first registration, and confi
|
|
|
130
130
|
assert.equal(waitingForFirstAccount(service), true);
|
|
131
131
|
await assert.rejects(service.register({ email: "early@example.com", password: PASSWORD }), codeRequired);
|
|
132
132
|
|
|
133
|
-
const owner = await service.confirmRegistration({ token: links[0].searchParams.get("confirmation_token") });
|
|
133
|
+
const owner = await service.confirmRegistration({ token: links[0].searchParams.get("confirmation_token"), password: PASSWORD });
|
|
134
134
|
assert.equal(owner.actor.email, "owner@example.com");
|
|
135
135
|
assert.ok(owner.session.access_token);
|
|
136
136
|
assert.equal(waitingForFirstAccount(service), false);
|
package/test/oauthSignIn.test.js
CHANGED
package/test/profileSync.test.js
CHANGED
|
@@ -639,6 +639,15 @@ test("local auth password strategy supports partial overrides and rejects invali
|
|
|
639
639
|
);
|
|
640
640
|
});
|
|
641
641
|
|
|
642
|
+
test("the file backend refuses a second account with an id or email with a coded conflict", async () => {
|
|
643
|
+
const backend = createLocalFileBackend({ storeDir: await temporaryStoreDir("jskit-auth-duplicate-") });
|
|
644
|
+
const account = (id, email) => backend.withTransaction((tx) => tx.users.create({ id, email, displayName: "Ada", password: "hash" }));
|
|
645
|
+
await account("usr_first", "ada@example.com");
|
|
646
|
+
const conflict = { status: 409, code: "auth.local.accounts.exists", message: "An account with this id or email already exists." };
|
|
647
|
+
await assert.rejects(account("usr_second", "ada@example.com"), conflict);
|
|
648
|
+
await assert.rejects(account("usr_first", "other@example.com"), conflict);
|
|
649
|
+
});
|
|
650
|
+
|
|
642
651
|
test("local auth login verifies password and creates session in one backend transaction", async () => {
|
|
643
652
|
const password = await hashPassword("current password value");
|
|
644
653
|
let transactions = 0;
|
|
@@ -978,13 +987,18 @@ test("local auth provider completes recovery through a recovery-scoped session",
|
|
|
978
987
|
assert.equal(login.actor.email, "recovery@example.com");
|
|
979
988
|
});
|
|
980
989
|
|
|
981
|
-
test("local auth reset invalidates other
|
|
982
|
-
const { authService } = await createStartedApp();
|
|
990
|
+
test("local auth reset invalidates the user's other password resets and leaves their other kinds of token open", async () => {
|
|
991
|
+
const { authService, backend } = await createStartedApp();
|
|
983
992
|
await authService.register({
|
|
984
993
|
email: "recovery-tokens@example.com",
|
|
985
994
|
password: "correct horse battery staple",
|
|
986
995
|
displayName: "Recovery Tokens"
|
|
987
996
|
});
|
|
997
|
+
// An application's own kind of recovery token, such as a sign-in link, told apart by its id's prefix.
|
|
998
|
+
await backend.withTransaction(async (tx) => {
|
|
999
|
+
const user = await tx.users.findByEmail("recovery-tokens@example.com");
|
|
1000
|
+
await tx.recovery.create({ id: "magic_link", userId: user.id, tokenHash: "hash-magic-link", expiresAt: new Date(Date.now() + 3_600_000).toISOString() });
|
|
1001
|
+
});
|
|
988
1002
|
|
|
989
1003
|
const firstResetRequest = await authService.requestPasswordReset({
|
|
990
1004
|
email: "recovery-tokens@example.com"
|
|
@@ -1018,6 +1032,8 @@ test("local auth reset invalidates other outstanding recovery tokens for the use
|
|
|
1018
1032
|
}),
|
|
1019
1033
|
/Recovery token is invalid or expired/
|
|
1020
1034
|
);
|
|
1035
|
+
const link = await backend.withTransaction((tx) => tx.recovery.findByTokenHash("hash-magic-link"));
|
|
1036
|
+
assert.equal(link.usedAt, "", "the reset leaves the sign-in link open");
|
|
1021
1037
|
});
|
|
1022
1038
|
|
|
1023
1039
|
test("local auth provider changes password through the account-security contract", async () => {
|
|
@@ -1507,9 +1523,19 @@ test("the confirmation sender emails the link, which is never returned or logged
|
|
|
1507
1523
|
assert.equal(`${link.origin}${link.pathname}`, "https://app.example.test/auth/login");
|
|
1508
1524
|
assert.equal(JSON.stringify(logs).includes(link.searchParams.get("confirmation_token")), false);
|
|
1509
1525
|
|
|
1526
|
+
// The link's code alone is refused: confirming takes the registration's password too.
|
|
1527
|
+
await assert.rejects(
|
|
1528
|
+
app.actionExecutor.execute({
|
|
1529
|
+
actionId: "auth.register.confirm",
|
|
1530
|
+
input: { token: link.searchParams.get("confirmation_token") },
|
|
1531
|
+
context: { channel: "internal" }
|
|
1532
|
+
}),
|
|
1533
|
+
(error) => error.code === "ACTION_VALIDATION_FAILED" && Object.keys(error.details.fieldErrors).join() === "password"
|
|
1534
|
+
);
|
|
1535
|
+
assert.deepEqual(hooked, []);
|
|
1510
1536
|
const confirmed = await app.actionExecutor.execute({
|
|
1511
1537
|
actionId: "auth.register.confirm",
|
|
1512
|
-
input: { token: link.searchParams.get("confirmation_token") },
|
|
1538
|
+
input: { token: link.searchParams.get("confirmation_token"), password: "correct horse battery staple" },
|
|
1513
1539
|
context: { channel: "internal" }
|
|
1514
1540
|
});
|
|
1515
1541
|
assert.equal(confirmed.actor.email, "mail@example.com");
|
|
@@ -5,6 +5,9 @@ import { sha256Base64url } from "../src/server/lib/tokens.js";
|
|
|
5
5
|
const PASSWORD = "correct horse battery staple";
|
|
6
6
|
const EMAIL = "ada@example.com";
|
|
7
7
|
const invalidLink = { status: 400, code: "auth.local.register.confirmationInvalid" };
|
|
8
|
+
const wrongPassword = { status: 400, code: "auth.local.register.confirmationPasswordInvalid" };
|
|
9
|
+
const invalidCredentials = { status: 401, code: AUTH_TEXTS.invalidCredentials.code };
|
|
10
|
+
const unconfirmed = { status: 403, code: AUTH_TEXTS.emailUnconfirmed.code };
|
|
8
11
|
|
|
9
12
|
/** The code of a development confirmation link. */
|
|
10
13
|
function linkToken(result) {
|
|
@@ -34,22 +37,14 @@ async function exerciseEmailConfirmation(t, service, storedRegistrations) {
|
|
|
34
37
|
assert.equal(stored.includes(sha256Base64url(firstToken)), true);
|
|
35
38
|
|
|
36
39
|
// Until it is confirmed, the right password is refused as unconfirmed; a wrong one is an ordinary failure.
|
|
37
|
-
await assert.rejects(service.login({ email: EMAIL, password: PASSWORD }),
|
|
38
|
-
|
|
39
|
-
code: AUTH_TEXTS.emailUnconfirmed.code
|
|
40
|
-
});
|
|
41
|
-
await assert.rejects(service.login({ email: EMAIL, password: "a wrong password" }), {
|
|
42
|
-
status: 401,
|
|
43
|
-
code: AUTH_TEXTS.invalidCredentials.code
|
|
44
|
-
});
|
|
40
|
+
await assert.rejects(service.login({ email: EMAIL, password: PASSWORD }), unconfirmed);
|
|
41
|
+
await assert.rejects(service.login({ email: EMAIL, password: "a wrong password" }), invalidCredentials);
|
|
45
42
|
|
|
46
|
-
//
|
|
47
|
-
const secondToken = linkToken(await service.register({ email: EMAIL, password: PASSWORD, displayName: "Ada" }));
|
|
48
|
-
await assert.rejects(service.confirmRegistration({ token: firstToken }), invalidLink);
|
|
43
|
+
// Asking for a new link replaces the link.
|
|
49
44
|
const resent = await service.resendRegisterConfirmation({ email: EMAIL });
|
|
50
45
|
assert.equal(resent.messageCode, "auth.local.register.confirmationResent");
|
|
51
|
-
const
|
|
52
|
-
await assert.rejects(service.confirmRegistration({ token:
|
|
46
|
+
const secondToken = linkToken(resent);
|
|
47
|
+
await assert.rejects(service.confirmRegistration({ token: firstToken, password: PASSWORD }), invalidLink);
|
|
53
48
|
// The answer for an email nobody registered is the same, without a link.
|
|
54
49
|
assert.deepEqual(await service.resendRegisterConfirmation({ email: "nobody@example.com" }), {
|
|
55
50
|
ok: true,
|
|
@@ -58,29 +53,80 @@ async function exerciseEmailConfirmation(t, service, storedRegistrations) {
|
|
|
58
53
|
messageParams: {}
|
|
59
54
|
});
|
|
60
55
|
|
|
61
|
-
//
|
|
62
|
-
|
|
56
|
+
// The link alone, or with another password, creates nothing: the registration and its link still wait.
|
|
57
|
+
await assert.rejects(service.confirmRegistration({ token: secondToken }), wrongPassword);
|
|
58
|
+
await assert.rejects(service.confirmRegistration({ token: secondToken, password: "a wrong password" }), wrongPassword);
|
|
59
|
+
await assert.rejects(service.login({ email: EMAIL, password: PASSWORD }), unconfirmed);
|
|
60
|
+
|
|
61
|
+
// Confirming with the registration's password creates the account and signs the person in; its password signs in too.
|
|
62
|
+
const confirmed = await service.confirmRegistration({ token: secondToken, password: PASSWORD });
|
|
63
63
|
assert.ok(confirmed.session.access_token);
|
|
64
64
|
assert.equal(confirmed.actor.email, EMAIL);
|
|
65
65
|
assert.equal(confirmed.actor.displayName, "Ada");
|
|
66
66
|
assert.equal((await service.login({ email: EMAIL, password: PASSWORD })).actor.email, EMAIL);
|
|
67
|
-
assert.equal((await storedRegistrations()).includes(sha256Base64url(
|
|
67
|
+
assert.equal((await storedRegistrations()).includes(sha256Base64url(secondToken)), false);
|
|
68
68
|
|
|
69
69
|
// The link works once, and the confirmed email cannot register again.
|
|
70
|
-
await assert.rejects(service.confirmRegistration({ token:
|
|
70
|
+
await assert.rejects(service.confirmRegistration({ token: secondToken, password: PASSWORD }), invalidLink);
|
|
71
71
|
await assert.rejects(service.register({ email: EMAIL, password: PASSWORD }), {
|
|
72
72
|
status: 409,
|
|
73
73
|
code: "auth.local.register.emailTaken"
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
-
// A link expires after a day; the waiting password is then an ordinary failed sign-in
|
|
76
|
+
// A link expires after a day; the waiting password is then an ordinary failed sign-in, asking for a new link sends
|
|
77
|
+
// none, and registering again starts afresh.
|
|
77
78
|
const lateToken = linkToken(await service.register({ email: "late@example.com", password: PASSWORD }));
|
|
78
79
|
t.mock.timers.tick(24 * 60 * 60 * 1000 + 1000);
|
|
79
|
-
await assert.rejects(service.confirmRegistration({ token: lateToken }), invalidLink);
|
|
80
|
-
await assert.rejects(service.login({ email: "late@example.com", password: PASSWORD }),
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
});
|
|
80
|
+
await assert.rejects(service.confirmRegistration({ token: lateToken, password: PASSWORD }), invalidLink);
|
|
81
|
+
await assert.rejects(service.login({ email: "late@example.com", password: PASSWORD }), invalidCredentials);
|
|
82
|
+
assert.equal(Object.hasOwn(await service.resendRegisterConfirmation({ email: "late@example.com" }), "confirmationUrl"), false);
|
|
83
|
+
const againToken = linkToken(await service.register({ email: "late@example.com", password: PASSWORD }));
|
|
84
|
+
assert.equal((await service.confirmRegistration({ token: againToken, password: PASSWORD })).actor.email, "late@example.com");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Registering an email someone else owns, before its owner registers it or
|
|
89
|
+
* after, against any backend with confirmation on. Each link stands for the
|
|
90
|
+
* email its owner receives (development shows it in the answer), and the owner
|
|
91
|
+
* opens it with their own password. Whatever the order, the account a link
|
|
92
|
+
* creates opens only with the owner's password.
|
|
93
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthService} service
|
|
94
|
+
*/
|
|
95
|
+
async function exerciseRegistrationTakeover(service) {
|
|
96
|
+
const ownPassword = "the owner's own password";
|
|
97
|
+
const otherPassword = "someone else's password";
|
|
98
|
+
|
|
99
|
+
// Someone else registers the email first; its owner ignores that link and later registers it.
|
|
100
|
+
const before = "before@example.com";
|
|
101
|
+
linkToken(await service.register({ email: before, password: otherPassword, displayName: "Someone else" }));
|
|
102
|
+
const ownLink = linkToken(await service.register({ email: before, password: ownPassword, displayName: "Owner" }));
|
|
103
|
+
const first = await service.confirmRegistration({ token: ownLink, password: ownPassword });
|
|
104
|
+
assert.equal(first.actor.displayName, "Owner");
|
|
105
|
+
assert.equal((await service.login({ email: before, password: ownPassword })).actor.email, before);
|
|
106
|
+
await assert.rejects(service.login({ email: before, password: otherPassword }), invalidCredentials);
|
|
107
|
+
|
|
108
|
+
// The owner registers first; someone else registers the email later. The owner's link stops working, and the new
|
|
109
|
+
// one, which reaches the owner too, does not open with the owner's password: nothing is created.
|
|
110
|
+
const after = "after@example.com";
|
|
111
|
+
const ownFirst = linkToken(await service.register({ email: after, password: ownPassword, displayName: "Owner" }));
|
|
112
|
+
const theirs = linkToken(await service.register({ email: after, password: otherPassword, displayName: "Someone else" }));
|
|
113
|
+
await assert.rejects(service.confirmRegistration({ token: ownFirst, password: ownPassword }), invalidLink);
|
|
114
|
+
await assert.rejects(service.confirmRegistration({ token: theirs, password: ownPassword }), wrongPassword);
|
|
115
|
+
await assert.rejects(service.login({ email: after, password: otherPassword }), unconfirmed);
|
|
116
|
+
// Registering again gives the owner a link that works.
|
|
117
|
+
const ownAgain = linkToken(await service.register({ email: after, password: ownPassword, displayName: "Owner" }));
|
|
118
|
+
const second = await service.confirmRegistration({ token: ownAgain, password: ownPassword });
|
|
119
|
+
assert.equal(second.actor.displayName, "Owner");
|
|
120
|
+
await assert.rejects(service.login({ email: after, password: otherPassword }), invalidCredentials);
|
|
121
|
+
|
|
122
|
+
// A link the owner never asked for creates nothing when opened with the owner's password, and asking for a new
|
|
123
|
+
// link, which anyone may, keeps the registration's password.
|
|
124
|
+
const unasked = "unasked@example.com";
|
|
125
|
+
const unaskedLink = linkToken(await service.register({ email: unasked, password: otherPassword }));
|
|
126
|
+
await assert.rejects(service.confirmRegistration({ token: unaskedLink, password: ownPassword }), wrongPassword);
|
|
127
|
+
const resentLink = linkToken(await service.resendRegisterConfirmation({ email: unasked }));
|
|
128
|
+
await assert.rejects(service.confirmRegistration({ token: resentLink, password: ownPassword }), wrongPassword);
|
|
129
|
+
await assert.rejects(service.login({ email: unasked, password: ownPassword }), invalidCredentials);
|
|
84
130
|
}
|
|
85
131
|
|
|
86
|
-
export { exerciseEmailConfirmation };
|
|
132
|
+
export { exerciseEmailConfirmation, exerciseRegistrationTakeover };
|