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

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
+ - `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`). 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
6
  - 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
7
  - Upgrading: a custom `auth.local.backend` implements `users.hasAny()`.
7
8
  - 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,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -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),
@@ -1357,13 +1357,57 @@ test("in production, email confirmation needs an auth.local.confirmation-sender,
1357
1357
  () => createStartedApp({ env: production }),
1358
1358
  (error) => String(error.details?.cause?.message || error.message || "") ===
1359
1359
  "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."
1360
+ "is installed to email the confirmation links. Install one, set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
1361
+ "to let accounts register without confirming their email, or set AUTH_LOCAL_SELF_REGISTRATION=false " +
1362
+ "when accounts are only invited."
1362
1363
  );
1363
1364
  const optedOut = await createStartedApp({ env: { ...production, AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1364
1365
  assert.equal(optedOut.authService.getCapabilities().features.emailConfirmation, false);
1365
1366
  });
1366
1367
 
1368
+ // Confirmation guards self-registration, so an app whose accounts are only invited (or made by the first account)
1369
+ // starts in production without a confirmation sender: anyone else's registration is refused.
1370
+ test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confirmation sender and only invitations register", async (t) => {
1371
+ const app = await createStartedApp({
1372
+ env: {
1373
+ NODE_ENV: "production",
1374
+ AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1375
+ AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1376
+ AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1377
+ AUTH_LOCAL_EMAIL_CONFIRMATION: "",
1378
+ AUTH_LOCAL_SELF_REGISTRATION: "false"
1379
+ },
1380
+ invitationContextResolver: {
1381
+ async resolveInvitationContext({ token, email }) {
1382
+ return token === "invite-for-bea" && email === "bea@example.com" ? { token, source: "test-invite" } : null;
1383
+ }
1384
+ }
1385
+ });
1386
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1387
+ assert.equal(app.authService.getCapabilities().features.emailConfirmation, false);
1388
+ // The first account registers with its setup code.
1389
+ const owner = await app.authService.register({
1390
+ email: "owner@example.com",
1391
+ password: "correct horse battery staple",
1392
+ setupCode: await firstAccountSetupCode(app.storeDir)
1393
+ });
1394
+ assert.equal(owner.actor.email, "owner@example.com");
1395
+ const closed = { status: 403, code: "auth.local.register.closed" };
1396
+ await assert.rejects(() => app.authService.register({ email: "eve@example.com", password: "correct horse battery staple" }), closed);
1397
+ await assert.rejects(() => app.authService.register({
1398
+ email: "eve@example.com",
1399
+ password: "correct horse battery staple",
1400
+ invitation: { token: "invite-for-bea" }
1401
+ }), closed);
1402
+ const invited = await app.authService.register({
1403
+ email: "bea@example.com",
1404
+ password: "correct horse battery staple",
1405
+ invitation: { token: "invite-for-bea" }
1406
+ });
1407
+ assert.equal(invited.actor.email, "bea@example.com");
1408
+ assert.equal(invited.requiresEmailConfirmation, false);
1409
+ });
1410
+
1367
1411
  test("the confirmation sender emails the link, which is never returned or logged, and the register hook runs on confirming", async (t) => {
1368
1412
  const messages = [];
1369
1413
  const logs = [];