@jskit-ai/auth-provider-local-core 0.2.10 → 0.2.11

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.
@@ -0,0 +1,186 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
5
+ import { sha256Base64url } from "./tokens.js";
6
+
7
+ // The file in AUTH_LOCAL_STORE_DIR that holds the code while it is needed.
8
+ const SETUP_CODE_FILE = "first-account-setup-code";
9
+ // The variable in which a hosting tool may supply the code itself.
10
+ const SETUP_CODE_ENV = "AUTH_LOCAL_SETUP_CODE";
11
+ // A supplied code needs at least this many letters and digits, as many as a code made here.
12
+ const SETUP_CODE_MIN_CHARACTERS = 20;
13
+ // Crockford's base32: no I, L, O or U, so a code read aloud or retyped stays exact.
14
+ const SETUP_CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
15
+ const SETUP_CODE_LENGTH = 20;
16
+
17
+ function newSetupCode() {
18
+ const characters = Array.from(randomBytes(SETUP_CODE_LENGTH), (byte) => SETUP_CODE_ALPHABET[byte % 32]);
19
+ return characters.join("").match(/.{5}/gu).join("-");
20
+ }
21
+
22
+ // Letter case, spaces, dashes and other punctuation do not matter.
23
+ function normalizedSetupCode(code) {
24
+ return String(code || "").toUpperCase().replace(/[^0-9A-Z]/gu, "");
25
+ }
26
+
27
+ function setupCodeHash(code) {
28
+ return sha256Base64url(normalizedSetupCode(code));
29
+ }
30
+
31
+ function setupCodeRequired() {
32
+ return new AppError(403, "This app has no account yet. Its first account needs the setup code from the server's log or its hosting service.", {
33
+ code: "auth.local.setup.codeRequired"
34
+ });
35
+ }
36
+
37
+ function setupCodeInvalid() {
38
+ return new AppError(403, "That is not this app's setup code. Copy it again from the server's log or its hosting service.", {
39
+ code: "auth.local.setup.codeInvalid"
40
+ });
41
+ }
42
+
43
+ /**
44
+ * The first account of a production server. While local auth has no account,
45
+ * creating one needs a one-time setup code that only the server's operator can
46
+ * read: each start of an ownerless production server makes a new code, writes
47
+ * it in the log and in `first-account-setup-code` in AUTH_LOCAL_STORE_DIR, and
48
+ * keeps only its hash. A hosting tool that supplies the code in
49
+ * AUTH_LOCAL_SETUP_CODE shows it to the operator itself: the server then uses
50
+ * that code at every start, and neither logs nor writes it. The code admits
51
+ * registrations until an account exists, then stops working and its file is
52
+ * deleted. Development needs no code.
53
+ * @param {object} dependencies
54
+ * @param {import("../types.js").AuthLocalBackend} dependencies.backend
55
+ * @param {import("../types.js").AuthLocalConfig} dependencies.config
56
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
57
+ */
58
+ function createFirstAccountSetup({ backend, config, logger }) {
59
+ const codeFile = path.join(config.storeDir, SETUP_CODE_FILE);
60
+ let codeHash = null;
61
+ let started = null;
62
+
63
+ // The file only hands the code to the operator, and the log has it too, so
64
+ // a store directory that cannot be written does not stop the server.
65
+ function writeCodeFile(code) {
66
+ try {
67
+ fs.mkdirSync(config.storeDir, { recursive: true, mode: 0o700 });
68
+ fs.writeFileSync(codeFile, `${code}\n`, { mode: 0o600 });
69
+ fs.chmodSync(codeFile, 0o600);
70
+ return codeFile;
71
+ } catch (error) {
72
+ logger.warn({ error: error.message, firstAccountSetupCodeFile: codeFile }, "Local auth could not write its setup code file.");
73
+ return "";
74
+ }
75
+ }
76
+
77
+ function removeCodeFile() {
78
+ try {
79
+ fs.rmSync(codeFile, { force: true });
80
+ } catch (error) {
81
+ logger.warn({ error: error.message, firstAccountSetupCodeFile: codeFile }, "Local auth could not delete its setup code file.");
82
+ }
83
+ }
84
+
85
+ function finish() {
86
+ codeHash = null;
87
+ removeCodeFile();
88
+ }
89
+
90
+ async function prepare() {
91
+ if (await backend.withTransaction((tx) => tx.users.hasAny())) {
92
+ finish();
93
+ return;
94
+ }
95
+ if (config.setupCode) {
96
+ // The hosting tool shows its code, so a file left by an earlier start would only mislead.
97
+ codeHash = setupCodeHash(config.setupCode);
98
+ removeCodeFile();
99
+ logger.warn(
100
+ { firstAccountSetupCodeEnv: SETUP_CODE_ENV },
101
+ `Local auth has no account yet: register the first account with the setup code in ${SETUP_CODE_ENV}.`
102
+ );
103
+ return;
104
+ }
105
+ const code = newSetupCode();
106
+ codeHash = setupCodeHash(code);
107
+ logger.warn(
108
+ { firstAccountSetupCode: code, firstAccountSetupCodeFile: writeCodeFile(code) },
109
+ "Local auth has no account yet: register the first account with this setup code."
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Checks for an account once, when the server starts; outside production,
115
+ * there is nothing to check. Later calls answer the same check.
116
+ */
117
+ function start() {
118
+ if (!config.isProduction) {
119
+ return Promise.resolve();
120
+ }
121
+ started ??= prepare().catch((error) => {
122
+ started = null;
123
+ throw error;
124
+ });
125
+ return started;
126
+ }
127
+
128
+ async function admitIn(tx, setupCode) {
129
+ if (await tx.users.hasAny()) {
130
+ finish();
131
+ return;
132
+ }
133
+ if (!String(setupCode || "").trim()) {
134
+ throw setupCodeRequired();
135
+ }
136
+ if (setupCodeHash(setupCode) !== codeHash) {
137
+ throw setupCodeInvalid();
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Refuses a registration while the first account needs its setup code and
143
+ * `setupCode` is not it.
144
+ * @param {unknown} setupCode
145
+ */
146
+ async function admitRegistration(setupCode) {
147
+ await start();
148
+ if (codeHash !== null) {
149
+ await backend.withTransaction((tx) => admitIn(tx, setupCode));
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Refuses, in the transaction that would create it, an account made by an
155
+ * OAuth sign-in while the first account needs its setup code: that account
156
+ * registers by password. Call `start()` before the transaction.
157
+ * @param {import("../types.js").AuthLocalBackendTransaction} tx
158
+ */
159
+ async function admitOAuthAccount(tx) {
160
+ if (codeHash !== null) {
161
+ await admitIn(tx, "");
162
+ }
163
+ }
164
+
165
+ /** Called once this server has created an account: the code stops working. */
166
+ function accountCreated() {
167
+ if (codeHash !== null) {
168
+ finish();
169
+ }
170
+ }
171
+
172
+ /** True while the first account needs the setup code, as far as this server knows. */
173
+ function isWaiting() {
174
+ return codeHash !== null;
175
+ }
176
+
177
+ return Object.freeze({
178
+ start,
179
+ admitRegistration,
180
+ admitOAuthAccount,
181
+ accountCreated,
182
+ isWaiting
183
+ });
184
+ }
185
+
186
+ export { SETUP_CODE_ENV, SETUP_CODE_FILE, SETUP_CODE_MIN_CHARACTERS, createFirstAccountSetup, normalizedSetupCode };
@@ -1,7 +1,9 @@
1
1
  export { createLocalAuthService } from "./service.js";
2
2
  export { resolveLocalAuthConfig } from "./config.js";
3
+ export { createLoggedConfirmationSender } from "./emailConfirmation.js";
3
4
  export { createLoggedRecoverySender } from "./passwordFlows.js";
4
5
  export { createLocalFileBackend } from "./fileBackend.js";
6
+ export { SETUP_CODE_ENV, SETUP_CODE_FILE, createFirstAccountSetup } from "./firstAccountSetup.js";
5
7
  export {
6
8
  LOCAL_AUTH_USER_REGISTERED_EVENT,
7
9
  createLocalAuthRegisterHookDecorator
@@ -17,13 +17,23 @@ const OAUTH_REDIRECT_PATH = "/auth/login";
17
17
  * @param {object} dependencies
18
18
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
19
19
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
20
+ * @param {import("../types.js").AuthLocalFirstAccountSetup} dependencies.firstAccountSetup
20
21
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
21
22
  * @param {Map<string, import("../types.js").AuthLocalOAuthProvider>} dependencies.oauthProvidersById
22
23
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
23
24
  * @param {ReturnType<typeof import("./securityStatus.js").createLocalSecurityStatus>} dependencies.securityStatus
24
25
  * @param {import("../types.js").AuthLocalSessions} dependencies.sessions
25
26
  */
26
- function createLocalOAuthFlows({ backend, config, logger, oauthProvidersById, profileProjector, securityStatus, sessions }) {
27
+ function createLocalOAuthFlows({
28
+ backend,
29
+ config,
30
+ firstAccountSetup,
31
+ logger,
32
+ oauthProvidersById,
33
+ profileProjector,
34
+ securityStatus,
35
+ sessions
36
+ }) {
27
37
  const { isProduction, oauthEnabled } = config;
28
38
  const OAUTH_ATTEMPT_COOKIE = hostOnlyCookieName(OAUTH_ATTEMPT_COOKIE_NAME, isProduction);
29
39
  const oauthRedirectUri = oauthEnabled ? `${config.appPublicUrl.replace(/\/$/u, "")}${OAUTH_REDIRECT_PATH}` : "";
@@ -89,11 +99,13 @@ function createLocalOAuthFlows({ backend, config, logger, oauthProvidersById, pr
89
99
  * new user created like register; profile sync then provisions it as usual.
90
100
  */
91
101
  async function signInWithOAuthIdentity(identity) {
102
+ await firstAccountSetup.start();
92
103
  const result = await backend.withTransaction(async (tx) => {
93
104
  const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
94
105
  let user = linked ? await tx.users.findById(linked.userId) : await tx.users.findByEmail(identity.email);
95
106
  const registered = !linked && !user;
96
107
  if (registered) {
108
+ await firstAccountSetup.admitOAuthAccount(tx);
97
109
  user = await tx.users.create({
98
110
  id: createId("usr"),
99
111
  email: identity.email,
@@ -114,6 +126,9 @@ function createLocalOAuthFlows({ backend, config, logger, oauthProvidersById, pr
114
126
  }
115
127
  return { user, registered, session: await sessions.createSessionForUser(tx, user) };
116
128
  });
129
+ if (result.registered) {
130
+ firstAccountSetup.accountCreated();
131
+ }
117
132
  return {
118
133
  ...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector })),
119
134
  registered: result.registered
@@ -95,7 +95,7 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
95
95
  }
96
96
 
97
97
  async function resetPassword(input, request) {
98
- validatePasswordInput(input.password);
98
+ validatePasswordInput(input.password, config.passwordMinLength);
99
99
  const payload = verifySignedToken(sessions.readRecoveryAccessToken(request), config.sessionSecret);
100
100
  if (!payload?.sub || !payload?.sid) {
101
101
  throw createAuthError(AUTH_TEXTS.sessionRequired);
@@ -109,9 +109,13 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
109
109
  if (session.purpose !== "recovery") {
110
110
  throw new AppError(401, "Recovery session required.", { code: "auth.local.recovery.sessionRequired" });
111
111
  }
112
- await tx.users.updatePassword(String(payload.sub), password);
112
+ const user = await tx.users.updatePassword(String(payload.sub), password);
113
113
  await tx.sessions.revokeForUser(String(payload.sub));
114
114
  await tx.recovery.consumeForUser(String(payload.sub));
115
+ // Recovery is the way back in for an account that failed sign-ins keep waiting.
116
+ if (user) {
117
+ await tx.signInFailures.clear(user.email);
118
+ }
115
119
  });
116
120
  return {
117
121
  ok: true,
@@ -120,7 +124,7 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
120
124
  }
121
125
 
122
126
  async function changePassword(request, input) {
123
- validatePasswordInput(input.newPassword);
127
+ validatePasswordInput(input.newPassword, config.passwordMinLength);
124
128
  const authResult = await sessions.authenticateRequest(request);
125
129
  if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
126
130
  throw createAuthError(AUTH_TEXTS.sessionRequired);
@@ -53,7 +53,8 @@ function logNonBlockingHookFailure({ logger, hook, error }) {
53
53
  /**
54
54
  * @param {object} run
55
55
  * @param {{ hookId: string, blocking: boolean, handle: LocalAuthRegisterHook["handle"] }} run.hook
56
- * @param {object} run.result The answer of register, or of an oauthComplete that registered the user.
56
+ * @param {object} run.result The answer of a register or confirmRegistration that created the
57
+ * account, or of an oauthComplete that registered the user.
57
58
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} run.logger
58
59
  */
59
60
  async function runRegisterHook({ hook, result, logger }) {
@@ -75,7 +76,9 @@ async function runRegisterHook({ hook, result, logger }) {
75
76
 
76
77
  /**
77
78
  * An auth service decorator that runs an application's hook for each user
78
- * that registers, by password or by a first OAuth sign-in.
79
+ * that registers, by password or by a first OAuth sign-in. A registration
80
+ * that waits for its email to be confirmed has no account yet: the hook runs
81
+ * when confirmRegistration creates it.
79
82
  * @param {object} options
80
83
  * @param {string} [options.decoratorId]
81
84
  * @param {number} [options.order]
@@ -97,6 +100,16 @@ function createLocalAuthRegisterHookDecorator({ decoratorId = "auth.local.regist
97
100
  enumerable: true,
98
101
  value: async function register(input) {
99
102
  const result = await authService.register(input);
103
+ if (result.requiresEmailConfirmation !== true) {
104
+ await runRegisterHook({ hook: registerHook, result, logger });
105
+ }
106
+ return result;
107
+ }
108
+ },
109
+ confirmRegistration: {
110
+ enumerable: true,
111
+ value: async function confirmRegistration(input) {
112
+ const result = await authService.confirmRegistration(input);
100
113
  await runRegisterHook({ hook: registerHook, result, logger });
101
114
  return result;
102
115
  }
@@ -4,6 +4,8 @@ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
4
4
  import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
5
5
  import { createLocalAccounts } from "./accounts.js";
6
6
  import { PROVIDER_ID } from "./authPayloads.js";
7
+ import { createLocalEmailConfirmation } from "./emailConfirmation.js";
8
+ import { createFirstAccountSetup } from "./firstAccountSetup.js";
7
9
  import { createLocalOAuthFlows } from "./oauthFlows.js";
8
10
  import { createLocalPasswordFlows } from "./passwordFlows.js";
9
11
  import { normalizePasswordStrategy } from "./passwords.js";
@@ -16,6 +18,10 @@ import { createLocalSessions } from "./sessions.js";
16
18
  * @param {object} dependencies
17
19
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
18
20
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
21
+ * @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
22
+ * `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender.
23
+ * @param {import("../types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup] The first
24
+ * account's setup code, already started by the provider; by default, one that starts on first use.
19
25
  * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
20
26
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
21
27
  * @param {import("../types.js").AuthLocalPasswordStrategy} dependencies.passwordStrategy The
@@ -28,6 +34,8 @@ import { createLocalSessions } from "./sessions.js";
28
34
  function createLocalAuthService({
29
35
  backend,
30
36
  config,
37
+ confirmationSender,
38
+ firstAccountSetup: givenFirstAccountSetup = null,
31
39
  invitationContextResolver,
32
40
  logger,
33
41
  passwordStrategy,
@@ -35,6 +43,7 @@ function createLocalAuthService({
35
43
  recoverySender
36
44
  }) {
37
45
  const passwords = normalizePasswordStrategy(passwordStrategy);
46
+ const firstAccountSetup = givenFirstAccountSetup ?? createFirstAccountSetup({ backend, config, logger });
38
47
  const oauthProvidersById = new Map(config.oauthProviders.map((provider) => [provider.id, provider]));
39
48
  const { oauthEnabled, recoveryEnabled } = config;
40
49
  const appProfileProjection = profileProjector !== noAppProfiles;
@@ -62,7 +71,8 @@ function createLocalAuthService({
62
71
  enabled: oauthEnabled,
63
72
  providers: config.oauthProviders.map(({ id, label }) => ({ id, label }))
64
73
  },
65
- emailConfirmation: false,
74
+ emailConfirmation: config.emailConfirmation,
75
+ emailConfirmationCode: config.emailConfirmation,
66
76
  profileUpdate: true,
67
77
  providerLinking: {
68
78
  start: oauthEnabled,
@@ -74,12 +84,28 @@ function createLocalAuthService({
74
84
  devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
75
85
  }
76
86
  });
87
+ // While a production server has no account, registering asks for the setup code.
88
+ const capabilitiesWaitingForFirstAccount = normalizeAuthCapabilities({
89
+ ...capabilities,
90
+ features: { ...capabilities.features, firstAccountSetupCode: true }
91
+ });
77
92
 
78
93
  const sessions = createLocalSessions({ appProfileProjection, backend, config, profileProjector });
94
+ const emailConfirmation = createLocalEmailConfirmation({
95
+ backend,
96
+ config,
97
+ confirmationSender,
98
+ firstAccountSetup,
99
+ invitationContextResolver,
100
+ profileProjector,
101
+ sessions
102
+ });
79
103
  const accounts = createLocalAccounts({
80
104
  appProfileProjection,
81
105
  backend,
82
106
  config,
107
+ emailConfirmation,
108
+ firstAccountSetup,
83
109
  invitationContextResolver,
84
110
  passwords,
85
111
  profileProjector,
@@ -97,6 +123,7 @@ function createLocalAuthService({
97
123
  const oauthFlows = createLocalOAuthFlows({
98
124
  backend,
99
125
  config,
126
+ firstAccountSetup,
100
127
  logger,
101
128
  oauthProvidersById,
102
129
  profileProjector,
@@ -105,11 +132,21 @@ function createLocalAuthService({
105
132
  });
106
133
 
107
134
  function getCapabilities() {
108
- return capabilities;
135
+ return firstAccountSetup.isWaiting() ? capabilitiesWaitingForFirstAccount : capabilities;
109
136
  }
110
137
 
111
- function resendRegisterConfirmation() {
112
- return throwUnsupportedAuthOperation("resendRegisterConfirmation");
138
+ function resendRegisterConfirmation(input) {
139
+ if (!config.emailConfirmation) {
140
+ return throwUnsupportedAuthOperation("resendRegisterConfirmation");
141
+ }
142
+ return emailConfirmation.resend(input);
143
+ }
144
+
145
+ function confirmRegistration(input) {
146
+ if (!config.emailConfirmation) {
147
+ return throwUnsupportedAuthOperation("confirmRegistration");
148
+ }
149
+ return emailConfirmation.confirm(input);
113
150
  }
114
151
 
115
152
  function requestOtpLogin() {
@@ -135,6 +172,7 @@ function createLocalAuthService({
135
172
  clearSessionCookies: sessions.clearSessionCookies,
136
173
  register: accounts.register,
137
174
  resendRegisterConfirmation,
175
+ confirmRegistration,
138
176
  login: accounts.login,
139
177
  requestOtpLogin,
140
178
  verifyOtpLogin,
@@ -0,0 +1,123 @@
1
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { parsePositiveInteger } from "@jskit-ai/kernel/server/runtime";
3
+
4
+ /**
5
+ * The failed sign-ins in a row after which an account must wait before its next
6
+ * attempt, the first wait, and the longest: each further failure doubles the
7
+ * wait, up to the longest. NIST SP 800-63B gives 30 seconds up to an hour as
8
+ * its example.
9
+ */
10
+ const DEFAULT_SIGN_IN_THROTTLE = Object.freeze({
11
+ failuresBeforeWait: 5,
12
+ firstWaitSeconds: 30,
13
+ maxWaitSeconds: 3600
14
+ });
15
+
16
+ /** NIST SP 800-63B: at most 100 consecutive failed attempts on one account. */
17
+ const MAX_FAILURES_BEFORE_WAIT = 100;
18
+
19
+ /** An account's failures are forgotten a day after its last one. */
20
+ const FORGET_FAILURES_AFTER_MS = 24 * 60 * 60 * 1000;
21
+
22
+ function readSetting(env, name, fallback) {
23
+ const raw = env[name];
24
+ if (raw === undefined || String(raw).trim() === "") {
25
+ return fallback;
26
+ }
27
+ const value = parsePositiveInteger(raw);
28
+ if (value === null) {
29
+ throw new Error(`${name} must be a positive whole number.`);
30
+ }
31
+ return value;
32
+ }
33
+
34
+ /**
35
+ * How failed sign-ins slow down one account, from AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT,
36
+ * AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS and AUTH_LOCAL_SIGN_IN_MAX_WAIT_SECONDS.
37
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
38
+ */
39
+ function resolveSignInThrottle(env) {
40
+ const failuresBeforeWait = readSetting(
41
+ env,
42
+ "AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT",
43
+ DEFAULT_SIGN_IN_THROTTLE.failuresBeforeWait
44
+ );
45
+ const firstWaitSeconds = readSetting(
46
+ env,
47
+ "AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS",
48
+ DEFAULT_SIGN_IN_THROTTLE.firstWaitSeconds
49
+ );
50
+ const maxWaitSeconds = readSetting(env, "AUTH_LOCAL_SIGN_IN_MAX_WAIT_SECONDS", DEFAULT_SIGN_IN_THROTTLE.maxWaitSeconds);
51
+ if (failuresBeforeWait > MAX_FAILURES_BEFORE_WAIT) {
52
+ throw new Error(`AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT must be at most ${MAX_FAILURES_BEFORE_WAIT}.`);
53
+ }
54
+ if (maxWaitSeconds < firstWaitSeconds) {
55
+ throw new Error("AUTH_LOCAL_SIGN_IN_MAX_WAIT_SECONDS must be at least AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS.");
56
+ }
57
+ return Object.freeze({
58
+ failuresBeforeWait,
59
+ firstWaitMs: firstWaitSeconds * 1000,
60
+ maxWaitMs: maxWaitSeconds * 1000
61
+ });
62
+ }
63
+
64
+ /**
65
+ * The milliseconds the account must still wait before its next sign-in, or 0.
66
+ * @param {{ lockedUntil: string } | null} record
67
+ * @param {number} now
68
+ */
69
+ function signInWaitMs(record, now) {
70
+ const lockedUntil = Date.parse(record?.lockedUntil || "");
71
+ return Number.isFinite(lockedUntil) && lockedUntil > now ? lockedUntil - now : 0;
72
+ }
73
+
74
+ /**
75
+ * The account's record after one more failed sign-in.
76
+ * @param {ReturnType<typeof resolveSignInThrottle>} throttle
77
+ * @param {{ failures: number, lastFailedAt: string } | null} record
78
+ * @param {string} email
79
+ * @param {number} now
80
+ */
81
+ function recordSignInFailure(throttle, record, email, now) {
82
+ const lastFailedAt = Date.parse(record?.lastFailedAt || "");
83
+ const recent = Number.isFinite(lastFailedAt) && now - lastFailedAt < FORGET_FAILURES_AFTER_MS;
84
+ const failures = (recent ? record.failures : 0) + 1;
85
+ const waits = failures - throttle.failuresBeforeWait + 1;
86
+ const waitMs = waits > 0 ? Math.min(throttle.maxWaitMs, throttle.firstWaitMs * 2 ** (waits - 1)) : 0;
87
+ return {
88
+ email,
89
+ failures,
90
+ lastFailedAt: new Date(now).toISOString(),
91
+ lockedUntil: waitMs > 0 ? new Date(now + waitMs).toISOString() : ""
92
+ };
93
+ }
94
+
95
+ /** Failure records whose last failure is old enough to forget. */
96
+ function forgottenFailuresBefore(now) {
97
+ return new Date(now - FORGET_FAILURES_AFTER_MS).toISOString();
98
+ }
99
+
100
+ /**
101
+ * The refusal of a sign-in while its account waits, with the minutes to wait;
102
+ * Retry-After gives the exact seconds.
103
+ * @param {number} waitMs
104
+ */
105
+ function signInLockedError(waitMs) {
106
+ const seconds = Math.max(1, Math.ceil(waitMs / 1000));
107
+ const count = Math.ceil(seconds / 60);
108
+ const unit = count === 1 ? "minute" : "minutes";
109
+ return new AppError(429, `Too many failed sign-ins for this account. Try again in ${count} ${unit}.`, {
110
+ code: "auth.local.login.locked",
111
+ params: { count, retryAfterSeconds: seconds },
112
+ headers: { "retry-after": String(seconds) }
113
+ });
114
+ }
115
+
116
+ export {
117
+ DEFAULT_SIGN_IN_THROTTLE,
118
+ forgottenFailuresBefore,
119
+ recordSignInFailure,
120
+ resolveSignInThrottle,
121
+ signInLockedError,
122
+ signInWaitMs
123
+ };
@@ -5,7 +5,9 @@ import {
5
5
  import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
6
6
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
7
  import { resolveLocalAuthConfig } from "../lib/config.js";
8
+ import { createLoggedConfirmationSender } from "../lib/emailConfirmation.js";
8
9
  import { createLocalFileBackend } from "../lib/fileBackend.js";
10
+ import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
9
11
  import { createLoggedRecoverySender } from "../lib/passwordFlows.js";
10
12
  import { scryptPasswordStrategy } from "../lib/passwords.js";
11
13
  import { createLocalAuthService } from "../lib/service.js";
@@ -20,6 +22,7 @@ const AuthLocalProvider = defineProvider({
20
22
  },
21
23
  optional: {
22
24
  backend: "auth.local.backend",
25
+ confirmationSender: "auth.local.confirmation-sender",
23
26
  passwordStrategy: "auth.local.password-strategy",
24
27
  profileProjector: "auth.profile.projector",
25
28
  recoverySender: "auth.local.recovery-sender"
@@ -34,6 +37,8 @@ const AuthLocalProvider = defineProvider({
34
37
  * @param {object} dependencies
35
38
  * @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
36
39
  * @param {import("../types.js").AuthLocalBackend | null} dependencies.backend The `auth.local.backend`, when one is installed.
40
+ * @param {import("../types.js").AuthLocalConfirmationSender | null} dependencies.confirmationSender The
41
+ * `auth.local.confirmation-sender`, when one is installed.
37
42
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
38
43
  * @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
39
44
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
@@ -41,13 +46,23 @@ const AuthLocalProvider = defineProvider({
41
46
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
42
47
  * @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
43
48
  */
44
- boot({ appRoot, backend, env, extensions, logger, passwordStrategy, profileProjector, recoverySender }, { outputs }) {
49
+ async boot(
50
+ { appRoot, backend, confirmationSender, env, extensions, logger, passwordStrategy, profileProjector, recoverySender },
51
+ { outputs }
52
+ ) {
45
53
  const fileBackend = backend === null;
46
54
  const emailRecovery = recoverySender !== null;
47
- const config = resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery });
55
+ const emailConfirmationSender = confirmationSender !== null;
56
+ const config = resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender });
57
+ const localBackend = fileBackend ? createLocalFileBackend({ storeDir: config.storeDir }) : backend;
58
+ // A production server without accounts logs its setup code as it starts.
59
+ const firstAccountSetup = createFirstAccountSetup({ backend: localBackend, config, logger });
60
+ await firstAccountSetup.start();
48
61
  const baseService = createLocalAuthService({
49
- backend: fileBackend ? createLocalFileBackend({ storeDir: config.storeDir }) : backend,
62
+ backend: localBackend,
50
63
  config,
64
+ confirmationSender: emailConfirmationSender ? confirmationSender : createLoggedConfirmationSender(logger),
65
+ firstAccountSetup,
51
66
  invitationContextResolver: extensions.resolveInvitationContextResolver(),
52
67
  logger,
53
68
  passwordStrategy: passwordStrategy ?? scryptPasswordStrategy,