@jskit-ai/auth-core 0.2.29 → 0.2.31

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,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Email change: `features.emailChange` and three auth.service operations it gates (`AUTH_OPERATION_FEATURES`): `requestEmailChange(request, { email, password })`, the signed-in person's own change; `requestEmailChangeForUser({ userId, email })`, an application's change of an account it chose; and `confirmEmailChange({ token })`, the link sent to the new address. Two actions run them over HTTP and from server code, never automation: `auth.emailChange.request` (signed in) and `auth.emailChange.confirm` (anyone with the link), from `createEmailChangeActions` (`./server/actions/emailChangeActions`), which `AuthFeature` contributes; their commands are `authEmailChangeRequestCommand` and `authEmailChangeConfirmCommand` (`./shared/commands/authEmailChangeCommands`), and their paths `AUTH_PATHS.EMAIL_CHANGE` (`/api/email-change`) and `AUTH_PATHS.EMAIL_CHANGE_CONFIRM` (`/api/email-change/confirm`). Upgrading: every auth provider implements the three operations; one without email change throws `AUTH_OPERATION_UNSUPPORTED`.
6
+ - The actions that sign someone in hand `auth.service` the request they came in on: `auth.register`, `auth.register.confirm`, `auth.login.password` and `auth.password.recovery.complete` call `register`, `confirmRegistration`, `login` and `completePasswordRecovery` with `(input, request)`, the request null for an internal call, as `auth.login.oauth.complete` and `auth.dev.loginAs` already did, so a provider can keep where each session was signed in from. `AuthService` documents the optional second parameter; a provider that ignores it is unchanged.
7
+ - **Breaking:** dev sign-in, the CSRF cookie's `Secure` and `__Host-` prefix and unknown role grants follow `APP_ENV`, not `NODE_ENV`. `resolveDevAuthPolicy({ enabled, appEnv, secret })` takes the application's `APP_ENV` in place of `nodeEnv` and answers `isDeployed` (staging or production) in place of `isProduction`; a missing or unknown `appEnv` throws. `AUTH_DEV_BYPASS_ENABLED` in staging or production refuses to start with `AUTH_DEV_BYPASS_ENABLED is for development only: remove it from staging and production.` The auth plugin takes `appEnv` in place of `nodeEnv`.
5
8
  - **Breaking:** `./server/passSignIn` is gone. `signPass`, `verifyPass` and `resolvePassSignInFromEnv` moved unchanged to `@jskit-ai/auth-pass/server`, a package that installs no providers, so an application with its own sign-in can check passes without auth-core's runtime. `AUTH_TEXTS` loses the seven `pass*` entries and `locales/en.json` the `auth.pass.*` texts; they are `PASS_TEXTS` and `createPassError` in auth-pass, whose catalog has the same English. Import from `@jskit-ai/auth-pass/server` instead. `AUTH_PATHS.LOGIN_PASS` and the auth service's `signInWithPass({ pass })` stay here.
6
9
  - One-time pass sign-in: `./server/passSignIn` exports `signPass` (for the issuer, which holds an Ed25519 private key), `verifyPass` and `resolvePassSignInFromEnv`. A pass is a compact JWS (`alg` EdDSA, `typ` `pass+jwt`) naming one person (`sub`), one application (`aud`), one resource (`resource`) and its id (`jti`), lasting 60 seconds by default and at most five minutes. `AUTH_PASS_PUBLIC_KEY` (PEM, or base64 DER on one line) turns it on, with `AUTH_PASS_AUDIENCE` and `AUTH_PASS_RESOURCE` required. A refused pass is a 401 coded `auth.pass.malformed`, `auth.pass.badSignature`, `auth.pass.wrongAudience`, `auth.pass.wrongResource`, `auth.pass.expired` or `auth.pass.replayed`, or a 403 `auth.pass.unmapped`, each with an English text in `locales/en.json`. `AUTH_PATHS.LOGIN_PASS` is `/api/login/pass`, and the auth service gains the optional `signInWithPass({ pass })`.
7
10
  - `AUTH_COOKIE_SAME_SITE` sets the CSRF cookie's SameSite: `lax` (the default, unset or blank) or `strict`, as local auth's cookies take it; any other value stops the auth policy's startup with `AUTH_COOKIE_SAME_SITE must be lax or strict, not "<value>".` `./server/utils` exports `resolveAuthCookieSameSite(env)`, which reads it. Applications that leave it unset are unchanged.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-core",
3
- "version": "0.2.29",
3
+ "version": "0.2.31",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -12,6 +12,7 @@
12
12
  "./server/providers/AuthPolicyProvider": "./src/server/providers/AuthPolicyProvider.js",
13
13
  "./server/actions/authActions": "./src/server/actions/authActions.js",
14
14
  "./server/actions/secondFactorActions": "./src/server/actions/secondFactorActions.js",
15
+ "./server/actions/emailChangeActions": "./src/server/actions/emailChangeActions.js",
15
16
  "./server/authExtensions": "./src/server/authExtensions.js",
16
17
  "./server/noAppProfiles": "./src/server/noAppProfiles.js",
17
18
  "./server/authPolicyContextResolverRegistry": "./src/server/authPolicyContextResolverRegistry.js",
@@ -64,6 +65,7 @@
64
65
  "./shared/commands/authLogoutCommand": "./src/shared/commands/authLogoutCommand.js",
65
66
  "./shared/commands/authSessionReadCommand": "./src/shared/commands/authSessionReadCommand.js",
66
67
  "./shared/commands/authSecondFactorCommands": "./src/shared/commands/authSecondFactorCommands.js",
68
+ "./shared/commands/authEmailChangeCommands": "./src/shared/commands/authEmailChangeCommands.js",
67
69
  "./locales/en.json": "./locales/en.json"
68
70
  },
69
71
  "dependencies": {
@@ -147,6 +149,6 @@
147
149
  }
148
150
  },
149
151
  "peerDependencies": {
150
- "@jskit-ai/kernel": "0.2.26"
152
+ "@jskit-ai/kernel": "0.2.27"
151
153
  }
152
154
  }
@@ -51,7 +51,7 @@ function createAuthActions({ authService }) {
51
51
  channels: ["api", "internal"],
52
52
  surfaces: ["*"],
53
53
  input: authRegisterCommand.operation.body,
54
- execute: (input) => authService.register(input)
54
+ execute: (input, context) => authService.register(input, resolveRequest(context))
55
55
  }),
56
56
  Object.freeze({
57
57
  id: "auth.register.confirmation.resend",
@@ -69,7 +69,7 @@ function createAuthActions({ authService }) {
69
69
  channels: ["api", "internal"],
70
70
  surfaces: ["*"],
71
71
  input: authRegisterConfirmCommand.operation.body,
72
- execute: (input) => authService.confirmRegistration(input)
72
+ execute: (input, context) => authService.confirmRegistration(input, resolveRequest(context))
73
73
  }),
74
74
  Object.freeze({
75
75
  id: "auth.login.password",
@@ -78,7 +78,7 @@ function createAuthActions({ authService }) {
78
78
  channels: ["api", "internal"],
79
79
  surfaces: ["*"],
80
80
  input: authLoginPasswordCommand.operation.body,
81
- execute: (input) => authService.login(input)
81
+ execute: (input, context) => authService.login(input, resolveRequest(context))
82
82
  }),
83
83
  Object.freeze({
84
84
  id: "auth.login.otp.request",
@@ -141,7 +141,7 @@ function createAuthActions({ authService }) {
141
141
  channels: ["api", "internal"],
142
142
  surfaces: ["*"],
143
143
  input: authPasswordRecoveryCompleteCommand.operation.body,
144
- execute: (input) => authService.completePasswordRecovery(input)
144
+ execute: (input, context) => authService.completePasswordRecovery(input, resolveRequest(context))
145
145
  }),
146
146
  Object.freeze({
147
147
  id: "auth.password.reset",
@@ -0,0 +1,43 @@
1
+ import { resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
2
+ import {
3
+ authEmailChangeConfirmCommand,
4
+ authEmailChangeRequestCommand
5
+ } from "../../shared/commands/authEmailChangeCommands.js";
6
+
7
+ const ACTION_REQUEST_EMAIL_CHANGE = "auth.emailChange.request";
8
+ const ACTION_CONFIRM_EMAIL_CHANGE = "auth.emailChange.confirm";
9
+
10
+ // Over HTTP or from the server's own code; a password or a link never reaches automation.
11
+ const EMAIL_CHANGE_COMMAND = Object.freeze({
12
+ version: 1,
13
+ kind: "command",
14
+ channels: Object.freeze(["api", "internal"]),
15
+ surfaces: Object.freeze(["*"])
16
+ });
17
+
18
+ /**
19
+ * The email change's actions, each one call to the installed provider's auth.service: the signed-in person asks for
20
+ * their own change, and whoever opens the link sent to the new address confirms it, signed in or not. An
21
+ * application's change of an account it chose is auth.service's requestEmailChangeForUser, called by its own code
22
+ * after its own permission check.
23
+ * @param {{ authService: import("../types.js").AuthService }} dependencies
24
+ */
25
+ function createEmailChangeActions({ authService }) {
26
+ return Object.freeze([
27
+ Object.freeze({
28
+ ...EMAIL_CHANGE_COMMAND,
29
+ id: ACTION_REQUEST_EMAIL_CHANGE,
30
+ input: authEmailChangeRequestCommand.operation.body,
31
+ permission: Object.freeze({ require: "authenticated" }),
32
+ execute: (input, context) => authService.requestEmailChange(resolveRequest(context), input)
33
+ }),
34
+ Object.freeze({
35
+ ...EMAIL_CHANGE_COMMAND,
36
+ id: ACTION_CONFIRM_EMAIL_CHANGE,
37
+ input: authEmailChangeConfirmCommand.operation.body,
38
+ execute: (input) => authService.confirmEmailChange(input)
39
+ })
40
+ ]);
41
+ }
42
+
43
+ export { ACTION_CONFIRM_EMAIL_CHANGE, ACTION_REQUEST_EMAIL_CHANGE, createEmailChangeActions };
@@ -1,4 +1,5 @@
1
1
  import { hasPermission } from "@jskit-ai/kernel/shared/support/permissions";
2
+ import { appEnvironment } from "@jskit-ai/kernel/shared/support/appEnvironment";
2
3
  import { parseBooleanFlag } from "./booleanFlag.js";
3
4
  import { resolveAuthCookieSameSite } from "./utils.js";
4
5
 
@@ -43,13 +44,13 @@ function createAuthPolicy({ authService, extensions, env }) {
43
44
  hasPermission: defaultHasPermission,
44
45
  resolveContext,
45
46
  options: Object.freeze({
46
- // The plugin resolves both defaults: NODE_ENV not production, and the /api/ prefix.
47
- nodeEnv: env.NODE_ENV,
47
+ // The plugin resolves the /api/ prefix by default; the CSRF cookie follows APP_ENV.
48
+ appEnv: appEnvironment(env),
48
49
  apiPrefix: env.AUTH_API_PREFIX,
49
50
  // Unset AUTH_CSRF_UNSAFE_METHODS keeps the plugin default (POST, PUT, PATCH, DELETE).
50
51
  unsafeMethods: unsafeMethods.length > 0 ? Object.freeze(unsafeMethods) : undefined,
51
52
  // The CSRF cookie's SameSite is the sign-in cookies' (AUTH_COOKIE_SAME_SITE). Unset AUTH_CSRF_COOKIE_SECURE
52
- // follows NODE_ENV (Secure in production).
53
+ // follows APP_ENV (Secure in staging and production).
53
54
  csrfCookieOpts: Object.freeze({
54
55
  sameSite: csrfCookieSameSite,
55
56
  ...(String(env.AUTH_CSRF_COOKIE_SECURE ?? "").trim()
@@ -1,4 +1,4 @@
1
- import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
1
+ import { isDeployed } from "@jskit-ai/kernel/shared/support/appEnvironment";
2
2
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
3
3
  import { timingSafeEqual } from "node:crypto";
4
4
  import { parseBooleanFlag } from "./booleanFlag.js";
@@ -54,40 +54,42 @@ function isLocalDevAuthRequest(request) {
54
54
  return isLoopbackIp(remoteAddress) && isLoopbackHostname(normalizeRequestHostname(request));
55
55
  }
56
56
 
57
- function resolveDevAuthPolicy({
58
- enabled = false,
59
- nodeEnv = "development",
60
- secret = ""
61
- } = {}) {
57
+ /**
58
+ * Dev sign-in's policy, and whether the application is deployed (staging or production), which every auth provider
59
+ * reads from here to refuse development shortcuts such as cookies without Secure.
60
+ * @param {{ enabled?: unknown, appEnv: string, secret?: string }} settings `appEnv` is the application's APP_ENV;
61
+ * a missing or unknown one throws.
62
+ */
63
+ function resolveDevAuthPolicy({ enabled = false, appEnv, secret = "" }) {
62
64
  return Object.freeze({
63
65
  enabled: parseBooleanFlag(enabled, false),
64
- isProduction: isProductionEnv({ NODE_ENV: nodeEnv }),
66
+ isDeployed: isDeployed({ APP_ENV: appEnv }),
65
67
  secret: String(secret || "").trim()
66
68
  });
67
69
  }
68
70
 
69
- function resolveDevAuthPolicyFromEnv(env = {}) {
71
+ function resolveDevAuthPolicyFromEnv(env) {
70
72
  return resolveDevAuthPolicy({
71
73
  enabled: env.AUTH_DEV_BYPASS_ENABLED,
72
- nodeEnv: env.NODE_ENV,
74
+ appEnv: env.APP_ENV,
73
75
  secret: env.AUTH_DEV_BYPASS_SECRET
74
76
  });
75
77
  }
76
78
 
77
79
  /**
78
- * True when dev sign-in as another user is on: enabled, outside production.
80
+ * True when dev sign-in as another user is on: enabled, in development or test.
79
81
  * @param {ReturnType<typeof resolveDevAuthPolicy>} policy
80
82
  */
81
83
  function isDevAuthBootstrapEnabled(policy) {
82
- return policy.enabled && !policy.isProduction;
84
+ return policy.enabled && !policy.isDeployed;
83
85
  }
84
86
 
85
87
  function assertDevAuthPolicy(policy = {}) {
86
88
  if (!policy.enabled) {
87
89
  return;
88
90
  }
89
- if (policy.isProduction) {
90
- throw new Error("AUTH_DEV_BYPASS_ENABLED must not be enabled in production.");
91
+ if (policy.isDeployed) {
92
+ throw new Error("AUTH_DEV_BYPASS_ENABLED is for development only: remove it from staging and production.");
91
93
  }
92
94
  if (!policy.secret) {
93
95
  throw new Error("AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true.");
@@ -95,7 +97,7 @@ function assertDevAuthPolicy(policy = {}) {
95
97
  }
96
98
 
97
99
  function ensureDevAuthRuntimeAvailable(policy = {}, request = null) {
98
- if (!policy.enabled || policy.isProduction) {
100
+ if (!policy.enabled || policy.isDeployed) {
99
101
  throw new AppError(404, "Not found.", { code: "auth.dev.unavailable" });
100
102
  }
101
103
  if (!policy.secret) {
@@ -1,7 +1,7 @@
1
1
  import fastifyCookie from "@fastify/cookie";
2
2
  import fastifyCsrfProtection from "@fastify/csrf-protection";
3
3
  import { safeRequestUrl } from "@jskit-ai/kernel/server/runtime/requestUrl";
4
- import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
4
+ import { isDeployed } from "@jskit-ai/kernel/shared/support/appEnvironment";
5
5
  import { SECOND_FACTOR_REQUIRED } from "../../shared/authSecondFactor.js";
6
6
  import { isSecondFactorMet, secondFactorRequiredParams } from "../secondFactor.js";
7
7
  import { hostOnlyCookieName } from "../utils.js";
@@ -81,9 +81,9 @@ function authPolicyPlugin(deps = {}, options = {}) {
81
81
  const { resolveCsrfToken: resolveCsrfTokenFn = resolveCsrfToken, createError = createAuthPolicyError } = options;
82
82
 
83
83
  // CSRF uses tokens checked against a secret cookie, never SameSite alone. In
84
- // production that cookie is host-only (__Host-), so a sibling host cannot plant
84
+ // staging and production (APP_ENV) that cookie is host-only (__Host-), so a sibling host cannot plant
85
85
  // a secret it knows and forge tokens.
86
- const csrfCookieSecure = typeof csrfCookieOpts.secure === "boolean" ? csrfCookieOpts.secure : isProductionEnv({ NODE_ENV: options.nodeEnv });
86
+ const csrfCookieSecure = typeof csrfCookieOpts.secure === "boolean" ? csrfCookieOpts.secure : isDeployed({ APP_ENV: options.appEnv });
87
87
  const csrfCookieOptions = {
88
88
  path: "/",
89
89
  sameSite: "lax",
@@ -1,5 +1,6 @@
1
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
2
2
  import { createAuthActions } from "../actions/authActions.js";
3
+ import { createEmailChangeActions } from "../actions/emailChangeActions.js";
3
4
  import { createSecondFactorActions } from "../actions/secondFactorActions.js";
4
5
 
5
6
  // Without an auth provider installed there is no auth.service, so no auth actions.
@@ -13,7 +14,11 @@ const AuthFeature = defineFeature({
13
14
  },
14
15
  actions({ authService }) {
15
16
  return authService
16
- ? Object.freeze([...createAuthActions({ authService }), ...createSecondFactorActions({ authService })])
17
+ ? Object.freeze([
18
+ ...createAuthActions({ authService }),
19
+ ...createSecondFactorActions({ authService }),
20
+ ...createEmailChangeActions({ authService })
21
+ ])
17
22
  : NO_AUTH_ACTIONS;
18
23
  }
19
24
  });
@@ -126,21 +126,31 @@
126
126
  * @property {(reply: object) => void} clearSessionCookies
127
127
  * @property {(request: object) => Promise<AuthLogoutResult>} logout
128
128
  * @property {() => boolean} isDevAuthBootstrapEnabled
129
- * @property {(input: object) => Promise<object>} register
129
+ * @property {(input: object, request?: object | null) => Promise<object>} register The request, when there is one,
130
+ * is the one the person registers from, as for login.
130
131
  * @property {(input: object) => Promise<object>} resendRegisterConfirmation
131
- * @property {(input: { token: string, password: string }) => Promise<object>} confirmRegistration Creates the account a
132
- * registration waited to create until its email was confirmed, from its link's code and the password it registered
133
- * with, and signs the person in.
134
- * @property {(input: object) => Promise<object>} login
132
+ * @property {(input: { token: string, password: string }, request?: object | null) => Promise<object>} confirmRegistration
133
+ * Creates the account a registration waited to create until its email was confirmed, from its link's code and the
134
+ * password it registered with, and signs the person in.
135
+ * @property {(input: object, request?: object | null) => Promise<object>} login The request the person signs in
136
+ * from, when there is one (an internal call has none): a provider may keep where its session was signed in from.
135
137
  * @property {(input: object) => Promise<object>} requestOtpLogin
136
138
  * @property {(input: object) => Promise<object>} verifyOtpLogin
137
139
  * @property {(input: object, request: object | null) => Promise<object>} oauthStart
138
140
  * @property {(input: object, request: object | null) => Promise<object>} oauthComplete
139
141
  * @property {(input: object) => Promise<object>} requestPasswordReset
140
- * @property {(input: object) => Promise<object>} completePasswordRecovery
142
+ * @property {(input: object, request?: object | null) => Promise<object>} completePasswordRecovery
141
143
  * @property {(input: object, request: object | null) => Promise<object>} resetPassword
142
144
  * @property {(request: object, input: object) => Promise<object>} changePassword
143
145
  * @property {(request: object, input: object) => Promise<object>} updateDisplayName
146
+ * @property {(request: object, input: { email: string, password: string }) => Promise<{ ok: true, email: string }>}
147
+ * requestEmailChange The signed-in person's change of their own email, with their password: a link goes to the new
148
+ * address, and the email changes when it is used.
149
+ * @property {(input: { userId: string, email: string }) => Promise<{ ok: true, email: string }>} requestEmailChangeForUser
150
+ * The application's change of the email of an account it chose (a provider user id), which decides who may: a link
151
+ * goes to the new address, and the email changes when it is used.
152
+ * @property {(input: { token: string }) => Promise<{ ok: true, email: string }>} confirmEmailChange Uses the link sent
153
+ * to the new address: the account's email becomes it.
144
154
  * @property {(request: object) => Promise<object>} getSecurityStatus
145
155
  * @property {(request: object, input: object) => Promise<object>} setPasswordSignInEnabled
146
156
  * @property {(request: object, input: object) => Promise<object>} startProviderLink
@@ -165,7 +175,7 @@
165
175
  * whose staff lost their authenticator. `byUserId` names who reset it, for the audit event.
166
176
  * @property {(reply: object, result: object) => void} [writeOAuthStartCookies] Keeps the state of an OAuth sign-in that oauthStart() began.
167
177
  * @property {(reply: object) => void} [clearOAuthStartCookies]
168
- * @property {(input: { pass: string }) => Promise<object>} [signInWithPass] Signs in the account a one-time signed pass
178
+ * @property {(input: { pass: string }, request?: object | null) => Promise<object>} [signInWithPass] Signs in the account a one-time signed pass
169
179
  * names (`@jskit-ai/auth-pass/server`), once per pass; local auth has it, with AUTH_PASS_PUBLIC_KEY set.
170
180
  * @property {(request: object, options?: { everywhere?: boolean }) => Promise<any>} [logoutEverywhere]
171
181
  * @property {() => object} [getSettingsProfileAuthInfo] What the account settings show about the provider's profile.
@@ -21,6 +21,9 @@ const AUTH_OPERATION_FEATURES = Object.freeze({
21
21
  resetPassword: "passwordRecovery.complete",
22
22
  changePassword: "password.change",
23
23
  updateDisplayName: "profileUpdate",
24
+ requestEmailChange: "emailChange",
25
+ requestEmailChangeForUser: "emailChange",
26
+ confirmEmailChange: "emailChange",
24
27
  getSecurityStatus: "securityStatus",
25
28
  // readable-check: allow setter-seam - not a slot: setPasswordSignInEnabled is an auth.service operation
26
29
  setPasswordSignInEnabled: "password.methodToggle",
@@ -157,6 +160,8 @@ function normalizeAuthCapabilities(value = {}) {
157
160
  emailConfirmation: normalizeBoolean(featuresSource.emailConfirmation),
158
161
  emailConfirmationCode: normalizeBoolean(featuresSource.emailConfirmationCode),
159
162
  firstAccountSetupCode: normalizeBoolean(featuresSource.firstAccountSetupCode),
163
+ // An account's email changes once a link sent to the new address is used.
164
+ emailChange: normalizeBoolean(featuresSource.emailChange),
160
165
  profileUpdate: normalizeBoolean(featuresSource.profileUpdate),
161
166
  providerLinking: Object.freeze({
162
167
  start: normalizeBoolean(providerLinkingSource.start),
@@ -18,7 +18,9 @@ const AUTH_PATHS = Object.freeze({
18
18
  SECOND_FACTOR_SETUP: "/api/second-factor/setup",
19
19
  SECOND_FACTOR_SETUP_CONFIRM: "/api/second-factor/setup/confirm",
20
20
  SECOND_FACTOR_VERIFY: "/api/second-factor/verify",
21
- SECOND_FACTOR_RECOVERY_CODES: "/api/second-factor/recovery-codes"
21
+ SECOND_FACTOR_RECOVERY_CODES: "/api/second-factor/recovery-codes",
22
+ EMAIL_CHANGE: "/api/email-change",
23
+ EMAIL_CHANGE_CONFIRM: "/api/email-change/confirm"
22
24
  });
23
25
 
24
26
  function buildAuthOauthStartPath(provider) {
@@ -0,0 +1,85 @@
1
+ import { createSchema } from "json-rest-schema";
2
+ import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
+ import {
4
+ authEmailFieldDefinition,
5
+ authLoginPasswordFieldDefinition,
6
+ authRecoveryTokenValidator,
7
+ AUTH_FIELD_MESSAGES,
8
+ createCommandMessages
9
+ } from "./authCommandValidators.js";
10
+
11
+ // An account's email change: the signed-in person asks for a new address with their password, and the link sent to
12
+ // that address confirms it.
13
+ const AUTH_EMAIL_CHANGE_REQUEST_MESSAGES = createCommandMessages({
14
+ fields: {
15
+ email: {
16
+ required: AUTH_FIELD_MESSAGES.emailRequired,
17
+ minLength: AUTH_FIELD_MESSAGES.emailRequired,
18
+ pattern: AUTH_FIELD_MESSAGES.emailAddressInvalid,
19
+ default: AUTH_FIELD_MESSAGES.emailAddressInvalid
20
+ },
21
+ password: {
22
+ required: AUTH_FIELD_MESSAGES.passwordRequired,
23
+ minLength: AUTH_FIELD_MESSAGES.passwordRequired,
24
+ default: AUTH_FIELD_MESSAGES.passwordRequired
25
+ }
26
+ }
27
+ });
28
+
29
+ const AUTH_EMAIL_CHANGE_CONFIRM_MESSAGES = createCommandMessages({
30
+ fields: {
31
+ token: {
32
+ required: AUTH_FIELD_MESSAGES.confirmationCodeRequired,
33
+ minLength: AUTH_FIELD_MESSAGES.confirmationCodeRequired,
34
+ default: AUTH_FIELD_MESSAGES.confirmationCodeRequired
35
+ }
36
+ }
37
+ });
38
+
39
+ // The address the link went to, or the email the account now has.
40
+ const emailChangeOutputValidator = deepFreeze({
41
+ schema: createSchema({
42
+ ok: { type: "boolean", required: true },
43
+ email: { ...authEmailFieldDefinition, required: true }
44
+ }),
45
+ mode: "replace"
46
+ });
47
+
48
+ const authEmailChangeRequestCommand = deepFreeze({
49
+ command: "auth.emailChange.request",
50
+ operation: {
51
+ method: "POST",
52
+ body: deepFreeze({
53
+ schema: createSchema({
54
+ email: { ...authEmailFieldDefinition, required: true },
55
+ password: { ...authLoginPasswordFieldDefinition, required: true }
56
+ }),
57
+ mode: "create",
58
+ messages: AUTH_EMAIL_CHANGE_REQUEST_MESSAGES
59
+ }),
60
+ response: emailChangeOutputValidator,
61
+ messages: AUTH_EMAIL_CHANGE_REQUEST_MESSAGES,
62
+ idempotent: false,
63
+ invalidates: []
64
+ }
65
+ });
66
+
67
+ const authEmailChangeConfirmCommand = deepFreeze({
68
+ command: "auth.emailChange.confirm",
69
+ operation: {
70
+ method: "POST",
71
+ body: deepFreeze({
72
+ schema: createSchema({
73
+ token: { ...authRecoveryTokenValidator, required: true }
74
+ }),
75
+ mode: "create",
76
+ messages: AUTH_EMAIL_CHANGE_CONFIRM_MESSAGES
77
+ }),
78
+ response: emailChangeOutputValidator,
79
+ messages: AUTH_EMAIL_CHANGE_CONFIRM_MESSAGES,
80
+ idempotent: false,
81
+ invalidates: ["auth.session.read"]
82
+ }
83
+ });
84
+
85
+ export { authEmailChangeConfirmCommand, authEmailChangeRequestCommand };
@@ -39,7 +39,7 @@ const authRegisterBodyValidator = deepFreeze({
39
39
  source: { type: "string", required: false, minLength: 1, maxLength: 120 }
40
40
  })
41
41
  },
42
- // The first account's one-time setup code, which a production server
42
+ // The first account's one-time setup code, which a staging or production server
43
43
  // without accounts asks for (capability features.firstAccountSetupCode).
44
44
  setupCode: { type: "string", required: false, minLength: 1, maxLength: 64 }
45
45
  }),
@@ -20,3 +20,4 @@ export {
20
20
  authSecondFactorSetupStartCommand,
21
21
  authSecondFactorVerifyCommand
22
22
  } from "./authSecondFactorCommands.js";
23
+ export { authEmailChangeConfirmCommand, authEmailChangeRequestCommand } from "./authEmailChangeCommands.js";
@@ -5,6 +5,7 @@ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
5
5
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
6
6
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
7
  import { createAuthActions } from "../src/server/actions/authActions.js";
8
+ import { createEmailChangeActions } from "../src/server/actions/emailChangeActions.js";
8
9
  import { createSecondFactorActions } from "../src/server/actions/secondFactorActions.js";
9
10
  import { AuthFeature } from "../src/server/providers/AuthFeature.js";
10
11
 
@@ -41,6 +42,35 @@ test("shared dev login-as action passes the trusted request to auth.service", as
41
42
  assert.deepEqual(received, { input, request });
42
43
  });
43
44
 
45
+ test("the actions that sign someone in hand auth.service the request they came in, for the session they make", async () => {
46
+ const calls = [];
47
+ const record = (name) => async (...args) => {
48
+ calls.push([name, ...args]);
49
+ return { name };
50
+ };
51
+ const authService = {
52
+ register: record("register"),
53
+ confirmRegistration: record("confirmRegistration"),
54
+ login: record("login"),
55
+ completePasswordRecovery: record("completePasswordRecovery")
56
+ };
57
+ const request = { id: "request-1" };
58
+ const actions = createAuthActions({ authService });
59
+ for (const id of ["auth.register", "auth.register.confirm", "auth.login.password", "auth.password.recovery.complete"]) {
60
+ await actions.find((action) => action.id === id).execute({ email: "ada@example.com" }, { requestMeta: { request } });
61
+ }
62
+ // An internal call has no request.
63
+ await actions.find((action) => action.id === "auth.login.password").execute({ email: "ada@example.com" }, {});
64
+ const input = { email: "ada@example.com" };
65
+ assert.deepEqual(calls, [
66
+ ["register", input, request],
67
+ ["confirmRegistration", input, request],
68
+ ["login", input, request],
69
+ ["completePasswordRecovery", input, request],
70
+ ["login", input, null]
71
+ ]);
72
+ });
73
+
44
74
  test("second factor actions hand the request's own session and the input to auth.service", async () => {
45
75
  const calls = [];
46
76
  const record = (name) => async (...args) => {
@@ -79,6 +109,29 @@ test("second factor actions hand the request's own session and the input to auth
79
109
  ]);
80
110
  });
81
111
 
112
+ test("email change actions: the signed-in person's request with the session, and a link's confirmation by anyone", async () => {
113
+ const calls = [];
114
+ const record = (name) => async (...args) => {
115
+ calls.push([name, ...args]);
116
+ return { ok: true, email: "new@example.com" };
117
+ };
118
+ const authService = { requestEmailChange: record("requestEmailChange"), confirmEmailChange: record("confirmEmailChange") };
119
+ const request = { id: "request-1" };
120
+ const actions = createEmailChangeActions({ authService });
121
+ assert.deepEqual(actions.map((action) => [action.id, action.kind, action.permission ?? null]), [
122
+ ["auth.emailChange.request", "command", { require: "authenticated" }],
123
+ ["auth.emailChange.confirm", "command", null]
124
+ ]);
125
+ assert.equal(actions.some((action) => action.channels.includes("automation")), false, "passwords and links never reach automation");
126
+ const [requestChange, confirmChange] = actions;
127
+ await requestChange.execute({ email: "new@example.com", password: "pw" }, { requestMeta: { request } });
128
+ await confirmChange.execute({ token: "link-token" }, { requestMeta: { request } });
129
+ assert.deepEqual(calls, [
130
+ ["requestEmailChange", request, { email: "new@example.com", password: "pw" }],
131
+ ["confirmEmailChange", { token: "link-token" }]
132
+ ]);
133
+ });
134
+
82
135
  test("AuthFeature contributes actions only when auth.service exists", async () => {
83
136
  let actions = null;
84
137
  const SelectedAuthProvider = defineProvider({
@@ -112,6 +165,7 @@ test("AuthFeature contributes actions only when auth.service exists", async () =
112
165
  await runtime.start();
113
166
  assert.equal(actions.listDefinitions().some((definition) => definition.id === "auth.login.password"), true);
114
167
  assert.equal(actions.listDefinitions().some((definition) => definition.id === "auth.secondFactor.verify"), true);
168
+ assert.equal(actions.listDefinitions().some((definition) => definition.id === "auth.emailChange.confirm"), true);
115
169
  assert.deepEqual(actions.getDefinition("auth.session.read").surfaces, ["*"]);
116
170
 
117
171
  let publicActions = null;
@@ -118,6 +118,17 @@ test("the second factor is a capability of its own, which every second factor op
118
118
  }
119
119
  });
120
120
 
121
+ test("email change is a capability of its own, which each email change operation needs", () => {
122
+ const without = normalizeAuthCapabilities({ features: { password: { login: true } } });
123
+ const withEmailChange = normalizeAuthCapabilities({ features: { emailChange: true } });
124
+ assert.equal(without.features.emailChange, false);
125
+ assert.equal(withEmailChange.features.emailChange, true);
126
+ for (const operation of ["requestEmailChange", "requestEmailChangeForUser", "confirmEmailChange"]) {
127
+ assert.equal(isAuthOperationSupported(without, operation), false, operation);
128
+ assert.equal(isAuthOperationSupported(withEmailChange, operation), true, operation);
129
+ }
130
+ });
131
+
121
132
  test("normalizeAuthActor builds the canonical actor", () => {
122
133
  const actor = normalizeAuthActor({
123
134
  provider: "supabase",
@@ -27,7 +27,7 @@ async function createApp(t) {
27
27
  }
28
28
  },
29
29
  extensions,
30
- env: { NODE_ENV: "test" }
30
+ env: { APP_ENV: "test" }
31
31
  });
32
32
 
33
33
  const app = Fastify();
@@ -7,8 +7,10 @@ import {
7
7
  assertDevAuthPolicy,
8
8
  ensureDevAuthExchangeAvailable,
9
9
  ensureDevAuthRuntimeAvailable,
10
+ isDevAuthBootstrapEnabled,
10
11
  isLocalDevAuthRequest,
11
- resolveDevAuthPolicy
12
+ resolveDevAuthPolicy,
13
+ resolveDevAuthPolicyFromEnv
12
14
  } from "../src/server/devAuth.js";
13
15
 
14
16
  const DEV_AUTH_SECRET = "preview-exchange-secret";
@@ -32,7 +34,7 @@ function createRequest({
32
34
  function enabledPolicy(overrides = {}) {
33
35
  return resolveDevAuthPolicy({
34
36
  enabled: true,
35
- nodeEnv: "development",
37
+ appEnv: "development",
36
38
  secret: DEV_AUTH_SECRET,
37
39
  ...overrides
38
40
  });
@@ -47,14 +49,32 @@ test("parseBooleanFlag normalizes conventional environment flag values", () => {
47
49
 
48
50
  test("dev auth policy rejects production and missing-secret enablement", () => {
49
51
  assert.throws(
50
- () => assertDevAuthPolicy(enabledPolicy({ nodeEnv: "production" })),
51
- /must not be enabled in production/
52
+ () => assertDevAuthPolicy(enabledPolicy({ appEnv: "staging" })),
53
+ { message: /^AUTH_DEV_BYPASS_ENABLED is for development only: remove it from staging and production\.$/u }
52
54
  );
53
55
  assert.throws(
54
56
  () => assertDevAuthPolicy(enabledPolicy({ secret: "" })),
55
57
  /AUTH_DEV_BYPASS_SECRET is required/
56
58
  );
57
- assert.doesNotThrow(() => assertDevAuthPolicy(resolveDevAuthPolicy()));
59
+ assert.doesNotThrow(() => assertDevAuthPolicy(resolveDevAuthPolicy({ appEnv: "production" })), "off is allowed anywhere");
60
+ assert.throws(() => resolveDevAuthPolicy({ enabled: true }), { message: /^APP_ENV is not set/u }, "never guesses development");
61
+ });
62
+
63
+ test("dev sign-in follows APP_ENV: allowed in development and test, refused in staging and production, whatever NODE_ENV", () => {
64
+ const policyIn = (APP_ENV, NODE_ENV) => resolveDevAuthPolicyFromEnv({
65
+ APP_ENV, NODE_ENV, AUTH_DEV_BYPASS_ENABLED: "true", AUTH_DEV_BYPASS_SECRET: DEV_AUTH_SECRET
66
+ });
67
+ for (const APP_ENV of ["development", "test"]) {
68
+ assert.equal(isDevAuthBootstrapEnabled(policyIn(APP_ENV, "production")), true, APP_ENV);
69
+ assert.doesNotThrow(() => ensureDevAuthRuntimeAvailable(policyIn(APP_ENV, "production"), createRequest()), APP_ENV);
70
+ }
71
+ for (const APP_ENV of ["staging", "production"]) {
72
+ const policy = policyIn(APP_ENV, "production");
73
+ assert.equal(policy.isDeployed, true, APP_ENV);
74
+ assert.equal(isDevAuthBootstrapEnabled(policy), false, APP_ENV);
75
+ assert.throws(() => ensureDevAuthRuntimeAvailable(policy, createRequest()), { code: "auth.dev.unavailable" }, APP_ENV);
76
+ }
77
+ assert.throws(() => resolveDevAuthPolicyFromEnv({}), { message: /^APP_ENV is not set/u });
58
78
  });
59
79
 
60
80
  test("dev auth trusts only a direct loopback connection with a loopback Host", () => {
@@ -111,7 +131,7 @@ test("dev auth refusals carry their own codes", () => {
111
131
  }
112
132
  return null;
113
133
  };
114
- assert.equal(codeOf(() => ensureDevAuthRuntimeAvailable(resolveDevAuthPolicy(), createRequest())), "auth.dev.unavailable");
134
+ assert.equal(codeOf(() => ensureDevAuthRuntimeAvailable(resolveDevAuthPolicy({ appEnv: "development" }), createRequest())), "auth.dev.unavailable");
115
135
  assert.throws(() => ensureDevAuthRuntimeAvailable(enabledPolicy({ secret: "" }), createRequest()), (error) =>
116
136
  error.message === "AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true." && error.code === undefined);
117
137
  assert.equal(
@@ -15,7 +15,7 @@ test("auth policy protects real Fastify requests with CSRF", async (t) => {
15
15
  hasPermission() {
16
16
  return false;
17
17
  }
18
- }, { nodeEnv: "test" })(app);
18
+ }, { appEnv: "test" })(app);
19
19
 
20
20
  app.get("/api/csrf", { config: { authPolicy: "public" } }, (_request, reply) => ({
21
21
  token: reply.generateCsrf()
@@ -53,7 +53,7 @@ test("production CSRF secrets live in a host-only __Host- cookie a sibling host
53
53
  hasPermission() {
54
54
  return false;
55
55
  }
56
- }, { nodeEnv: "production" })(app);
56
+ }, { appEnv: "production" })(app);
57
57
  app.get("/api/csrf", { config: { authPolicy: "public" } }, (_request, reply) => ({ token: reply.generateCsrf() }));
58
58
  app.post("/api/write", { config: { authPolicy: "public" } }, () => ({ accepted: true }));
59
59
 
@@ -98,7 +98,7 @@ test("resolves csrf token headers and skips auth for non-api/public routes", asy
98
98
  }
99
99
  },
100
100
  {
101
- nodeEnv: "test"
101
+ appEnv: "test"
102
102
  }
103
103
  );
104
104
 
@@ -145,7 +145,7 @@ test("propagates csrf callback error", async () => {
145
145
  hasPermission() {
146
146
  return true;
147
147
  }
148
- });
148
+ }, { appEnv: "test" });
149
149
 
150
150
  await registerPlugin(fastify);
151
151
  await assert.rejects(
@@ -194,7 +194,7 @@ test("enforces own policy owner checks and invalid policy guard", async () => {
194
194
  onPolicyDenied(event) {
195
195
  denyEvents.push(event);
196
196
  }
197
- });
197
+ }, { appEnv: "test" });
198
198
 
199
199
  await registerPlugin(fastify);
200
200
 
@@ -295,7 +295,7 @@ test("enforces permission checks and resolves workspace context when requested",
295
295
  onPolicyDenied(event) {
296
296
  denyEvents.push(event);
297
297
  }
298
- });
298
+ }, { appEnv: "test" });
299
299
 
300
300
  await registerPlugin(fastify);
301
301
  await assert.rejects(
@@ -330,7 +330,7 @@ test("each policy refusal carries its own code next to the English", async () =>
330
330
  hasPermission() {
331
331
  return false;
332
332
  }
333
- })(fastify);
333
+ }, { appEnv: "test" })(fastify);
334
334
 
335
335
  async function refusal(config, params = {}) {
336
336
  try {
@@ -20,7 +20,7 @@ function createFastify() {
20
20
 
21
21
  function runtimeInputs(fastify) {
22
22
  return {
23
- "runtime.env": { NODE_ENV: "test" },
23
+ "runtime.env": { APP_ENV: "test" },
24
24
  "runtime.fastify": fastify,
25
25
  "runtime.logger": silentLogger
26
26
  };
@@ -157,7 +157,7 @@ async function csrfSecretCookie(t, env) {
157
157
  const app = Fastify();
158
158
  t.after(() => app.close());
159
159
  const runtime = createCapabilityRuntime({
160
- inputs: { ...runtimeInputs(app), "runtime.env": { NODE_ENV: "test", ...env } },
160
+ inputs: { ...runtimeInputs(app), "runtime.env": { APP_ENV: "test", ...env } },
161
161
  providers: [EventProvider, ActionProvider, HttpProvider, AuthExtensionsProvider, AuthFeature, AuthPolicyProvider]
162
162
  });
163
163
  await runtime.start();
@@ -25,7 +25,7 @@ async function startPolicy({ hasPermission = () => true } = {}) {
25
25
  onPolicyDenied(event) {
26
26
  denied.push(event.reason);
27
27
  }
28
- })(fastify);
28
+ }, { appEnv: "test" })(fastify);
29
29
  return {
30
30
  state,
31
31
  denied,