@jskit-ai/auth-core 0.2.8 → 0.2.9

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,11 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The register body takes `setupCode`, the first account's one-time setup code, and the capability `features.firstAccountSetupCode` says a provider is waiting for it. New message key: `jskit.auth.validation.setupCodeInvalid`.
6
+ - Registration confirmation: the action and command `auth.register.confirm` (`POST /api/register/confirm`, body `{ token }`, answer `{ ok, email, username, message }` with a message code) confirm a registration's email from the code in its link, and `authApi.confirmRegistration()` calls it. `AuthService.confirmRegistration(input)` creates the waiting account and its session; a provider without it answers `AUTH_OPERATION_UNSUPPORTED`. The capability `features.emailConfirmationCode` says the provider takes a code that way. The register and resend answers may carry `confirmationUrl`, the link itself in development. New message keys: `jskit.auth.login.emailUnconfirmed` (refused sign-in, status 403) and `jskit.auth.validation.confirmationCodeRequired`.
7
+ - The dev auth policy and the CSRF cookie's default decide production with the kernel's `isProductionEnv`, the check every JSKIT package now shares; what counts as production is unchanged. `./server/devAuth` no longer exports `isProductionNodeEnv(nodeEnv)`: call `isProductionEnv(env)` from `@jskit-ai/kernel/server/runtime/runtimeMode` instead.
8
+ - The auth policy no longer registers `@fastify/rate-limit`, which it did after the routes existed, so no route limit applied; the kernel now registers it before the routes and enforces each route's `rateLimit`.
9
+
5
10
  - Every auth command's field messages (sign-in, registration, one-time codes, OAuth, password reset and recovery, dev sign-in) are sent in the coded form `{ code, message, params }`, so their field errors translate. The English is unchanged.
6
11
  - The default access-denied texts carry the messageCodes `auth.denied.notAllowlistedDefault`, `auth.denied.blockedDefault` and `auth.denied.unspecified`; `./shared/authDenied` adds `AUTH_DENIED_DEFAULT_TEXTS` and `AUTH_DENIED_FALLBACK_TEXT` (`{ message, messageCode }`). `AUTH_DENIED_DEFAULT_MESSAGES` and the English are unchanged.
7
12
 
package/locales/en.json CHANGED
@@ -6,7 +6,8 @@
6
6
  "unavailable": "Authentication service temporarily unavailable. Please retry."
7
7
  },
8
8
  "login": {
9
- "invalidCredentials": "Invalid email or password."
9
+ "invalidCredentials": "Invalid email or password.",
10
+ "emailUnconfirmed": "Confirm your email address before signing in: open the link we emailed you, or ask for a new one."
10
11
  },
11
12
  "policy": {
12
13
  "ownerUnresolved": "Route owner could not be resolved.",
@@ -50,7 +51,9 @@
50
51
  "otpTypeUnsupported": "Only email OTP verification is supported.",
51
52
  "recoveryCodeInvalid": "Recovery code is invalid.",
52
53
  "recoveryTokenHashInvalid": "Recovery token hash is invalid.",
53
- "recoveryTypeUnsupported": "Only recovery links are supported."
54
+ "recoveryTypeUnsupported": "Only recovery links are supported.",
55
+ "confirmationCodeRequired": "Enter the confirmation code or link from the email.",
56
+ "setupCodeInvalid": "Enter the setup code from the server's log or its hosting service."
54
57
  },
55
58
  "profile": {
56
59
  "displayNameRequired": "Display name is required."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-core",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -48,6 +48,7 @@
48
48
  "./shared/commands": "./src/shared/commands/index.js",
49
49
  "./shared/commands/authRegisterCommand": "./src/shared/commands/authRegisterCommand.js",
50
50
  "./shared/commands/authRegisterConfirmationResendCommand": "./src/shared/commands/authRegisterConfirmationResendCommand.js",
51
+ "./shared/commands/authRegisterConfirmCommand": "./src/shared/commands/authRegisterConfirmCommand.js",
51
52
  "./shared/commands/authLoginPasswordCommand": "./src/shared/commands/authLoginPasswordCommand.js",
52
53
  "./shared/commands/authLoginOtpRequestCommand": "./src/shared/commands/authLoginOtpRequestCommand.js",
53
54
  "./shared/commands/authLoginOtpVerifyCommand": "./src/shared/commands/authLoginOtpVerifyCommand.js",
@@ -64,7 +65,6 @@
64
65
  "dependencies": {
65
66
  "@fastify/cookie": "^11.1.2",
66
67
  "@fastify/csrf-protection": "^8.0.1",
67
- "@fastify/rate-limit": "^11.2.0",
68
68
  "json-rest-schema": "^1.0.17"
69
69
  },
70
70
  "jskit": {
@@ -143,6 +143,6 @@
143
143
  }
144
144
  },
145
145
  "peerDependencies": {
146
- "@jskit-ai/kernel": "0.2.8"
146
+ "@jskit-ai/kernel": "0.2.9"
147
147
  }
148
148
  }
@@ -10,6 +10,7 @@ import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
10
10
  import {
11
11
  authRegisterCommand,
12
12
  authRegisterConfirmationResendCommand,
13
+ authRegisterConfirmCommand,
13
14
  authLoginPasswordCommand,
14
15
  authLoginOtpRequestCommand,
15
16
  authLoginOtpVerifyCommand,
@@ -61,6 +62,15 @@ function createAuthActions({ authService }) {
61
62
  input: authRegisterConfirmationResendCommand.operation.body,
62
63
  execute: (input) => authService.resendRegisterConfirmation(input)
63
64
  }),
65
+ Object.freeze({
66
+ id: "auth.register.confirm",
67
+ version: 1,
68
+ kind: "command",
69
+ channels: ["api", "internal"],
70
+ surfaces: ["*"],
71
+ input: authRegisterConfirmCommand.operation.body,
72
+ execute: (input) => authService.confirmRegistration(input)
73
+ }),
64
74
  Object.freeze({
65
75
  id: "auth.login.password",
66
76
  version: 1,
@@ -9,6 +9,8 @@ const AUTH_TEXTS = Object.freeze({
9
9
  sessionRequired: Object.freeze({ status: 401, code: "auth.session.required" }),
10
10
  sessionUnavailable: Object.freeze({ status: 503, code: "auth.session.unavailable" }),
11
11
  invalidCredentials: Object.freeze({ status: 401, code: "auth.login.invalidCredentials" }),
12
+ // The password is right, but the registration's email is not confirmed yet.
13
+ emailUnconfirmed: Object.freeze({ status: 403, code: "auth.login.emailUnconfirmed" }),
12
14
  emailRequired: Object.freeze({ status: 400, code: "auth.validation.emailRequired" }),
13
15
  devUserRequired: Object.freeze({ status: 400, code: "auth.dev.userRequired" }),
14
16
  devUserNotFound: Object.freeze({ status: 400, code: "auth.dev.userNotFound" }),
@@ -1,3 +1,4 @@
1
+ import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
1
2
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
3
  import { timingSafeEqual } from "node:crypto";
3
4
  import { parseBooleanFlag } from "./booleanFlag.js";
@@ -53,15 +54,6 @@ function isLocalDevAuthRequest(request) {
53
54
  return isLoopbackIp(remoteAddress) && isLoopbackHostname(normalizeRequestHostname(request));
54
55
  }
55
56
 
56
- /**
57
- * True when NODE_ENV names production, in any letter case. Every auth package
58
- * decides "production" this one way.
59
- * @param {unknown} nodeEnv
60
- */
61
- function isProductionNodeEnv(nodeEnv) {
62
- return String(nodeEnv || "").trim().toLowerCase() === "production";
63
- }
64
-
65
57
  function resolveDevAuthPolicy({
66
58
  enabled = false,
67
59
  nodeEnv = "development",
@@ -69,7 +61,7 @@ function resolveDevAuthPolicy({
69
61
  } = {}) {
70
62
  return Object.freeze({
71
63
  enabled: parseBooleanFlag(enabled, false),
72
- isProduction: isProductionNodeEnv(nodeEnv),
64
+ isProduction: isProductionEnv({ NODE_ENV: nodeEnv }),
73
65
  secret: String(secret || "").trim()
74
66
  });
75
67
  }
@@ -140,7 +132,6 @@ export {
140
132
  ensureDevAuthRuntimeAvailable,
141
133
  isDevAuthBootstrapEnabled,
142
134
  isLocalDevAuthRequest,
143
- isProductionNodeEnv,
144
135
  resolveDevAuthPolicy,
145
136
  resolveDevAuthPolicyFromEnv
146
137
  };
@@ -1,8 +1,7 @@
1
1
  import fastifyCookie from "@fastify/cookie";
2
2
  import fastifyCsrfProtection from "@fastify/csrf-protection";
3
- import fastifyRateLimit from "@fastify/rate-limit";
4
3
  import { safeRequestUrl } from "@jskit-ai/kernel/server/runtime/requestUrl";
5
- import { isProductionNodeEnv } from "../devAuth.js";
4
+ import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
6
5
  import { hostOnlyCookieName } from "../utils.js";
7
6
 
8
7
  import { assertAuthPolicyDeps, normalizeActorResolution } from "./authPolicySupport.js";
@@ -10,9 +9,6 @@ import { AUTH_POLICY_DENY_REASONS, createAuthPolicyError } from "./errors.js";
10
9
  import { AUTH_POLICIES, CONTEXT_POLICIES, resolveAuthPolicyMeta } from "./routeMeta.js";
11
10
 
12
11
  const DEFAULT_API_PREFIX = "/api/";
13
- const DEFAULT_RATE_LIMIT_PLUGIN_OPTIONS = Object.freeze({
14
- global: false
15
- });
16
12
  const DEFAULT_UNSAFE_METHODS = Object.freeze(["POST", "PUT", "PATCH", "DELETE"]);
17
13
 
18
14
  function normalizeUnsafeMethods(methodsValue) {
@@ -25,16 +21,6 @@ function normalizeApiPrefix(value) {
25
21
  return normalized || DEFAULT_API_PREFIX;
26
22
  }
27
23
 
28
- function normalizeRateLimitPluginOptions(value) {
29
- if (!value || typeof value !== "object") {
30
- return {
31
- ...DEFAULT_RATE_LIMIT_PLUGIN_OPTIONS
32
- };
33
- }
34
-
35
- return value;
36
- }
37
-
38
24
  function resolveRouteConfig(request) {
39
25
  if (!request.routeOptions || typeof request.routeOptions !== "object") {
40
26
  return {};
@@ -87,7 +73,6 @@ function authPolicyPlugin(deps = {}, options = {}) {
87
73
  const { resolveActor, resolveContext, hasPermission, onPolicyDenied } = assertAuthPolicyDeps(deps);
88
74
  const apiPrefix = normalizeApiPrefix(options.apiPrefix);
89
75
  const unsafeMethods = normalizeUnsafeMethods(options.unsafeMethods);
90
- const rateLimitPluginOptions = normalizeRateLimitPluginOptions(options.rateLimitPluginOptions);
91
76
  const csrfCookieOpts =
92
77
  options.csrfCookieOpts && typeof options.csrfCookieOpts === "object" ? options.csrfCookieOpts : {};
93
78
  // createError(status, englishMessage, { code }) builds each refusal.
@@ -96,7 +81,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
96
81
  // CSRF uses tokens checked against a secret cookie, never SameSite alone. In
97
82
  // production that cookie is host-only (__Host-), so a sibling host cannot plant
98
83
  // a secret it knows and forge tokens.
99
- const csrfCookieSecure = typeof csrfCookieOpts.secure === "boolean" ? csrfCookieOpts.secure : isProductionNodeEnv(options.nodeEnv);
84
+ const csrfCookieSecure = typeof csrfCookieOpts.secure === "boolean" ? csrfCookieOpts.secure : isProductionEnv({ NODE_ENV: options.nodeEnv });
100
85
  const csrfCookieOptions = {
101
86
  path: "/",
102
87
  sameSite: "lax",
@@ -108,7 +93,6 @@ function authPolicyPlugin(deps = {}, options = {}) {
108
93
 
109
94
  return async function registerAuthPolicyPlugin(fastify) {
110
95
  await fastify.register(fastifyCookie);
111
- await fastify.register(fastifyRateLimit, rateLimitPluginOptions);
112
96
  await fastify.register(fastifyCsrfProtection, {
113
97
  getToken: resolveCsrfTokenFn,
114
98
  cookieKey: hostOnlyCookieName("_csrf", csrfCookieHostOnly),
@@ -76,6 +76,8 @@
76
76
  * @property {() => boolean} isDevAuthBootstrapEnabled
77
77
  * @property {(input: object) => Promise<object>} register
78
78
  * @property {(input: object) => Promise<object>} resendRegisterConfirmation
79
+ * @property {(input: { token: string }) => Promise<object>} confirmRegistration Creates the account a
80
+ * registration waited to create until its email was confirmed, from its link's code, and signs the person in.
79
81
  * @property {(input: object) => Promise<object>} login
80
82
  * @property {(input: object) => Promise<object>} requestOtpLogin
81
83
  * @property {(input: object) => Promise<object>} verifyOtpLogin
@@ -23,6 +23,10 @@ function createApi({ request }) {
23
23
  return request(AUTH_PATHS.REGISTER_CONFIRMATION_RESEND, { method: "POST", body: payload });
24
24
  }
25
25
 
26
+ function confirmRegistration(payload) {
27
+ return request(AUTH_PATHS.REGISTER_CONFIRM, { method: "POST", body: payload });
28
+ }
29
+
26
30
  function login(payload) {
27
31
  return request(AUTH_PATHS.LOGIN, { method: "POST", body: payload });
28
32
  }
@@ -76,6 +80,7 @@ function createApi({ request }) {
76
80
  session,
77
81
  register,
78
82
  resendRegisterConfirmation,
83
+ confirmRegistration,
79
84
  login,
80
85
  requestOtp,
81
86
  verifyOtp,
@@ -10,6 +10,7 @@ const AUTH_PASSWORD_RECOVERY_DELIVERIES = Object.freeze(["email", "dev-log", "de
10
10
  const AUTH_OPERATION_FEATURES = Object.freeze({
11
11
  register: "password.register",
12
12
  resendRegisterConfirmation: "emailConfirmation",
13
+ confirmRegistration: "emailConfirmationCode",
13
14
  login: "password.login",
14
15
  requestOtpLogin: "otp.login",
15
16
  verifyOtpLogin: "otp.login",
@@ -143,6 +144,8 @@ function normalizeAuthCapabilities(value = {}) {
143
144
  : null
144
145
  }),
145
146
  emailConfirmation: normalizeBoolean(featuresSource.emailConfirmation),
147
+ emailConfirmationCode: normalizeBoolean(featuresSource.emailConfirmationCode),
148
+ firstAccountSetupCode: normalizeBoolean(featuresSource.firstAccountSetupCode),
146
149
  profileUpdate: normalizeBoolean(featuresSource.profileUpdate),
147
150
  providerLinking: Object.freeze({
148
151
  start: normalizeBoolean(providerLinkingSource.start),
@@ -1,6 +1,7 @@
1
1
  const AUTH_PATHS = Object.freeze({
2
2
  REGISTER: "/api/register",
3
3
  REGISTER_CONFIRMATION_RESEND: "/api/register/confirmation/resend",
4
+ REGISTER_CONFIRM: "/api/register/confirm",
4
5
  LOGIN: "/api/login",
5
6
  LOGIN_OTP_REQUEST: "/api/login/otp/request",
6
7
  LOGIN_OTP_VERIFY: "/api/login/otp/verify",
@@ -159,12 +159,38 @@ const okMessageOutputValidator = deepFreeze({
159
159
  mode: "replace"
160
160
  });
161
161
 
162
+ // In development, when no email is sent, the confirmation link itself, so the
163
+ // sign-in screen can show it.
164
+ const confirmationUrlFieldDefinition = deepFreeze({ type: "string", required: false, minLength: 1, maxLength: 4096 });
165
+
162
166
  const registerOutputValidator = deepFreeze({
163
167
  schema: createSchema({
164
168
  ok: { type: "boolean", required: true },
165
169
  requiresEmailConfirmation: { type: "boolean", required: true },
166
170
  username: { type: "string", required: false, minLength: 1, maxLength: 120 },
167
171
  message: { type: "string", required: false, minLength: 1 },
172
+ confirmationUrl: confirmationUrlFieldDefinition,
173
+ ...messageCodeFieldDefinitions
174
+ }),
175
+ mode: "replace"
176
+ });
177
+
178
+ const registerConfirmationResendOutputValidator = deepFreeze({
179
+ schema: createSchema({
180
+ ok: { type: "boolean", required: true },
181
+ message: { type: "string", required: true, minLength: 1 },
182
+ confirmationUrl: confirmationUrlFieldDefinition,
183
+ ...messageCodeFieldDefinitions
184
+ }),
185
+ mode: "replace"
186
+ });
187
+
188
+ const registerConfirmOutputValidator = deepFreeze({
189
+ schema: createSchema({
190
+ ok: { type: "boolean", required: true },
191
+ email: { type: "string", required: true, minLength: 1, maxLength: AUTH_EMAIL_MAX_LENGTH },
192
+ username: { type: "string", required: false, minLength: 1, maxLength: 120 },
193
+ message: { type: "string", required: true, minLength: 1 },
168
194
  ...messageCodeFieldDefinitions
169
195
  }),
170
196
  mode: "replace"
@@ -319,6 +345,8 @@ const authCapabilitiesFeaturesOutputSchema = createSchema({
319
345
  schema: authOAuthLoginCapabilitiesOutputSchema
320
346
  },
321
347
  emailConfirmation: { type: "boolean", required: true },
348
+ emailConfirmationCode: { type: "boolean", required: true },
349
+ firstAccountSetupCode: { type: "boolean", required: true },
322
350
  profileUpdate: { type: "boolean", required: true },
323
351
  providerLinking: {
324
352
  type: "object",
@@ -445,7 +473,12 @@ const AUTH_FIELD_MESSAGES = deepFreeze({
445
473
  code: "auth.validation.recoveryTokenHashInvalid",
446
474
  message: "Recovery token hash is invalid."
447
475
  },
448
- recoveryTypeUnsupported: { code: "auth.validation.recoveryTypeUnsupported", message: "Only recovery links are supported." }
476
+ recoveryTypeUnsupported: { code: "auth.validation.recoveryTypeUnsupported", message: "Only recovery links are supported." },
477
+ confirmationCodeRequired: {
478
+ code: "auth.validation.confirmationCodeRequired",
479
+ message: "Enter the confirmation code or link from the email."
480
+ },
481
+ setupCodeInvalid: { code: "auth.validation.setupCodeInvalid", message: "Enter the setup code from the server's log or its hosting service." }
449
482
  });
450
483
 
451
484
  function createCommandMessages({
@@ -488,6 +521,8 @@ export {
488
521
  okOutputValidator,
489
522
  okMessageOutputValidator,
490
523
  registerOutputValidator,
524
+ registerConfirmationResendOutputValidator,
525
+ registerConfirmOutputValidator,
491
526
  loginOutputValidator,
492
527
  otpVerifyOutputValidator,
493
528
  oauthCompleteOutputValidator,
@@ -20,6 +20,9 @@ const AUTH_REGISTER_MESSAGES = createCommandMessages({
20
20
  required: AUTH_FIELD_MESSAGES.passwordRequired,
21
21
  minLength: AUTH_FIELD_MESSAGES.passwordMinLength,
22
22
  default: AUTH_FIELD_MESSAGES.passwordMinLength
23
+ },
24
+ setupCode: {
25
+ default: AUTH_FIELD_MESSAGES.setupCodeInvalid
23
26
  }
24
27
  }
25
28
  });
@@ -35,7 +38,10 @@ const authRegisterBodyValidator = deepFreeze({
35
38
  token: { type: "string", required: true, minLength: 1, maxLength: 2048 },
36
39
  source: { type: "string", required: false, minLength: 1, maxLength: 120 }
37
40
  })
38
- }
41
+ },
42
+ // The first account's one-time setup code, which a production server
43
+ // without accounts asks for (capability features.firstAccountSetupCode).
44
+ setupCode: { type: "string", required: false, minLength: 1, maxLength: 64 }
39
45
  }),
40
46
  mode: "create",
41
47
  messages: AUTH_REGISTER_MESSAGES
@@ -0,0 +1,42 @@
1
+ import { createSchema } from "json-rest-schema";
2
+ import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
+ import {
4
+ authRecoveryTokenValidator,
5
+ AUTH_FIELD_MESSAGES,
6
+ createCommandMessages,
7
+ registerConfirmOutputValidator
8
+ } from "./authCommandValidators.js";
9
+
10
+ const AUTH_REGISTER_CONFIRM_MESSAGES = createCommandMessages({
11
+ fields: {
12
+ token: {
13
+ required: AUTH_FIELD_MESSAGES.confirmationCodeRequired,
14
+ minLength: AUTH_FIELD_MESSAGES.confirmationCodeRequired,
15
+ default: AUTH_FIELD_MESSAGES.confirmationCodeRequired
16
+ }
17
+ }
18
+ });
19
+
20
+ // The code from a registration's confirmation link: confirming it creates the
21
+ // account and signs the person in.
22
+ const authRegisterConfirmBodyValidator = deepFreeze({
23
+ schema: createSchema({
24
+ token: { ...authRecoveryTokenValidator, required: true }
25
+ }),
26
+ mode: "create",
27
+ messages: AUTH_REGISTER_CONFIRM_MESSAGES
28
+ });
29
+
30
+ const authRegisterConfirmCommand = deepFreeze({
31
+ command: "auth.register.confirm",
32
+ operation: {
33
+ method: "POST",
34
+ body: authRegisterConfirmBodyValidator,
35
+ response: registerConfirmOutputValidator,
36
+ messages: AUTH_REGISTER_CONFIRM_MESSAGES,
37
+ idempotent: false,
38
+ invalidates: ["auth.session.read"]
39
+ }
40
+ });
41
+
42
+ export { authRegisterConfirmBodyValidator, AUTH_REGISTER_CONFIRM_MESSAGES, authRegisterConfirmCommand };
@@ -4,7 +4,7 @@ import {
4
4
  authEmailFieldDefinition,
5
5
  AUTH_FIELD_MESSAGES,
6
6
  createCommandMessages,
7
- okMessageOutputValidator
7
+ registerConfirmationResendOutputValidator
8
8
  } from "./authCommandValidators.js";
9
9
 
10
10
  const AUTH_REGISTER_CONFIRMATION_RESEND_MESSAGES = createCommandMessages({
@@ -31,7 +31,7 @@ const authRegisterConfirmationResendCommand = deepFreeze({
31
31
  operation: {
32
32
  method: "POST",
33
33
  body: authRegisterConfirmationResendBodyValidator,
34
- response: okMessageOutputValidator,
34
+ response: registerConfirmationResendOutputValidator,
35
35
  messages: AUTH_REGISTER_CONFIRMATION_RESEND_MESSAGES,
36
36
  idempotent: false,
37
37
  invalidates: []
@@ -1,5 +1,6 @@
1
1
  export { authRegisterCommand } from "./authRegisterCommand.js";
2
2
  export { authRegisterConfirmationResendCommand } from "./authRegisterConfirmationResendCommand.js";
3
+ export { authRegisterConfirmCommand } from "./authRegisterConfirmCommand.js";
3
4
  export { authLoginPasswordCommand } from "./authLoginPasswordCommand.js";
4
5
  export { authLoginOtpRequestCommand } from "./authLoginOtpRequestCommand.js";
5
6
  export { authLoginOtpVerifyCommand } from "./authLoginOtpVerifyCommand.js";
@@ -16,6 +16,7 @@ test("authApi exposes the expected methods and request routes", async () => {
16
16
  "session",
17
17
  "register",
18
18
  "resendRegisterConfirmation",
19
+ "confirmRegistration",
19
20
  "login",
20
21
  "requestOtp",
21
22
  "verifyOtp",
@@ -33,6 +34,7 @@ test("authApi exposes the expected methods and request routes", async () => {
33
34
  await api.login({ email: "x@example.com" });
34
35
  await api.devLoginAs({ userId: "42" });
35
36
  await api.logout();
37
+ await api.confirmRegistration({ token: "confirmation-code" });
36
38
 
37
39
  assert.equal(calls[0].url, "/api/session");
38
40
  assert.equal(calls[1].url, "/api/register/confirmation/resend");
@@ -43,6 +45,8 @@ test("authApi exposes the expected methods and request routes", async () => {
43
45
  assert.equal(calls[3].options.method, "POST");
44
46
  assert.equal(calls[4].url, "/api/logout");
45
47
  assert.equal(calls[4].options.method, "POST");
48
+ assert.equal(calls[5].url, "/api/register/confirm");
49
+ assert.deepEqual(calls[5].options, { method: "POST", body: { token: "confirmation-code" } });
46
50
  });
47
51
 
48
52
  test("authApi oauthStartUrl builds provider path with optional returnTo", () => {
@@ -66,6 +66,13 @@ test("normalizeAuthCapabilities returns one provider-neutral feature shape", ()
66
66
  assert.equal(isAuthOperationSupported(capabilities, "startProviderLink"), true);
67
67
  assert.equal(isAuthOperationSupported(capabilities, "unlinkProvider"), false);
68
68
  assert.equal(isAuthOperationSupported(capabilities, "resetPassword"), true);
69
+ // Confirming a registration from its link's code is its own capability.
70
+ assert.equal(capabilities.features.emailConfirmationCode, false);
71
+ assert.equal(isAuthOperationSupported(capabilities, "confirmRegistration"), false);
72
+ assert.equal(
73
+ isAuthOperationSupported(normalizeAuthCapabilities({ features: { emailConfirmationCode: true } }), "confirmRegistration"),
74
+ true
75
+ );
69
76
  assert.equal(
70
77
  isAuthOperationSupported(
71
78
  {
@@ -7,6 +7,7 @@ test("AUTH_PATHS defines canonical auth endpoint paths", () => {
7
7
  assert.equal(Object.isFrozen(AUTH_PATHS), true);
8
8
  assert.equal(AUTH_PATHS.LOGIN, "/api/login");
9
9
  assert.equal(AUTH_PATHS.REGISTER_CONFIRMATION_RESEND, "/api/register/confirmation/resend");
10
+ assert.equal(AUTH_PATHS.REGISTER_CONFIRM, "/api/register/confirm");
10
11
  assert.equal(AUTH_PATHS.LOGOUT, "/api/logout");
11
12
  assert.equal(AUTH_PATHS.SESSION, "/api/session");
12
13
  assert.equal(AUTH_PATHS.OAUTH_START_TEMPLATE, "/api/oauth/:provider/start");
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { resolveSchemaTransportSchemaDefinition } from "@jskit-ai/kernel/shared/validators";
4
4
  import { authRegisterCommand } from "../src/shared/commands/authRegisterCommand.js";
5
5
  import { authRegisterConfirmationResendCommand } from "../src/shared/commands/authRegisterConfirmationResendCommand.js";
6
+ import { authRegisterConfirmCommand } from "../src/shared/commands/authRegisterConfirmCommand.js";
6
7
  import { authLoginPasswordCommand } from "../src/shared/commands/authLoginPasswordCommand.js";
7
8
  import { authLoginOtpRequestCommand } from "../src/shared/commands/authLoginOtpRequestCommand.js";
8
9
  import { authLoginOtpVerifyCommand } from "../src/shared/commands/authLoginOtpVerifyCommand.js";
@@ -22,6 +23,7 @@ test("auth commands expose canonical operation validator messages", () => {
22
23
  const commands = {
23
24
  authRegisterCommand,
24
25
  authRegisterConfirmationResendCommand,
26
+ authRegisterConfirmCommand,
25
27
  authLoginPasswordCommand,
26
28
  authLoginOtpRequestCommand,
27
29
  authLoginOtpVerifyCommand,
@@ -54,6 +56,7 @@ test("every auth command message is coded and its English renders from the catal
54
56
  const commands = [
55
57
  authRegisterCommand,
56
58
  authRegisterConfirmationResendCommand,
59
+ authRegisterConfirmCommand,
57
60
  authLoginPasswordCommand,
58
61
  authLoginOtpRequestCommand,
59
62
  authLoginOtpVerifyCommand,
@@ -126,6 +129,18 @@ test("auth command body validators lowercase email inputs", () => {
126
129
  }
127
130
  });
128
131
 
132
+ test("registration takes the first account's setup code and confirmation takes its link's code", () => {
133
+ const registered = authRegisterCommand.operation.body.schema.create({
134
+ email: "owner@example.com",
135
+ password: "correct horse battery staple",
136
+ setupCode: "ABCDE-FGHJK-MNPQR-STVWX"
137
+ });
138
+ assert.equal(registered.validatedObject.setupCode, "ABCDE-FGHJK-MNPQR-STVWX");
139
+ assert.deepEqual(Object.keys(authRegisterConfirmCommand.operation.body.schema.create({ token: "code" }).validatedObject), [
140
+ "token"
141
+ ]);
142
+ });
143
+
129
144
  test("auth session and oauth start commands expose explicit nested response schemas", () => {
130
145
  const sessionResponseSchema = resolveSchemaTransportSchemaDefinition(
131
146
  authSessionReadCommand.operation.response,
@@ -5,7 +5,7 @@ import { createFakeFastifyPolicyRuntime } from "../../../tooling/testUtils/fakeF
5
5
 
6
6
  import { authPolicyPlugin } from "../src/server/lib/index.js";
7
7
 
8
- test("auth policy protects real Fastify requests with CSRF and route rate limits", async (t) => {
8
+ test("auth policy protects real Fastify requests with CSRF", async (t) => {
9
9
  const app = Fastify();
10
10
  t.after(() => app.close());
11
11
  await authPolicyPlugin({
@@ -21,9 +21,6 @@ test("auth policy protects real Fastify requests with CSRF and route rate limits
21
21
  token: reply.generateCsrf()
22
22
  }));
23
23
  app.post("/api/write", { config: { authPolicy: "public" } }, () => ({ accepted: true }));
24
- app.get("/api/limited", {
25
- config: { authPolicy: "public", rateLimit: { max: 1, timeWindow: "1 minute" } }
26
- }, () => ({ accepted: true }));
27
24
 
28
25
  const missingToken = await app.inject({ method: "POST", url: "/api/write" });
29
26
  assert.equal(missingToken.statusCode, 403);
@@ -44,8 +41,6 @@ test("auth policy protects real Fastify requests with CSRF and route rate limits
44
41
  method: "POST", url: "/api/write", cookies, headers: { "x-csrf-token": "invalid" }
45
42
  });
46
43
  assert.equal(invalidToken.statusCode, 403);
47
- assert.equal((await app.inject({ method: "GET", url: "/api/limited" })).statusCode, 200);
48
- assert.equal((await app.inject({ method: "GET", url: "/api/limited" })).statusCode, 429);
49
44
  });
50
45
 
51
46
  test("production CSRF secrets live in a host-only __Host- cookie a sibling host cannot plant", async (t) => {
@@ -44,7 +44,8 @@ test("AuthPolicyProvider installs Fastify policy and explicit action/visibility
44
44
  assert.ok(state.requestDecorators.has("membership"));
45
45
  assert.ok(state.requestDecorators.has("permissions"));
46
46
  assert.equal(typeof state.preHandler, "function");
47
- assert.ok(state.registeredPlugins.length >= 3);
47
+ // Cookies and CSRF; the kernel registers the rate limiter with the routes.
48
+ assert.equal(state.registeredPlugins.length, 2);
48
49
  assert.ok(runtime.diagnostics().capabilityIds.includes("auth.policy"));
49
50
  });
50
51