@jskit-ai/auth-provider-local-core 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - 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.
6
+ - 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
7
  - 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
8
  - 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
9
  - 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 +13,7 @@
11
13
  - 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
14
  - Upgrading: a custom `auth.local.backend` implements `users.hasAny()`.
13
15
  - 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`.
16
+ - 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
17
  - 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
18
  - 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
19
  - 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.15",
3
+ "version": "0.2.17",
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.12",
71
- "@jskit-ai/kernel": "0.2.12"
70
+ "@jskit-ai/auth-core": "0.2.14",
71
+ "@jskit-ai/kernel": "0.2.14"
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; registering again or asking for a new link replaces it.
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
- * @param {{ token: string }} input
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. The
144
- * answer is the same whether or not a registration waits for that email.
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 Error("Local auth user already exists.");
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,7 +305,7 @@ 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 clone(record || null);
308
+ return null;
308
309
  }
309
310
  record.usedAt = nowIso();
310
311
  mark("recovery");
@@ -71,20 +71,24 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
71
71
  if (!recoveryEnabled) {
72
72
  throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
73
73
  }
74
+ // Only the emailed token itself: the hash this provider stores of it never opens an account.
74
75
  const token = String(input.code || input.token || "").trim();
75
- const tokenHash = String(input.tokenHash || "").trim() || (token ? sha256Base64url(token) : "");
76
- if (!tokenHash) {
76
+ if (!token) {
77
77
  throw createAuthError(AUTH_TEXTS.recoveryTokenRequired);
78
78
  }
79
+ const tokenInvalid = () => new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
79
80
  return backend.withTransaction(async (tx) => {
80
- const recovery = await tx.recovery.findByTokenHash(tokenHash);
81
+ const recovery = await tx.recovery.findByTokenHash(sha256Base64url(token));
81
82
  if (!recovery || recovery.usedAt || isExpiredIso(recovery.expiresAt)) {
82
- throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
83
+ throw tokenInvalid();
84
+ }
85
+ // Of two completions with one token at once, only the one that consumes it opens a session.
86
+ if (!await tx.recovery.consume(recovery.id)) {
87
+ throw tokenInvalid();
83
88
  }
84
- await tx.recovery.consume(recovery.id);
85
89
  const user = await tx.users.findById(recovery.userId);
86
90
  if (!user || user.disabled) {
87
- throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
91
+ throw tokenInvalid();
88
92
  }
89
93
  const session = await sessions.createSessionForUser(tx, user, {
90
94
  purpose: "recovery",
@@ -103,6 +103,7 @@ function createLocalAuthService({
103
103
  confirmationSender,
104
104
  firstAccountSetup,
105
105
  invitationContextResolver,
106
+ passwords,
106
107
  profileProjector,
107
108
  sessions
108
109
  });
@@ -23,7 +23,7 @@
23
23
  * @property {{
24
24
  * create(input: object): Promise<object>,
25
25
  * findByTokenHash(tokenHash: string): Promise<object | null>,
26
- * consume(tokenId: string): Promise<object | null>,
26
+ * consume(tokenId: string): Promise<object | null>, the consumed token, or null when it is missing or already used
27
27
  * consumeForUser(userId: string): Promise<number>
28
28
  * }} recovery
29
29
  * @property {{
@@ -42,8 +42,9 @@
42
42
  * save(record: AuthLocalSignInFailures): Promise<AuthLocalSignInFailures>,
43
43
  * clear(email: string): Promise<number>,
44
44
  * deleteBefore(lastFailedAt: string): Promise<number>
45
- * }} signInFailures One record per account email, existing or not; `save`
46
- * replaces the email's record and `deleteBefore` removes those whose last failure is older.
45
+ * }} signInFailures One record per account email, existing or not; `find` holds the email's record until the
46
+ * transaction ends, so concurrent failures count one after another, `save` replaces the email's record and
47
+ * `deleteBefore` removes those whose last failure is older.
47
48
  * @property {{
48
49
  * save(record: AuthLocalRegistration): Promise<AuthLocalRegistration>,
49
50
  * findByEmail(email: string): Promise<AuthLocalRegistration | null>,
@@ -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);
@@ -55,8 +55,8 @@ function createUsersProfileSync() {
55
55
  profiles.push(profile);
56
56
  return profile;
57
57
  },
58
- async withTransaction(work) {
59
- return work({});
58
+ async withTransaction(options, work) {
59
+ return work(options);
60
60
  }
61
61
  },
62
62
  userSettingsRepository: {
@@ -94,8 +94,8 @@ function usersProfileSync() {
94
94
  profiles.push(profile);
95
95
  return profile;
96
96
  },
97
- async withTransaction(work) {
98
- return work({});
97
+ async withTransaction(options, work) {
98
+ return work(options);
99
99
  }
100
100
  },
101
101
  userSettingsRepository: {
@@ -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;
@@ -1507,9 +1516,19 @@ test("the confirmation sender emails the link, which is never returned or logged
1507
1516
  assert.equal(`${link.origin}${link.pathname}`, "https://app.example.test/auth/login");
1508
1517
  assert.equal(JSON.stringify(logs).includes(link.searchParams.get("confirmation_token")), false);
1509
1518
 
1519
+ // The link's code alone is refused: confirming takes the registration's password too.
1520
+ await assert.rejects(
1521
+ app.actionExecutor.execute({
1522
+ actionId: "auth.register.confirm",
1523
+ input: { token: link.searchParams.get("confirmation_token") },
1524
+ context: { channel: "internal" }
1525
+ }),
1526
+ (error) => error.code === "ACTION_VALIDATION_FAILED" && Object.keys(error.details.fieldErrors).join() === "password"
1527
+ );
1528
+ assert.deepEqual(hooked, []);
1510
1529
  const confirmed = await app.actionExecutor.execute({
1511
1530
  actionId: "auth.register.confirm",
1512
- input: { token: link.searchParams.get("confirmation_token") },
1531
+ input: { token: link.searchParams.get("confirmation_token"), password: "correct horse battery staple" },
1513
1532
  context: { channel: "internal" }
1514
1533
  });
1515
1534
  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
- status: 403,
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
- // Registering again, or asking for a new link, replaces the link.
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 thirdToken = linkToken(resent);
52
- await assert.rejects(service.confirmRegistration({ token: secondToken }), invalidLink);
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
- // Confirming creates the account and signs the person in; its password signs in too.
62
- const confirmed = await service.confirmRegistration({ token: thirdToken });
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(thirdToken)), false);
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: thirdToken }), invalidLink);
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
- status: 401,
82
- code: AUTH_TEXTS.invalidCredentials.code
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 };