@jskit-ai/auth-provider-local-core 0.2.12 → 0.2.14

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
+ - Local auth reports `features.password.selfRegister: false` with `AUTH_LOCAL_SELF_REGISTRATION=false`, so the sign-in page hides its Register tab, except while the app has no account: its first account may register (with the setup code in production), in development too, where the server now checks once at startup whether there is an account.
6
+ - `AUTH_LOCAL_SELF_REGISTRATION=false` closes self-registration: an account registers only by an invitation a feature's invitation context resolver resolves for its email, or as the first account (admitted by its setup code in production); anyone else is refused with 403 `auth.local.register.closed` (new message key `jskit.auth.local.register.closed`; an app with other locales adds it with `npx jskit i18n export <locale>`). Confirmation guards self-registration, so with it off a production server starts without an `auth.local.confirmation-sender`, and those registrations sign in at once. Upgrading: an invitation-only or admin-created-accounts app that refused to start in production for want of a confirmation sender sets `AUTH_LOCAL_SELF_REGISTRATION=false` (and can drop its own 404 hook on the register routes); the startup refusal now names this way out too. `resolveLocalAuthConfig()` returns `selfRegistration`.
5
7
  - 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`.
6
8
  - Upgrading: a custom `auth.local.backend` implements `users.hasAny()`.
7
9
  - 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.
package/locales/en.json CHANGED
@@ -12,6 +12,7 @@
12
12
  },
13
13
  "register": {
14
14
  "emailTaken": "An account already exists for this email.",
15
+ "closed": "This app's accounts are by invitation only.",
15
16
  "confirmationInvalid": "This confirmation link is invalid or has expired. Register again to get a new one.",
16
17
  "confirmationResent": "If a registration is waiting for that email, a new confirmation link has been sent."
17
18
  },
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "type": "module",
5
5
  "scripts": {
6
- "test": "node --test --test-concurrency=1"
6
+ "test": "jskit test"
7
7
  },
8
8
  "exports": {
9
9
  "./server/providers/AuthLocalProvider": "./src/server/providers/AuthLocalProvider.js",
@@ -67,7 +67,7 @@
67
67
  }
68
68
  },
69
69
  "peerDependencies": {
70
- "@jskit-ai/auth-core": "0.2.10",
71
- "@jskit-ai/kernel": "0.2.10"
70
+ "@jskit-ai/auth-core": "0.2.11",
71
+ "@jskit-ai/kernel": "0.2.11"
72
72
  }
73
73
  }
@@ -3,6 +3,7 @@ import { AUTH_PASSWORD_MAX_LENGTH } from "@jskit-ai/auth-core/shared/authConstra
3
3
  import { ensureDevAuthExchangeAvailable, isDevAuthBootstrapEnabled } from "@jskit-ai/auth-core/server/devAuth";
4
4
  import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
5
5
  import { AUTH_TEXTS, authFieldErrorDetails, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
6
+ import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
6
7
  import { DEV_AUTH_SESSION_PURPOSE, buildAuthPayload, buildAuthResult, findExistingAppProfile } from "./authPayloads.js";
7
8
  import { forgottenFailuresBefore, recordSignInFailure, signInLockedError, signInWaitMs } from "./signInThrottle.js";
8
9
  import { createId } from "./tokens.js";
@@ -147,6 +148,14 @@ function createLocalAccounts({
147
148
  }) {
148
149
  const { devAuth } = config;
149
150
 
151
+ // With self-registration off, an account registers only by an invitation a feature resolved (one passed through as
152
+ // given proves nothing), or as the app's first account.
153
+ async function admitClosedRegistration(profileOptions) {
154
+ if (invitationContextResolver !== invitationAsGiven && profileOptions.invitation) return;
155
+ if (!(await backend.withTransaction((tx) => tx.users.hasAny()))) return;
156
+ throw new AppError(403, "This app's accounts are by invitation only.", { code: "auth.local.register.closed" });
157
+ }
158
+
150
159
  async function register(input) {
151
160
  const email = validateEmailInput(input.email);
152
161
  validatePasswordInput(input.password, config.passwordMinLength);
@@ -154,6 +163,7 @@ function createLocalAccounts({
154
163
  await firstAccountSetup.admitRegistration(input.setupCode);
155
164
  // Checked now, so a registration with an invitation it cannot use is refused at once.
156
165
  const profileOptions = await resolveRegistrationProfileOptions(invitationContextResolver, input.invitation, email);
166
+ if (!config.selfRegistration) await admitClosedRegistration(profileOptions);
157
167
  const password = await passwords.hashPassword(input.password);
158
168
  if (config.emailConfirmation) {
159
169
  return emailConfirmation.begin({ email, displayName, password, invitation: normalizeInvitationInput(input.invitation) });
@@ -111,20 +111,24 @@ function resolveRecoveryDelivery(env, { emailRecovery, isProduction }) {
111
111
  * (AUTH_LOCAL_EMAIL_CONFIRMATION, on unless set to false), and how its link
112
112
  * reaches the person: by email through the installed confirmation sender, or,
113
113
  * in development without one, in the registration's response (the sign-in
114
- * screen shows it) and the log. Production without a sender stops startup,
115
- * because nobody could confirm.
114
+ * screen shows it) and the log. Confirmation guards self-registration: in
115
+ * production without a sender, startup stops while anyone may register,
116
+ * because nobody could confirm, and with self-registration off (invited
117
+ * accounts and the first one, admitted by its setup code) nothing is confirmed.
116
118
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
117
- * @param {{ emailConfirmationSender: boolean, isProduction: boolean }} options
119
+ * @param {{ emailConfirmationSender: boolean, isProduction: boolean, selfRegistration: boolean }} options
118
120
  * @returns {"email" | "dev-response" | "off"}
119
121
  */
120
- function resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction }) {
122
+ function resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction, selfRegistration }) {
121
123
  if (!parseBooleanFlag(env.AUTH_LOCAL_EMAIL_CONFIRMATION, true)) return "off";
122
124
  if (emailConfirmationSender) return "email";
123
125
  if (isProduction) {
126
+ if (!selfRegistration) return "off";
124
127
  throw new Error(
125
128
  "Local auth confirms each new account's email address in production, and no auth.local.confirmation-sender " +
126
- "is installed to email the confirmation links. Install one, or set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
127
- "to let accounts register without confirming their email."
129
+ "is installed to email the confirmation links. Install one, set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
130
+ "to let accounts register without confirming their email, or set AUTH_LOCAL_SELF_REGISTRATION=false " +
131
+ "when accounts are only invited."
128
132
  );
129
133
  }
130
134
  return "dev-response";
@@ -169,7 +173,10 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
169
173
  const oauthProviders = resolveOAuthProviders(env);
170
174
  const oauthEnabled = oauthProviders.length > 0;
171
175
  const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery, isProduction });
172
- const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction });
176
+ // AUTH_LOCAL_SELF_REGISTRATION, on unless set to false: off, an account registers only by an invitation a feature
177
+ // resolves, or as the first account.
178
+ const selfRegistration = parseBooleanFlag(env.AUTH_LOCAL_SELF_REGISTRATION, true);
179
+ const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isProduction, selfRegistration });
173
180
  return Object.freeze({
174
181
  storeDir,
175
182
  isProduction,
@@ -184,6 +191,7 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
184
191
  setupCode: resolveSetupCode(env, { isProduction }),
185
192
  recoveryDelivery,
186
193
  recoveryEnabled: recoveryDelivery !== "disabled",
194
+ selfRegistration,
187
195
  confirmationDelivery,
188
196
  emailConfirmation: confirmationDelivery !== "off",
189
197
  passwordMinLength: resolvePasswordMinLength(env),
@@ -49,7 +49,9 @@ function setupCodeInvalid() {
49
49
  * AUTH_LOCAL_SETUP_CODE shows it to the operator itself: the server then uses
50
50
  * that code at every start, and neither logs nor writes it. The code admits
51
51
  * registrations until an account exists, then stops working and its file is
52
- * deleted. Development needs no code.
52
+ * deleted. Development needs no code. In every mode it knows whether the app
53
+ * still has no account, so an invitation-only app can let its first account
54
+ * register.
53
55
  * @param {object} dependencies
54
56
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
55
57
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
@@ -58,6 +60,7 @@ function setupCodeInvalid() {
58
60
  function createFirstAccountSetup({ backend, config, logger }) {
59
61
  const codeFile = path.join(config.storeDir, SETUP_CODE_FILE);
60
62
  let codeHash = null;
63
+ let ownerless = false;
61
64
  let started = null;
62
65
 
63
66
  // The file only hands the code to the operator, and the log has it too, so
@@ -84,6 +87,7 @@ function createFirstAccountSetup({ backend, config, logger }) {
84
87
 
85
88
  function finish() {
86
89
  codeHash = null;
90
+ ownerless = false;
87
91
  removeCodeFile();
88
92
  }
89
93
 
@@ -92,6 +96,10 @@ function createFirstAccountSetup({ backend, config, logger }) {
92
96
  finish();
93
97
  return;
94
98
  }
99
+ ownerless = true;
100
+ if (!config.isProduction) {
101
+ return;
102
+ }
95
103
  if (config.setupCode) {
96
104
  // The hosting tool shows its code, so a file left by an earlier start would only mislead.
97
105
  codeHash = setupCodeHash(config.setupCode);
@@ -112,12 +120,9 @@ function createFirstAccountSetup({ backend, config, logger }) {
112
120
 
113
121
  /**
114
122
  * Checks for an account once, when the server starts; outside production,
115
- * there is nothing to check. Later calls answer the same check.
123
+ * only whether there is one. Later calls answer the same check.
116
124
  */
117
125
  function start() {
118
- if (!config.isProduction) {
119
- return Promise.resolve();
120
- }
121
126
  started ??= prepare().catch((error) => {
122
127
  started = null;
123
128
  throw error;
@@ -167,6 +172,12 @@ function createFirstAccountSetup({ backend, config, logger }) {
167
172
  if (codeHash !== null) {
168
173
  finish();
169
174
  }
175
+ ownerless = false;
176
+ }
177
+
178
+ /** True while the app has no account, as far as this server knows. */
179
+ function isOwnerless() {
180
+ return ownerless;
170
181
  }
171
182
 
172
183
  /** True while the first account needs the setup code, as far as this server knows. */
@@ -179,6 +190,7 @@ function createFirstAccountSetup({ backend, config, logger }) {
179
190
  admitRegistration,
180
191
  admitOAuthAccount,
181
192
  accountCreated,
193
+ isOwnerless,
182
194
  isWaiting
183
195
  });
184
196
  }
@@ -56,6 +56,8 @@ function createLocalAuthService({
56
56
  password: {
57
57
  login: true,
58
58
  register: true,
59
+ // Off with AUTH_LOCAL_SELF_REGISTRATION=false: an account registers by invitation, or as the first one.
60
+ selfRegister: config.selfRegistration,
59
61
  change: true,
60
62
  methodToggle: false
61
63
  },
@@ -84,10 +86,14 @@ function createLocalAuthService({
84
86
  devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
85
87
  }
86
88
  });
87
- // While a production server has no account, registering asks for the setup code.
88
- const capabilitiesWaitingForFirstAccount = normalizeAuthCapabilities({
89
+ // While the app has no account, its first one may register, and on a production server that asks for the setup code.
90
+ const capabilitiesForFirstAccount = normalizeAuthCapabilities({
89
91
  ...capabilities,
90
- features: { ...capabilities.features, firstAccountSetupCode: true }
92
+ features: { ...capabilities.features, password: { ...capabilities.features.password, selfRegister: true } }
93
+ });
94
+ const capabilitiesWaitingForFirstAccount = normalizeAuthCapabilities({
95
+ ...capabilitiesForFirstAccount,
96
+ features: { ...capabilitiesForFirstAccount.features, firstAccountSetupCode: true }
91
97
  });
92
98
 
93
99
  const sessions = createLocalSessions({ appProfileProjection, backend, config, profileProjector });
@@ -132,7 +138,10 @@ function createLocalAuthService({
132
138
  });
133
139
 
134
140
  function getCapabilities() {
135
- return firstAccountSetup.isWaiting() ? capabilitiesWaitingForFirstAccount : capabilities;
141
+ if (firstAccountSetup.isWaiting()) {
142
+ return capabilitiesWaitingForFirstAccount;
143
+ }
144
+ return firstAccountSetup.isOwnerless() ? capabilitiesForFirstAccount : capabilities;
136
145
  }
137
146
 
138
147
  function resendRegisterConfirmation(input) {
@@ -696,6 +696,10 @@ test("local auth service accepts a custom stored-password format", async () => {
696
696
  async withTransaction(callback) {
697
697
  return callback({
698
698
  users: {
699
+ // The first-account check reads this at the first registration, in development too.
700
+ async hasAny() {
701
+ return true;
702
+ },
699
703
  async findByEmail(email) {
700
704
  if (email !== "existing@example.com") {
701
705
  return null;
@@ -1357,13 +1361,79 @@ test("in production, email confirmation needs an auth.local.confirmation-sender,
1357
1361
  () => createStartedApp({ env: production }),
1358
1362
  (error) => String(error.details?.cause?.message || error.message || "") ===
1359
1363
  "Local auth confirms each new account's email address in production, and no auth.local.confirmation-sender " +
1360
- "is installed to email the confirmation links. Install one, or set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
1361
- "to let accounts register without confirming their email."
1364
+ "is installed to email the confirmation links. Install one, set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
1365
+ "to let accounts register without confirming their email, or set AUTH_LOCAL_SELF_REGISTRATION=false " +
1366
+ "when accounts are only invited."
1362
1367
  );
1363
1368
  const optedOut = await createStartedApp({ env: { ...production, AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1364
1369
  assert.equal(optedOut.authService.getCapabilities().features.emailConfirmation, false);
1365
1370
  });
1366
1371
 
1372
+ // Confirmation guards self-registration, so an app whose accounts are only invited (or made by the first account)
1373
+ // starts in production without a confirmation sender: anyone else's registration is refused.
1374
+ test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confirmation sender and only invitations register", async (t) => {
1375
+ const app = await createStartedApp({
1376
+ env: {
1377
+ NODE_ENV: "production",
1378
+ AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1379
+ AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1380
+ AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1381
+ AUTH_LOCAL_EMAIL_CONFIRMATION: "",
1382
+ AUTH_LOCAL_SELF_REGISTRATION: "false"
1383
+ },
1384
+ invitationContextResolver: {
1385
+ async resolveInvitationContext({ token, email }) {
1386
+ return token === "invite-for-bea" && email === "bea@example.com" ? { token, source: "test-invite" } : null;
1387
+ }
1388
+ }
1389
+ });
1390
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1391
+ assert.equal(app.authService.getCapabilities().features.emailConfirmation, false);
1392
+ // Until the first account exists, its registration is offered; then only an invited person's.
1393
+ const password = () => app.authService.getCapabilities().features.password;
1394
+ assert.deepEqual([password().register, password().selfRegister], [true, true]);
1395
+ // The first account registers with its setup code.
1396
+ const owner = await app.authService.register({
1397
+ email: "owner@example.com",
1398
+ password: "correct horse battery staple",
1399
+ setupCode: await firstAccountSetupCode(app.storeDir)
1400
+ });
1401
+ assert.equal(owner.actor.email, "owner@example.com");
1402
+ assert.deepEqual([password().register, password().selfRegister], [true, false]);
1403
+ const closed = { status: 403, code: "auth.local.register.closed" };
1404
+ await assert.rejects(() => app.authService.register({ email: "eve@example.com", password: "correct horse battery staple" }), closed);
1405
+ await assert.rejects(() => app.authService.register({
1406
+ email: "eve@example.com",
1407
+ password: "correct horse battery staple",
1408
+ invitation: { token: "invite-for-bea" }
1409
+ }), closed);
1410
+ const invited = await app.authService.register({
1411
+ email: "bea@example.com",
1412
+ password: "correct horse battery staple",
1413
+ invitation: { token: "invite-for-bea" }
1414
+ });
1415
+ assert.equal(invited.actor.email, "bea@example.com");
1416
+ assert.equal(invited.requiresEmailConfirmation, false);
1417
+ });
1418
+
1419
+ test("in development with AUTH_LOCAL_SELF_REGISTRATION=false, the first account's registration is offered until it exists", async (t) => {
1420
+ const app = await createStartedApp({ env: { AUTH_LOCAL_SELF_REGISTRATION: "false", AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1421
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1422
+ const password = () => app.authService.getCapabilities().features.password;
1423
+ assert.equal(password().selfRegister, true);
1424
+ assert.equal(app.authService.getCapabilities().features.firstAccountSetupCode, false, "development needs no setup code");
1425
+ await app.authService.register({ email: "owner@example.com", password: "correct horse battery staple" });
1426
+ assert.equal(password().selfRegister, false);
1427
+ await assert.rejects(
1428
+ () => app.authService.register({ email: "eve@example.com", password: "correct horse battery staple" }),
1429
+ { status: 403, code: "auth.local.register.closed" }
1430
+ );
1431
+ // With self-registration on (the default), anyone may register.
1432
+ const open = await createStartedApp({ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1433
+ t.after(() => fs.rm(open.storeDir, { recursive: true, force: true }));
1434
+ assert.equal(open.authService.getCapabilities().features.password.selfRegister, true);
1435
+ });
1436
+
1367
1437
  test("the confirmation sender emails the link, which is never returned or logged, and the register hook runs on confirming", async (t) => {
1368
1438
  const messages = [];
1369
1439
  const logs = [];