@jskit-ai/auth-provider-local-core 0.2.19 → 0.2.21

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,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - 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.
5
6
  - 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
7
  - 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
8
  - 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.19",
3
+ "version": "0.2.21",
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.16",
71
- "@jskit-ai/kernel": "0.2.16"
70
+ "@jskit-ai/auth-core": "0.2.18",
71
+ "@jskit-ai/kernel": "0.2.18"
72
72
  }
73
73
  }
@@ -121,7 +121,8 @@ async function resolveRegistrationProfileOptions(invitationContextResolver, invi
121
121
 
122
122
  /**
123
123
  * The accounts of local auth: registering one (which waits for its email to
124
- * be confirmed while config.emailConfirmation is on), signing in with its
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), signing in with its
125
126
  * password (failures slow the account down, as config.signInThrottle says) or
126
127
  * as a dev user, and renaming it.
127
128
  * @param {object} dependencies
@@ -156,16 +157,27 @@ function createLocalAccounts({
156
157
  throw new AppError(403, "This app's accounts are by invitation only.", { code: "auth.local.register.closed" });
157
158
  }
158
159
 
160
+ // A feature's resolver gives an invitation only while it can be used, so one it resolved that was sent to this
161
+ // email and has not expired proves the email: its link reached that address. One passed through as given, or one
162
+ // whose resolver does not say whom it was sent to, proves nothing.
163
+ function invitationProvesEmail(invitation, email) {
164
+ if (invitationContextResolver === invitationAsGiven || !invitation?.email) return false;
165
+ if (normalizeEmail(invitation.email) !== email) return false;
166
+ return invitation.expiresAt == null || new Date(invitation.expiresAt).getTime() > Date.now();
167
+ }
168
+
159
169
  async function register(input) {
160
170
  const email = validateEmailInput(input.email);
161
171
  validatePasswordInput(input.password, config.passwordMinLength);
162
172
  const displayName = normalizeDisplayName(input.displayName, email);
163
- await firstAccountSetup.admitRegistration(input.setupCode);
173
+ const firstAccount = await firstAccountSetup.admitRegistration(input.setupCode);
164
174
  // Checked now, so a registration with an invitation it cannot use is refused at once.
165
175
  const profileOptions = await resolveRegistrationProfileOptions(invitationContextResolver, input.invitation, email);
166
176
  if (!config.selfRegistration) await admitClosedRegistration(profileOptions);
167
177
  const password = await passwords.hashPassword(input.password);
168
- if (config.emailConfirmation) {
178
+ // The first account, admitted by the setup code only the operator can read, and an invited person need no link.
179
+ const emailProven = firstAccount || invitationProvesEmail(profileOptions.invitation, email);
180
+ if (config.emailConfirmation && !emailProven) {
169
181
  return emailConfirmation.begin({ email, displayName, password, invitation: normalizeInvitationInput(input.invitation) });
170
182
  }
171
183
  const result = await backend.withTransaction(async (tx) => {
@@ -213,9 +225,9 @@ function createLocalAccounts({
213
225
  return { waitMs };
214
226
  }
215
227
  const user = await tx.users.findByEmail(email);
216
- if (!user && config.emailConfirmation &&
217
- (await emailConfirmation.isWaitingWithPassword(tx, email, (registration) =>
218
- passwords.verifyPassword(password, registration.password)))) {
228
+ // Whatever config.emailConfirmation says now: a registration made while it was on still waits.
229
+ if (!user && (await emailConfirmation.isWaitingWithPassword(tx, email, (registration) =>
230
+ passwords.verifyPassword(password, registration.password)))) {
219
231
  return { unconfirmed: true };
220
232
  }
221
233
  if (!user || user.disabled || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
@@ -130,10 +130,11 @@ function createFirstAccountSetup({ backend, config, logger }) {
130
130
  return started;
131
131
  }
132
132
 
133
+ // True when the code admits the app's first account; false when an account exists and no code is needed.
133
134
  async function admitIn(tx, setupCode) {
134
135
  if (await tx.users.hasAny()) {
135
136
  finish();
136
- return;
137
+ return false;
137
138
  }
138
139
  if (!String(setupCode || "").trim()) {
139
140
  throw setupCodeRequired();
@@ -141,18 +142,20 @@ function createFirstAccountSetup({ backend, config, logger }) {
141
142
  if (setupCodeHash(setupCode) !== codeHash) {
142
143
  throw setupCodeInvalid();
143
144
  }
145
+ return true;
144
146
  }
145
147
 
146
148
  /**
147
149
  * Refuses a registration while the first account needs its setup code and
148
- * `setupCode` is not it.
150
+ * `setupCode` is not it. Answers true when the setup code admitted it: the
151
+ * app's first account, which only the server's operator can register, so it
152
+ * needs no email confirmation.
149
153
  * @param {unknown} setupCode
154
+ * @returns {Promise<boolean>}
150
155
  */
151
156
  async function admitRegistration(setupCode) {
152
157
  await start();
153
- if (codeHash !== null) {
154
- await backend.withTransaction((tx) => admitIn(tx, setupCode));
155
- }
158
+ return codeHash !== null && (await backend.withTransaction((tx) => admitIn(tx, setupCode)));
156
159
  }
157
160
 
158
161
  /**
@@ -55,8 +55,8 @@
55
55
  * delete(email: string): Promise<number>,
56
56
  * deleteExpired(now: string): Promise<number>
57
57
  * }} registrations Registrations waiting for their email to be confirmed, one per
58
- * email; `save` replaces the email's registration. Used only while
59
- * AUTH_LOCAL_EMAIL_CONFIRMATION is on.
58
+ * email; `save` replaces the email's registration. Saved only while
59
+ * AUTH_LOCAL_EMAIL_CONFIRMATION is on; a sign-in reads them whatever it says.
60
60
  */
61
61
 
62
62
  /**
@@ -4,15 +4,23 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import test from "node:test";
6
6
  import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
7
+ import { AUTH_TEXTS } from "@jskit-ai/auth-core/server/authTexts";
7
8
  import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
8
9
  import { localServiceOptions } from "../test-support/localService.js";
9
10
  import { exerciseEmailConfirmation, exerciseRegistrationTakeover } from "../test-support/emailConfirmationScenario.js";
10
11
 
11
12
  const PASSWORD = "correct horse battery staple";
13
+ const unconfirmed = { status: 403, code: AUTH_TEXTS.emailUnconfirmed.code };
14
+ const invalidCredentials = { status: 401, code: AUTH_TEXTS.invalidCredentials.code };
12
15
 
13
- async function startService(t, { env = {}, ...overrides } = {}) {
16
+ async function temporaryStoreDir(t) {
14
17
  const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-confirmation-"));
15
18
  t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
19
+ return storeDir;
20
+ }
21
+
22
+ async function startService(t, { env = {}, storeDir, ...overrides } = {}) {
23
+ storeDir ??= await temporaryStoreDir(t);
16
24
  const backend = createLocalFileBackend({ storeDir });
17
25
  // "" leaves AUTH_LOCAL_EMAIL_CONFIRMATION unset: confirmation on, its default.
18
26
  const options = localServiceOptions({ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "", ...env } });
@@ -80,3 +88,80 @@ test("an invitation is checked on registering and given to the account its confi
80
88
  await service.confirmRegistration({ token, password: PASSWORD });
81
89
  assert.deepEqual(synced, [{ email: "guest@example.com", source: "workspace-invite", token: "invite-1" }]);
82
90
  });
91
+
92
+ test("an invitation a feature resolved for the registering email signs in at once; any other registration still waits", async (t) => {
93
+ const later = new Date(Date.now() + 60 * 60 * 1000).toISOString();
94
+ // What a feature's resolver answers for each token, as workspace invites do: the address it was sent to and its expiry.
95
+ // A real resolver refuses another email or a lapsed invitation itself; these show local auth checks them too.
96
+ const invitations = {
97
+ "for-ada": { email: "Ada@Example.COM", expiresAt: later },
98
+ "for-bob": { email: "bob@example.com", expiresAt: later },
99
+ lapsed: { email: "cat@example.com", expiresAt: new Date(Date.now() - 1000).toISOString() },
100
+ unaddressed: {}
101
+ };
102
+ const synced = [];
103
+ const { service } = await startService(t, {
104
+ invitationContextResolver: {
105
+ async resolveInvitationContext({ token, source }) {
106
+ return { token, source, ...invitations[token] };
107
+ }
108
+ },
109
+ profileProjector: {
110
+ async syncIdentityProfile(profile, options) {
111
+ synced.push({ email: profile.email, token: options.invitation?.token });
112
+ return null;
113
+ },
114
+ async findByIdentity() {
115
+ return null;
116
+ }
117
+ }
118
+ });
119
+ const register = (email, token) =>
120
+ service.register({ email, password: PASSWORD, ...(token && { invitation: { token, source: "workspace-invite" } }) });
121
+
122
+ // Sent to this email, letter case aside, and not expired: the account exists at once, with its invitation.
123
+ const invited = await register("ada@example.com", "for-ada");
124
+ assert.equal(invited.requiresEmailConfirmation, false);
125
+ assert.ok(invited.session.access_token);
126
+ assert.deepEqual(synced, [{ email: "ada@example.com", token: "for-ada" }]);
127
+ assert.equal((await service.login({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
128
+
129
+ // Another person's invitation, a lapsed one, one that names no email, and no invitation at all: each waits for its
130
+ // link, and its password is refused as unconfirmed.
131
+ for (const [email, token] of [
132
+ ["eve@example.com", "for-bob"],
133
+ ["cat@example.com", "lapsed"],
134
+ ["dan@example.com", "unaddressed"],
135
+ ["fay@example.com", null]
136
+ ]) {
137
+ const waiting = await register(email, token);
138
+ assert.equal(waiting.requiresEmailConfirmation, true, email);
139
+ assert.equal(waiting.session, null, email);
140
+ await assert.rejects(service.login({ email, password: PASSWORD }), unconfirmed, email);
141
+ }
142
+ // Only the invited account has a profile: no waiting registration made one.
143
+ assert.deepEqual([...new Set(synced.map(({ email }) => email))], ["ada@example.com"]);
144
+ });
145
+
146
+ test("an invitation passed through as given, with no feature to resolve it, still waits for its link", async (t) => {
147
+ const { service } = await startService(t, { invitationContextResolver: invitationAsGiven });
148
+ const waiting = await service.register({
149
+ email: "ada@example.com",
150
+ password: PASSWORD,
151
+ invitation: { token: "anything", source: "workspace-invite", email: "ada@example.com" }
152
+ });
153
+ assert.equal(waiting.requiresEmailConfirmation, true);
154
+ await assert.rejects(service.login({ email: "ada@example.com", password: PASSWORD }), unconfirmed);
155
+ });
156
+
157
+ test("a registration made while confirmation was on is refused as unconfirmed after it is turned off, until it registers again", async (t) => {
158
+ const storeDir = await temporaryStoreDir(t);
159
+ const { service: confirming } = await startService(t, { storeDir });
160
+ assert.equal((await confirming.register({ email: "ada@example.com", password: PASSWORD })).requiresEmailConfirmation, true);
161
+
162
+ const { service } = await startService(t, { storeDir, env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
163
+ await assert.rejects(service.login({ email: "ada@example.com", password: PASSWORD }), unconfirmed);
164
+ await assert.rejects(service.login({ email: "ada@example.com", password: "a wrong password" }), invalidCredentials);
165
+ assert.equal((await service.register({ email: "ada@example.com", password: PASSWORD })).requiresEmailConfirmation, false);
166
+ assert.equal((await service.login({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
167
+ });
@@ -117,25 +117,42 @@ test("restarting while there is no account makes a new code, and the old one sto
117
117
  assert.equal(waitingForFirstAccount(later.service), false);
118
118
  });
119
119
 
120
- test("with email confirmation, the code admits the first registration, and confirming it ends the setup", async (t) => {
120
+ test("with email confirmation, the first account the setup code admits signs in at once and ends the setup; later sign-ups wait", async (t) => {
121
121
  const storeDir = await temporaryStoreDir(t);
122
122
  const links = [];
123
123
  const { service, setupCode } = await startServer(storeDir, {
124
124
  env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
125
- confirmationSender: async ({ confirmationUrl }) => { links.push(new URL(confirmationUrl)); }
125
+ confirmationSender: async ({ email, confirmationUrl }) => { links.push({ email, url: new URL(confirmationUrl) }); }
126
126
  });
127
- const waiting = await service.register({ email: "owner@example.com", password: PASSWORD, setupCode });
128
- assert.equal(waiting.requiresEmailConfirmation, true);
129
- // Until that registration is confirmed there is still no account, so the code is still needed.
130
- assert.equal(waitingForFirstAccount(service), true);
131
- await assert.rejects(service.register({ email: "early@example.com", password: PASSWORD }), codeRequired);
132
-
133
- const owner = await service.confirmRegistration({ token: links[0].searchParams.get("confirmation_token"), password: PASSWORD });
127
+ assert.equal(service.getCapabilities().features.emailConfirmation, true);
128
+ // Only the server's operator can read the code, so its registration needs no link: it is the owner's account at once.
129
+ const owner = await service.register({ email: "owner@example.com", password: PASSWORD, setupCode });
130
+ assert.equal(owner.requiresEmailConfirmation, false);
134
131
  assert.equal(owner.actor.email, "owner@example.com");
135
132
  assert.ok(owner.session.access_token);
133
+ assert.deepEqual(links, []);
136
134
  assert.equal(waitingForFirstAccount(service), false);
137
135
  assert.equal(await codeFile(storeDir), null);
138
- assert.equal((await service.register({ email: "later@example.com", password: PASSWORD })).requiresEmailConfirmation, true);
136
+ assert.equal((await service.login({ email: "owner@example.com", password: PASSWORD })).actor.email, "owner@example.com");
137
+
138
+ // Every later sign-up confirms its email, and cannot sign in until it does.
139
+ const later = await service.register({ email: "later@example.com", password: PASSWORD });
140
+ assert.equal(later.requiresEmailConfirmation, true);
141
+ assert.deepEqual(links.map(({ email }) => email), ["later@example.com"]);
142
+ await assert.rejects(service.login({ email: "later@example.com", password: PASSWORD }), {
143
+ status: 403,
144
+ code: "auth.login.emailUnconfirmed"
145
+ });
146
+ const confirmed = await service.confirmRegistration({ token: links[0].url.searchParams.get("confirmation_token"), password: PASSWORD });
147
+ assert.equal(confirmed.actor.email, "later@example.com");
148
+ });
149
+
150
+ test("development's first account, which needs no setup code, still confirms its email", async (t) => {
151
+ const storeDir = await temporaryStoreDir(t);
152
+ const { service } = await startServer(storeDir, { env: { NODE_ENV: "development", AUTH_LOCAL_EMAIL_CONFIRMATION: "" } });
153
+ const first = await service.register({ email: "dev@example.com", password: PASSWORD });
154
+ assert.equal(first.requiresEmailConfirmation, true);
155
+ assert.ok(first.confirmationUrl);
139
156
  });
140
157
 
141
158
  test("development asks for no setup code", async (t) => {
@@ -1508,15 +1508,24 @@ test("the confirmation sender emails the link, which is never returned or logged
1508
1508
  const features = app.authService.getCapabilities().features;
1509
1509
  assert.deepEqual([features.emailConfirmation, features.emailConfirmationCode], [true, true]);
1510
1510
 
1511
- const registered = await app.authService.register({
1512
- email: "mail@example.com",
1511
+ // The first account, admitted by its setup code, needs no link: it registers, and the hook runs, at once.
1512
+ const owner = await app.authService.register({
1513
+ email: "owner@example.com",
1513
1514
  password: "correct horse battery staple",
1514
1515
  setupCode: await firstAccountSetupCode(app.storeDir)
1515
1516
  });
1517
+ assert.equal(owner.requiresEmailConfirmation, false);
1518
+ assert.deepEqual(hooked, ["owner@example.com"]);
1519
+ assert.equal(messages.length, 0);
1520
+
1521
+ const registered = await app.authService.register({
1522
+ email: "mail@example.com",
1523
+ password: "correct horse battery staple"
1524
+ });
1516
1525
  assert.equal(registered.requiresEmailConfirmation, true);
1517
1526
  assert.equal(registered.session, null);
1518
1527
  assert.equal(Object.hasOwn(registered, "confirmationUrl"), false);
1519
- assert.deepEqual(hooked, []);
1528
+ assert.deepEqual(hooked, ["owner@example.com"]);
1520
1529
  assert.equal(messages.length, 1);
1521
1530
  assert.equal(messages[0].email, "mail@example.com");
1522
1531
  const link = new URL(messages[0].confirmationUrl);
@@ -1532,7 +1541,7 @@ test("the confirmation sender emails the link, which is never returned or logged
1532
1541
  }),
1533
1542
  (error) => error.code === "ACTION_VALIDATION_FAILED" && Object.keys(error.details.fieldErrors).join() === "password"
1534
1543
  );
1535
- assert.deepEqual(hooked, []);
1544
+ assert.deepEqual(hooked, ["owner@example.com"]);
1536
1545
  const confirmed = await app.actionExecutor.execute({
1537
1546
  actionId: "auth.register.confirm",
1538
1547
  input: { token: link.searchParams.get("confirmation_token"), password: "correct horse battery staple" },
@@ -1540,5 +1549,5 @@ test("the confirmation sender emails the link, which is never returned or logged
1540
1549
  });
1541
1550
  assert.equal(confirmed.actor.email, "mail@example.com");
1542
1551
  assert.ok(confirmed.session.access_token);
1543
- assert.deepEqual(hooked, ["mail@example.com"]);
1552
+ assert.deepEqual(hooked, ["owner@example.com", "mail@example.com"]);
1544
1553
  });