diff --git a/.changeset/auth-switches-read-declaration.md b/.changeset/auth-switches-read-declaration.md new file mode 100644 index 00000000000..6dd1d0c3db8 --- /dev/null +++ b/.changeset/auth-switches-read-declaration.md @@ -0,0 +1,23 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: Setup → Authentication's switches show what the deployment runs when nothing is saved + +Clause-②: yes (narrowing) — narrowed: with nothing stored, `SettingsService.get('auth', …)` and `GET /api/settings/auth` answer `email_password_enabled`, `signup_enabled` and `require_email_verification` with the deployment's declaration (still `source: 'default'`), where they answered the manifest default; so on a cloud-managed runtime (`OS_CLOUD_MANAGED=1`) whose deployment declares `emailAndPassword.enabled: false`, a save of `email_password_enabled: true` with nothing stored answers `400 SETTINGS_VALIDATION` (`invalid_value` at the key) and saves nothing in the batch, where it saved a row that was not applied; and a save that sets one of these keys to its manifest default where the declaration differs now asks the key's write predicates. Widened: a save that sets one of these keys to the declaration with nothing stored is no change and asks no predicate; on a deployment that declares `emailAndPassword.enabled: false` with nothing stored, the ten `auth` keys visible only while `email_password_enabled !== false` (`signup_enabled`, `require_email_verification`, `password_min_length`, `password_max_length`, `password_reject_breached`, `password_require_complexity`, `password_min_classes`, `password_history_count`, `password_expiry_days`, `mfa_required`) are hidden, so a save of one of them is no longer judged for `required`, options or bounds (for example `password_min_length: 2` is now stored where it was refused `400 SETTINGS_VALIDATION`), as under a stored `email_password_enabled: false`; a save that turns `email_password_enabled` on re-judges them; `AuthManager.resolveDisableSignUp(declared)` (public method). The Setup → Authentication live-status banner no longer states the declared-off, nothing-saved case (the switch says it): its `declaredOffLabel` / `declaredOffText` copy is removed, and the cloud-managed statement is always a `warning`. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the auth settings page or these switches; `content/docs/protocol/kernel/config-resolution.mdx` states the declared default. + + + +**BREAKING** for a reader of `GET /api/settings/auth` or `SettingsService.get('auth', …)` on a deployment whose own configuration differs from the manifest default for one of these three keys, with nothing saved: the value answered is now what runs (for example `email_password_enabled: { value: false, source: 'default' }` where the deployment declares `emailAndPassword.enabled: false`), not the manifest default. A saved value and an `OS_AUTH_*` override still win, and a clear returns to the declaration. + +What each switch reads with nothing saved: + +- `email_password_enabled` — `emailAndPassword.enabled`, on unless declared `false`. +- `signup_enabled` — off where self-registration is forced off (SSO-only, cloud-managed) or turned off by `OS_DISABLE_SIGNUP` or a declared `emailAndPassword.disableSignUp: true`; else on. +- `require_email_verification` — the declared `emailAndPassword.requireEmailVerification` under the audience posture in force: on under `email_domain`, on under `open` unless declared `false`, else as declared (off by default). + +On a cloud-managed runtime whose deployment declares email and password off, the switch now reads off with nothing saved, and turning it on is refused at the save door (before, the save was stored and not applied, because `true` was the value the settings service already resolved). Self-hosted deployments keep taking a saved value as before. + +What to do: nothing to migrate. A client that read `source: 'default'` as "the manifest default" should read it as "nothing is saved; this is the deployment's default". diff --git a/.changeset/settings-declared-default.md b/.changeset/settings-declared-default.md new file mode 100644 index 00000000000..d7f4360dc25 --- /dev/null +++ b/.changeset/settings-declared-default.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-settings': patch +--- + +feat(service-settings): a deployment's declared default answers the bottom rung of the settings cascade + +Clause-②: yes (widening) — widened: `SettingsService.registerDeclaredDefault(namespace, key, provider)` and the exported type `SettingsDeclaredDefault`. A key with a registered provider resolves, while nothing is stored and no `OS_*` override is in force, to what the provider answers instead of the manifest `default`, still `source: 'default'`; a key or namespace with no provider resolves exactly as before. +Metadata-protocol: none + +A manifest `default` is the console's default. Where a package's runtime takes a key from its own configuration while nothing is stored (plugin options, a host declaration), the settings page read the manifest default while something else ran, and a save of that default was "no change" to the key's write predicates. + +A package now states that value: `settings.registerDeclaredDefault('auth', 'email_password_enabled', () => declared)`. It is asked on each use and never recorded, and it answers every place the cascade read the manifest default: `get`, `getMany`, `getNamespace` (and `GET /api/settings/:namespace`), the change test that decides whether a write predicate is asked, the value a cleared key falls back to, and the type an `OS_*` value is coerced to. `undefined` or `null` means "nothing declared" (the manifest default stands); a provider that throws is reported once at `warn` and the manifest default answers. A stored row and an `OS_*` override still win. ADR-0007's rung 4 is amended to match. + +What to do: nothing for existing namespaces. diff --git a/content/docs/protocol/kernel/config-resolution.mdx b/content/docs/protocol/kernel/config-resolution.mdx index 2f7f1d1ef91..f304906d34d 100644 --- a/content/docs/protocol/kernel/config-resolution.mdx +++ b/content/docs/protocol/kernel/config-resolution.mdx @@ -65,10 +65,21 @@ ObjectStack replaces the chain with one resolver and one declared order. └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ -│ 5. DEFAULT the specifier's `default` in the manifest │ +│ 5. DEFAULT what the deployment declares for the key, else │ +│ the specifier's `default` in the manifest │ └─────────────────────────────────────────────────────────────┘ ``` +The bottom rung answers what the key takes in the running system while +nothing is stored. A package whose runtime takes a key from its own +configuration when nothing is stored (plugin options, a host declaration) +states that value with `registerDeclaredDefault(namespace, key, provider)`; +otherwise the manifest `default` answers. Either way the answer reports +`source: 'default'`: nothing is stored, and a clear returns to it. The auth +plugin states `email_password_enabled`, `signup_enabled` and +`require_email_verification` this way, so Setup → Authentication shows what +the deployment runs, not a console default it never applies. + Two rules follow from the walk, and both are enforced in `SettingsService`: - **First non-null entry wins.** Values are *not* merged — no deep merge, no @@ -251,8 +262,8 @@ OS_CRM_API_KEY=sk_live_... OS_AI_LOG_PROMPTS=true ``` -The raw string is coerced by the **type of the specifier's default** -(`coerceEnvValue`): +The raw string is coerced by the **type of the key's default** — the bottom +rung above (`coerceEnvValue`): ```bash OS_HTTP_TIMEOUT=30000 # default is a number → 30000 diff --git a/content/docs/references/system/settings-manifest.mdx b/content/docs/references/system/settings-manifest.mdx index 820172ae073..94327c49a62 100644 --- a/content/docs/references/system/settings-manifest.mdx +++ b/content/docs/references/system/settings-manifest.mdx @@ -23,7 +23,8 @@ Resolution order (handled by `SettingsService.get`): 1. process.env override (source='env', locked=true) 2. sys_setting scope=tenant 3. sys_setting scope=user - 4. manifest specifier.default + 4. what the running deployment declares for the key, else the manifest + specifier.default (source='default'; ADR-0007 rung 4 as amended) **Source:** `packages/spec/src/system/settings-manifest.zod.ts` diff --git a/docs/adr/0007-settings-manifest-and-kv-store.md b/docs/adr/0007-settings-manifest-and-kv-store.md index d4a86193212..a88264ac4ac 100644 --- a/docs/adr/0007-settings-manifest-and-kv-store.md +++ b/docs/adr/0007-settings-manifest-and-kv-store.md @@ -1,6 +1,6 @@ # ADR-0007: Settings — Manifest + K/V Store + Resolver (Apple-style) -**Status**: Accepted — backend implemented; UI pending (objectui) (proposed 2026-05-20 · calibrated 2026-06-12) · **Amended (2026-11-05, #30385)** — D6: a clear (`null`) of an env-pinned key is not refused; it clears the stored value beneath the override and changes nothing in force. · **Amended (2026-11-08, #30208)** — §Specifier set gains `map` (keyed rows with typed value columns); `json` stays for raw config and is no longer the home for maps. +**Status**: Accepted — backend implemented; UI pending (objectui) (proposed 2026-05-20 · calibrated 2026-06-12) · **Amended (2026-11-05, #30385)** — D6: a clear (`null`) of an env-pinned key is not refused; it clears the stored value beneath the override and changes nothing in force. · **Amended (2026-11-08, #30208)** — §Specifier set gains `map` (keyed rows with typed value columns); `json` stays for raw config and is no longer the home for maps. · **Amended (2026-11-28, #38098)** — §Resolution rung 4: what the running deployment declares for a key (`registerDeclaredDefault`), else the manifest `specifier.default`; still `source='default'`. **Deciders**: ObjectStack Protocol Architects **Builds on**: [ADR-0005](./0005-metadata-customization-overlay.md) (Metadata Customization Overlay), [ADR-0006 v4](./0006-project-environment-split.v4.md) (Project/Environment Split — this record was originally built on v3, superseded by v4) **Consumers**: `@objectstack/spec`, `@objectstack/platform-objects`, new `@objectstack/service-settings`, `@objectstack/plugin-auth` (Setup app), `objectui` (Settings renderer) @@ -77,7 +77,7 @@ ObjectStack's protocol-first DNA matches Apple's: a small set of declarative spe 1. process.env override (source='env', locked=true) ← highest 2. sys_setting WHERE scope='tenant' ← tenant 3. sys_setting WHERE scope='user' AND user_id=ctx.user_id ← user - 4. manifest specifier.default ← default + 4. deployment-declared default, else manifest specifier.default ← default returns: { value, source, locked } RUNTIME WRITE SettingsService.set(ns, key, value, scope, ctx) @@ -91,6 +91,8 @@ ObjectStack's protocol-first DNA matches Apple's: a small set of declarative spe POST /api/settings/:namespace/test → { ok, message, details } (optional, manifest-declared) ``` +*Amended 2026-11-28 (#38098): rung 4 read "manifest specifier.default". A manifest default is the console's default; where a package's runtime takes a key from its own configuration while nothing is stored (plugin options, a host declaration), the manifest default is a value nothing applies, so the page read one thing while another ran, and a save of it was "no change" to the key's write predicates. The package now states that value (`SettingsService.registerDeclaredDefault(namespace, key, provider)`, asked on each use, never recorded); rung 4 answers it, else the manifest default. The answer stays `source='default'` (the published enum admits no other value, nothing is stored, and a clear returns to it); a stored row and an `OS_*` override still win.* + ### Design principles (binding) 1. **One manifest, many namespaces.** Each plugin exports any number of `SettingsManifest`s. A manifest is a declarative tree of `Specifier`s — never a React component, never a SQL DDL. diff --git a/packages/platform-objects/src/system/sys-setting.object.ts b/packages/platform-objects/src/system/sys-setting.object.ts index 3da52eba9a1..48080e83b58 100644 --- a/packages/platform-objects/src/system/sys-setting.object.ts +++ b/packages/platform-objects/src/system/sys-setting.object.ts @@ -25,7 +25,8 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * 2. sys_platform_setting (source='global') * 3. sys_setting WHERE scope='tenant' (source='tenant') * 4. sys_setting WHERE scope='user' (source='user') - * 5. manifest specifier.default (source='default') + * 5. deployment-declared default, else + * manifest specifier.default (source='default') * * Encryption: rows with `encrypted=true` store ciphertext in `value_enc` * and leave `value` null. The plain value is never written to audit log diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 6115a5d0840..bb5355b7392 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -5863,6 +5863,18 @@ export class AuthManager { return this.resolveSsoOnly() || isCloudManaged(); } + /** + * Whether self-registration runs off for a given declared + * `emailAndPassword.disableSignUp`: forced off ({@link signUpForcedOff}), + * else the deployment env (`readDisableSignUpEnv`), else the declaration, + * else on. The one formula `getPublicConfig()` answers with, and the one the + * auth plugin states as `auth.signup_enabled`'s declared default (the value + * the switch shows while nothing is stored), so the two cannot disagree. + */ + public resolveDisableSignUp(declared: boolean | undefined): boolean { + return this.signUpForcedOff() ? true : (readDisableSignUpEnv() ?? declared ?? false); + } + /** * The tenancy posture ACTUALLY IN FORCE on this deployment — the one fact * both `organization/create`'s gate and `/auth/config`'s @@ -6053,7 +6065,6 @@ export class AuthManager { // lock registration policy; otherwise we fall back to configured/settings // `emailAndPassword.disableSignUp` (default `false`). const emailPasswordConfig: Partial = this.config.emailAndPassword ?? {}; - const disableSignUpFromEnv = readDisableSignUpEnv(); // SSO-only ("enforced") hides the local password form + self-registration. // `enabled` stays true (break-glass), but signup is forced off and the UI // suppresses the password form via `features.ssoEnforced` below. A @@ -6070,7 +6081,7 @@ export class AuthManager { const audience = this.getAudience(); const emailPassword = { enabled: emailPasswordConfig.enabled !== false, // Default to true - disableSignUp: this.signUpForcedOff() ? true : (disableSignUpFromEnv ?? emailPasswordConfig.disableSignUp ?? false), + disableSignUp: this.resolveDisableSignUp(emailPasswordConfig.disableSignUp), // Mirrors the wiring in createAuthInstance() through the SAME resolver: // a self-registration-permitting posture forces verification ON, except // an `open` deployment's explicit opt-out (#20389) — the advertised flag diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 2fb46e897c5..05a83a06bd9 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -160,6 +160,7 @@ import { type SignInMethodFloorDeps, } from './sign-in-method-floor.js'; import { describeEmailPasswordLiveStatus, type AuthLiveStatus } from './auth-settings-live-status.js'; +import { registerAuthDeclaredDefaults } from './auth-settings-declared-defaults.js'; import { judgePlatformAdmin, judgeHeldSession, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js'; import { decideDemoStaffEnvironmentGate, @@ -265,6 +266,12 @@ interface SettingsReadSurface { namespace: string, provider: (input: { ctx: Record; locale?: string }) => Promise, ): void; + /** + * State what a key takes in the running system while nothing is stored + * (`SettingsService.registerDeclaredDefault`). Optional, like `subscribe`. + * See auth-settings-declared-defaults.ts. + */ + registerDeclaredDefault?(namespace: string, key: string, provider: () => unknown): void; } /** [#23367] The auth setting that records when the API-key lifecycle policy took effect. */ @@ -2502,8 +2509,10 @@ export class AuthPlugin implements Plugin { * Bind the small open-source auth settings namespace to better-auth config. * * Only explicit settings values (stored or OS_AUTH_* env overrides) affect - * runtime config. Manifest defaults are UI defaults and do not mask code or - * deployment configuration. + * runtime config. A `source: 'default'` value is never applied: it is the + * manifest's UI default, or, for the keys in auth-settings-declared-defaults.ts, + * the deployment's own declaration read back, which the running config + * already holds. * * Call through {@link ensureAuthSettingsBound}, never directly. */ @@ -2522,6 +2531,16 @@ export class AuthPlugin implements Plugin { // value is stored; the pass below would only apply it. See the module. registerSignInMethodFloor(settings, this.signInMethodFloorDeps(ctx, this.authManager), ctx.logger); + // With nothing stored, the switches read what the deployment declares (the + // value the running config takes), not the manifest's console default. + // See auth-settings-declared-defaults.ts. + const declaringManager = this.authManager; + registerAuthDeclaredDefaults(settings, { + declared: () => this.declaredAuthOptions, + resolveDisableSignUp: (declared) => declaringManager.resolveDisableSignUp(declared), + audiencePosture: () => declaringManager.getAudience().posture, + }, ctx.logger); + const applySettings = async (): Promise => { if (!this.authManager) return; const authManager = this.authManager; @@ -2600,8 +2619,7 @@ export class AuthPlugin implements Plugin { // off keeps it off: the host refuses every password door there, so a // stored value that reads on would only advertise a form that signs // nobody in. The save door refuses turning it on (sign-in-method-floor.ts); - // a row stored before that check, or a re-save of the manifest default - // the save door is never asked about, is not applied. An + // a row stored before that check is not applied. An // `OS_AUTH_EMAIL_PASSWORD_ENABLED` value is the deployment's own // declaration and still applies. let emailPasswordHeldOff = false; @@ -3175,8 +3193,8 @@ export class AuthPlugin implements Plugin { const runPass = (): Promise => (pass = applySettings()); // Setup → Authentication states what runs when the switch says otherwise: - // with nothing stored the switch shows the manifest default while the - // running config takes the deployment's declaration. See auth-settings-live-status.ts. + // a value stored on that a cloud-managed runtime does not apply, or any + // other disagreement. See auth-settings-live-status.ts. if (typeof settings.registerLiveStatus === 'function') { const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager); try { @@ -3194,8 +3212,8 @@ export class AuthPlugin implements Plugin { } catch (err: any) { ctx.logger.warn( '[auth] Setup → Authentication: the live status was NOT registered ' - + `(${String(err?.message ?? err)}), so where the deployment declares email and password sign-in off ` - + 'with nothing saved, the page shows the switch on with nothing saying it is off.', + + `(${String(err?.message ?? err)}), so where a saved email and password value is not what runs ` + + '(a cloud-managed environment holding it off), the page shows the switch on with nothing saying it is off.', ); } } diff --git a/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts b/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts new file mode 100644 index 00000000000..e6649831ba0 --- /dev/null +++ b/packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts @@ -0,0 +1,93 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What Setup → Authentication's switches read while nothing is stored: the + * value the running config takes for the key, not the manifest's console + * default. + * + * The settings pass applies only stored or `OS_*` values, and with nothing + * stored the running config keeps the deployment's own declaration (plugin + * options and `auth:configure` handlers, `auth-settings-declared.ts`). The + * settings service resolved such a key to the manifest default, so a + * deployment that declared email and password off showed the switch on, and + * a save of that default read as "no change" to the key's write predicates. + * Each key here states its declaration to the settings service + * (`registerDeclaredDefault`, ADR-0007 §Resolution rung 4 as amended); the + * service answers it at the bottom of the cascade, still `source: 'default'` + * (nothing is stored), and a stored value or an `OS_*` override still wins. + * + * Only the keys whose declaration can differ from their manifest default + * through a value the deployment itself states, each computed through the + * formula the running config answers with, so the two cannot disagree: + * + * - `email_password_enabled` (manifest `true`): `emailAndPassword.enabled`, + * on unless declared `false` (`getPublicConfig().emailPassword.enabled`). + * - `signup_enabled` (manifest `true`): off where self-registration is + * forced off (SSO-only, cloud-managed), else per the deployment env, else + * per the declared `emailAndPassword.disableSignUp` + * (`AuthManager.resolveDisableSignUp`). + * - `require_email_verification` (manifest `false`): the declared + * `emailAndPassword.requireEmailVerification` under the audience posture in + * force (`resolveEmailVerificationRequirement`) — on under `email_domain`, + * on under `open` unless declared `false`. + * + * Asked by the settings service on each read, never recorded here, so a + * posture change or a host flag is followed at once. + */ + +import type { AudiencePosture } from '@objectstack/spec/system'; +import { resolveEmailVerificationRequirement } from './audience-posture.js'; +import type { DeclaredAuthOptions } from './auth-settings-declared.js'; + +/** What a declared default is computed from, all read when asked. */ +export interface AuthDeclaredDefaultFacts { + /** The deployment's own values, captured in `init()` before any setting applied. */ + declared(): DeclaredAuthOptions; + /** `AuthManager.resolveDisableSignUp`: self-registration off for a declared `disableSignUp`. */ + resolveDisableSignUp(declared: boolean | undefined): boolean; + /** The audience posture in force (`AuthManager.getAudience().posture`). */ + audiencePosture(): AudiencePosture; +} + +/** Each key's declared default, by key. */ +export const AUTH_DECLARED_DEFAULTS: Readonly boolean>> = { + email_password_enabled: (facts) => facts.declared().emailAndPassword?.enabled !== false, + signup_enabled: (facts) => !facts.resolveDisableSignUp(facts.declared().emailAndPassword?.disableSignUp), + require_email_verification: (facts) => + resolveEmailVerificationRequirement( + facts.audiencePosture(), + facts.declared().emailAndPassword?.requireEmailVerification, + ), +}; + +/** The slice of the settings service this needs (structural: no package dependency). */ +export interface DeclaredDefaultHost { + registerDeclaredDefault?(namespace: string, key: string, provider: () => unknown): void; +} + +/** + * Register every key in {@link AUTH_DECLARED_DEFAULTS}. A settings surface + * without the seam is skipped, as every optional method of that surface is + * (`registerLiveStatus`, `subscribe`). A registration that throws leaves that + * switch reading the manifest default while nothing is stored: said at + * `warn` (a functional degradation — nothing stored is lost), naming the + * consequence. + */ +export function registerAuthDeclaredDefaults( + host: DeclaredDefaultHost, + facts: AuthDeclaredDefaultFacts, + logger: { warn(message: string): void }, +): void { + if (typeof host.registerDeclaredDefault !== 'function') return; + for (const [key, compute] of Object.entries(AUTH_DECLARED_DEFAULTS)) { + try { + host.registerDeclaredDefault('auth', key, () => compute(facts)); + } catch (err: any) { + logger.warn( + `[auth] Setup → Authentication: the declared default of auth.${key} was NOT registered ` + + `(${String(err?.message ?? err)}), so with nothing saved that switch shows the console default rather ` + + 'than what this deployment runs.', + ); + } + } +} diff --git a/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts index ddc39b34678..a92c7be2186 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.test.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Setup → Authentication says what runs when the email and password switch - * says otherwise (`auth-settings-live-status.ts`). + * Setup → Authentication shows what runs (`auth-settings-declared-defaults.ts`, + * `auth-settings-live-status.ts`). * * Through the REAL settings service (`@objectstack/service-settings`, aliased * to its source) and its real `GET /api/settings/:namespace` route, the one @@ -10,16 +10,19 @@ * * Pinned: * 1. a deployment that declares email and password off, with nothing stored: - * the switch still resolves to the manifest default (`true`, `source: - * 'default'`) while the runtime runs it off, and the page is headed by a - * live-status banner saying it is off on this deployment, in the caller's - * language (measured before the change: no banner); + * the switch resolves to the declaration (`false`, `source: 'default'`), + * what runs, and the page states nothing (measured before the change: the + * manifest default `true` and an `info` banner saying it is off); * 2. CONTROL: email and password declared on (the default), nothing stored: - * no banner; + * `true`, no banner; * 3. a stored value still wins where it is applied: saved on over a declared * off, or saved off over a declared on, and the page states nothing; - * 4. on a cloud-managed runtime that holds it off: the banner says so, `info` - * with nothing stored, `warning` over a stored on that is not applied. + * 4. on a cloud-managed runtime that holds it off: nothing stored reads off + * with no banner; a value stored on, not applied, is the one case the + * value cannot say, headed by a `warning`; + * 5. `signup_enabled` and `require_email_verification` read their + * declarations the same way: self-registration declared off or forced off + * by SSO-only, verification forced on by the `email_domain` posture. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -39,9 +42,9 @@ import { AUTH_LIVE_STATUS_COPY, describeEmailPasswordLiveStatus } from './auth-s const SECRET = 'test-secret-at-least-32-chars-long'; const ADMIN = { enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }; -const ENV_KEYS = ['OS_CLOUD_MANAGED', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_SSO_ONLY'] as const; +const ENV_KEYS = ['OS_CLOUD_MANAGED', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_SSO_ONLY', 'OS_DISABLE_SIGNUP'] as const; -describe('Setup → Authentication states email and password sign-in as it runs', () => { +describe('Setup → Authentication shows the auth switches as they run', () => { const savedEnv: Partial> = {}; const setManaged = (on: boolean) => { @@ -69,9 +72,15 @@ describe('Setup → Authentication states email and password sign-in as it runs' }); /** Boot as a host does (init → start → kernel:ready), with email and password declared as given. */ - const boot = async (opts: { emailPassword?: boolean; hostSignInHandoff?: boolean } = {}) => { - const settings = new SettingsService({ env: {} }); - settings.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); + const boot = async (opts: { + emailPassword?: boolean; + emailAndPassword?: Record; + audience?: Record; + hostSignInHandoff?: boolean; + settings?: SettingsService; + } = {}) => { + const settings = opts.settings ?? new SettingsService({ env: {} }); + if (!opts.settings) settings.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); const hooks = new Map Promise>>(); const ctx = { registerService: vi.fn(), @@ -91,7 +100,13 @@ describe('Setup → Authentication states email and password sign-in as it runs' const plugin = new AuthPlugin({ secret: SECRET, baseUrl: 'http://localhost:3000', - ...(opts.emailPassword === undefined ? {} : { emailAndPassword: { enabled: opts.emailPassword } }), + ...(opts.emailPassword === undefined && !opts.emailAndPassword ? {} : { + emailAndPassword: { + ...(opts.emailPassword === undefined ? {} : { enabled: opts.emailPassword }), + ...opts.emailAndPassword, + }, + }), + ...(opts.audience ? { audience: opts.audience } : {}), ...(opts.hostSignInHandoff ? { hostSignInHandoff: true } : {}), }); await plugin.init(ctx); @@ -135,43 +150,36 @@ describe('Setup → Authentication states email and password sign-in as it runs' /** Let the settings pass a write's change event started run to its end. */ const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); - it('declared off with nothing stored: the switch reads the default, and the page says it is off', async () => { + it('declared off with nothing stored: the switch reads the declaration, and the page states nothing', async () => { const { settings, manager } = await boot({ emailPassword: false }); expect(passwordOn(manager)).toBe(false); - // The stored-value read is unchanged: nothing is stored, so the manifest default. - expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'default' }); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: false, source: 'default' }); const { page, banner } = await readPage(settings); - expect(page.values.email_password_enabled).toMatchObject({ value: true, source: 'default' }); - expect(banner).toMatchObject({ - type: 'info_banner', - label: AUTH_LIVE_STATUS_COPY.en.declaredOffLabel, - bannerText: AUTH_LIVE_STATUS_COPY.en.declaredOffText, - bannerSeverity: 'info', - }); - // It heads the page. - expect(page.manifest.specifiers[0].id).toBe(SETTINGS_LIVE_STATUS_BANNER_ID); - - // In the caller's language. - const zh = await readPage(settings, { 'accept-language': 'zh-CN' }); - expect(zh.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY['zh-CN'].declaredOffLabel }); + expect(page.values.email_password_enabled).toMatchObject({ value: false, source: 'default', locked: false }); + expect(banner).toBeUndefined(); }); - it('CONTROL: declared on with nothing stored, the page states nothing', async () => { + it('CONTROL: declared on with nothing stored, the switch reads on and the page states nothing', async () => { const { settings, manager } = await boot(); expect(passwordOn(manager)).toBe(true); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'default' }); const { page, banner } = await readPage(settings); expect(page.values.email_password_enabled).toMatchObject({ value: true, source: 'default' }); expect(banner).toBeUndefined(); }); - it('a stored value still wins where it is applied, and the page states nothing', async () => { - const off = await boot({ emailPassword: false }); + it('a stored value still wins where it is applied, and a clear returns to the declaration', async () => { + // The host's sign-in handoff keeps a way in, so the sign-in floor lets the clear below through. + const off = await boot({ emailPassword: false, hostSignInHandoff: true }); await off.settings.setMany('auth', { email_password_enabled: true }); await vi.waitFor(() => expect(passwordOn(off.manager)).toBe(true)); const savedOn = await readPage(off.settings); expect(savedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' }); expect(savedOn.banner).toBeUndefined(); + await off.settings.setMany('auth', { email_password_enabled: null }); + await vi.waitFor(() => expect(passwordOn(off.manager)).toBe(false)); + expect(await off.settings.get('auth', 'email_password_enabled')).toMatchObject({ value: false, source: 'default' }); // Saved off over a declared on; the host's sign-in handoff keeps a way in, so the sign-in floor lets it through. const on = await boot({ hostSignInHandoff: true }); @@ -183,23 +191,102 @@ describe('Setup → Authentication states email and password sign-in as it runs' expect(savedOff.banner).toBeUndefined(); }); - it('a cloud-managed runtime that holds it off says so: info with nothing stored, warning over a stored on', async () => { + it('a cloud-managed runtime that holds it off: nothing stored reads off; a value stored on is stated as a warning', async () => { setManaged(true); const { settings, manager } = await boot({ emailPassword: false }); const nothingStored = await readPage(settings); - expect(nothingStored.banner).toMatchObject({ + expect(nothingStored.page.values.email_password_enabled).toMatchObject({ value: false, source: 'default' }); + expect(nothingStored.banner).toBeUndefined(); + + // A row stored on before boot (the save door now refuses a save of on here) is not applied. + const seeded = new SettingsService({ env: {} }); + seeded.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!); + await seeded.set('auth', 'email_password_enabled', true, {}); + const held = await boot({ emailPassword: false, settings: seeded }); + await settle(); + expect(passwordOn(held.manager)).toBe(false); + const storedOn = await readPage(held.settings); + expect(storedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' }); + expect(storedOn.banner).toMatchObject({ + type: 'info_banner', label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel, bannerText: AUTH_LIVE_STATUS_COPY.en.managedOffText, - bannerSeverity: 'info', + bannerSeverity: 'warning', }); - - // A re-save of the default is stored and not applied (the settings pass's managed hold). - await settings.setMany('auth', { email_password_enabled: true }); - await settle(); + expect(storedOn.page.manifest.specifiers[0].id).toBe(SETTINGS_LIVE_STATUS_BANNER_ID); + const zh = await readPage(held.settings, { 'accept-language': 'zh-CN' }); + expect(zh.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY['zh-CN'].managedOffLabel }); expect(passwordOn(manager)).toBe(false); - const storedOn = await readPage(settings); - expect(storedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' }); - expect(storedOn.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel, bannerSeverity: 'warning' }); + }); + + it('signup_enabled reads the declaration: declared off, or forced off by SSO-only; CONTROL on', async () => { + const control = await boot(); + expect(control.manager.getPublicConfig().emailPassword.disableSignUp).toBe(false); + expect((await readPage(control.settings)).page.values.signup_enabled).toMatchObject({ value: true, source: 'default' }); + + const declared = await boot({ emailAndPassword: { disableSignUp: true } }); + expect(declared.manager.getPublicConfig().emailPassword.disableSignUp).toBe(true); + expect((await readPage(declared.settings)).page.values.signup_enabled).toMatchObject({ value: false, source: 'default' }); + // A stored value still wins over it. + await declared.settings.setMany('auth', { signup_enabled: true }); + await vi.waitFor(() => expect(declared.manager.getPublicConfig().emailPassword.disableSignUp).toBe(false)); + expect(await declared.settings.get('auth', 'signup_enabled')).toMatchObject({ value: true, source: 'global' }); + + process.env.OS_AUTH_SSO_ONLY = 'true'; + const ssoOnly = await boot(); + expect(ssoOnly.manager.getPublicConfig().emailPassword.disableSignUp).toBe(true); + expect(await ssoOnly.settings.get('auth', 'signup_enabled')).toMatchObject({ value: false, source: 'default' }); + }); + + it('signup_enabled reads off where a cloud-managed runtime or OS_DISABLE_SIGNUP turns sign-up off', async () => { + process.env.OS_DISABLE_SIGNUP = 'true'; + const envOff = await boot(); + expect(envOff.manager.getPublicConfig().emailPassword.disableSignUp).toBe(true); + expect(await envOff.settings.get('auth', 'signup_enabled')).toMatchObject({ value: false, source: 'default' }); + delete process.env.OS_DISABLE_SIGNUP; + + setManaged(true); + const managed = await boot(); + expect(managed.manager.getPublicConfig().emailPassword.disableSignUp).toBe(true); + expect(await managed.settings.get('auth', 'signup_enabled')).toMatchObject({ value: false, source: 'default' }); + }); + + it('declared off, nothing stored: the keys shown only while email and password is on are hidden, so a save of one is not judged', async () => { + // The same as under a stored `false`: password_min_length (min 6) is visible only while + // email_password_enabled !== false, and a hidden specifier is not validated. + const off = await boot({ emailPassword: false }); + await expect(off.settings.setMany('auth', { password_min_length: 2 })).resolves.toBeDefined(); + expect(await off.settings.get('auth', 'password_min_length')).toMatchObject({ value: 2, source: 'global' }); + // Turning email and password on re-judges it (it is the gated key's visibility dependency). + await expect(off.settings.setMany('auth', { email_password_enabled: true })).rejects.toMatchObject({ + code: 'SETTINGS_VALIDATION', + fields: [expect.objectContaining({ field: 'password_min_length' })], + }); + + // CONTROL: declared on, the same save is refused at the key's bound. + const on = await boot(); + await expect(on.settings.setMany('auth', { password_min_length: 2 })).rejects.toMatchObject({ + code: 'SETTINGS_VALIDATION', + fields: [expect.objectContaining({ field: 'password_min_length' })], + }); + expect(await on.settings.get('auth', 'password_min_length')).toMatchObject({ source: 'default' }); + }); + + it('require_email_verification reads the declaration under the posture in force; CONTROL off', async () => { + const control = await boot(); + expect(control.manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(false); + expect(await control.settings.get('auth', 'require_email_verification')).toMatchObject({ value: false, source: 'default' }); + + const declared = await boot({ emailAndPassword: { requireEmailVerification: true } }); + expect(declared.manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(true); + expect(await declared.settings.get('auth', 'require_email_verification')).toMatchObject({ value: true, source: 'default' }); + + const domain = await boot({ + audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'member_default' }, + }); + expect(domain.manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(true); + expect((await readPage(domain.settings)).page.values.require_email_verification) + .toMatchObject({ value: true, source: 'default' }); }); }); diff --git a/packages/plugins/plugin-auth/src/auth-settings-live-status.ts b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts index 0b9f17ae54a..11d7a879a23 100644 --- a/packages/plugins/plugin-auth/src/auth-settings-live-status.ts +++ b/packages/plugins/plugin-auth/src/auth-settings-live-status.ts @@ -8,20 +8,19 @@ import type { SettingsCopyLocale } from './settings-copy-locale.js'; * RUNS, when that differs from the switch on the page. * * The switch shows what `auth.email_password_enabled` resolves to. With nothing - * stored that is the manifest default (on), while the running config takes - * the deployment's own declaration (`emailAndPassword.enabled`): the settings - * pass applies only stored or `OS_*` values, and the manifest default is a - * console default that never rules (`auth-settings-declared.ts`). So a - * deployment that declares email and password off, with nothing stored, shows - * the switch on for a sign-in method that is off. A cloud-managed runtime that - * holds it off (`emailPasswordHeldOffByHost`) shows a stored on that is not - * applied the same way. + * stored that is the deployment's own declaration (`emailAndPassword.enabled`, + * `auth-settings-declared-defaults.ts`), which is what runs, so the switch + * itself says it and nothing is stated. What the value still cannot say is a + * stored value the runtime does not apply: on a cloud-managed runtime that + * holds email and password off (`emailPasswordHeldOffByHost`), a value stored + * on shows the switch on for a sign-in method that is off; and any other + * disagreement between the switch and what runs. Those head the page as a + * `warning`. * * The settings service's live-status seam (`registerLiveStatus`) is how a page * says what runs beside what is stored; its `values` serve option-bearing keys * only, so a toggle is stated in the banner that heads the page. Read at - * request time, never recorded at boot; nothing is stated while the switch - * and the running value agree. + * request time, never recorded at boot. * * Same shape as service-settings' `SettingsLiveStatus`, restated because this * plugin reaches the settings service through a structural surface and takes @@ -47,10 +46,7 @@ export interface EmailPasswordLiveInput { /** The words of the statement, one entry per language on the platform locale table. */ export interface AuthLiveStatusCopy { - /** Declared off by the deployment, nothing stored. */ - declaredOffLabel: string; - declaredOffText: string; - /** Held off by the host on a cloud-managed runtime. */ + /** Held off by the host on a cloud-managed runtime, over a value stored on. */ managedOffLabel: string; managedOffText: string; /** Any other disagreement between the switch and what runs. */ @@ -60,10 +56,6 @@ export interface AuthLiveStatusCopy { export const AUTH_LIVE_STATUS_COPY: Record = { en: { - declaredOffLabel: 'Email and password sign-in is off on this deployment', - declaredOffText: 'This deployment\'s own configuration turns email and password sign-in off, and nothing is ' - + 'saved here, so the switch below shows the console default (on), not what runs. The sign-in page offers ' - + 'no email and password form. A value saved here takes precedence over that configuration.', managedOffLabel: 'Email and password sign-in is off on this environment', managedOffText: 'This environment is cloud-managed and its deployment turns email and password sign-in off: ' + 'people sign in through the identity provider of the organisation that hosts it, and the sign-in page ' @@ -73,9 +65,6 @@ export const AUTH_LIVE_STATUS_COPY: Record { - const { settings, manager, heldOffSaid } = await boot(); + it('with nothing stored the switch reads the declaration, so a save of on is a change the save door refuses', async () => { + const { settings, manager } = await boot(); expect(passwordOn(manager)).toBe(false); + // The deployment's declaration (off) answers the bottom rung, not the manifest default (on). + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: false, source: 'default' }); - // With nothing stored the value resolves to the manifest default (on), so - // this save is no change to the settings service, reaches no predicate, - // and is stored. Measured before the fix: the public config answered true. - await settings.setMany('auth', { email_password_enabled: true }); + // Before the declared default, `true` resolved as the current value, so + // this save was no change, reached no predicate, and was stored. + const refusal = await refusalOf(settings.setMany('auth', { email_password_enabled: true })); + expect(refusal.code).toBe('SETTINGS_VALIDATION'); + expect(refusal.fields).toEqual([ + expect.objectContaining({ + field: 'email_password_enabled', + code: 'invalid_value', + constraint: { cloudManaged: true, declaredEmailPassword: false }, + }), + ]); + expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: false, source: 'default' }); + + const http = await put(settings, { email_password_enabled: true }); + expect(http.status).toBe(400); + expect(http.body.error.code).toBe('SETTINGS_VALIDATION'); + await settle(); + expect(passwordOn(manager)).toBe(false); + }); + + it('a stored value that reads on is not applied: the public config keeps answering off, said once', async () => { + // Stored before boot, as a row written before the save door existed. + const seeded = makeSettings(); + await seeded.set('auth', 'email_password_enabled', true, {}); + const { settings, manager, heldOffSaid } = await boot({ settings: seeded }); expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'global' }); await settle(); expect(passwordOn(manager)).toBe(false); @@ -1175,8 +1198,9 @@ describe('a cloud-managed runtime keeps email and password off when its deployme }); it('a row stored on is put right by clearing it, which the sign-in floor does not refuse', async () => { - const { settings, manager, heldOffSaid } = await boot(); - await settings.setMany('auth', { email_password_enabled: true }); + const seeded = makeSettings(); + await seeded.set('auth', 'email_password_enabled', true, {}); + const { settings, manager, heldOffSaid } = await boot({ settings: seeded }); await settle(); expect(heldOffSaid()).toHaveLength(1); @@ -1192,11 +1216,16 @@ describe('a cloud-managed runtime keeps email and password off when its deployme await vi.waitFor(() => expect( manager.getPublicConfig().socialProviders.some((p: { id: string }) => p.id === 'google'), ).toBe(true)); - // `true` is the resolved default here, so no predicate is asked at that key; - // the Google key must not read it as a way in the runtime will offer. + // The key's own save door refuses `true` (the declaration, off, is what it + // resolves to); the Google key must not read it as a way in either. const refusal = await refusalOf(settings.setMany('auth', { email_password_enabled: true, google_enabled: false })); expect(refusal.code).toBe('SETTINGS_VALIDATION'); expect(refusal.fields).toEqual([ + expect.objectContaining({ + field: 'email_password_enabled', + code: 'invalid_value', + constraint: { cloudManaged: true, declaredEmailPassword: false }, + }), expect.objectContaining({ field: 'google_enabled', code: 'invalid_value', constraint: { lastSignInMethod: 'google' } }), ]); expect(await settings.get('auth', 'google_enabled')).toMatchObject({ value: true }); diff --git a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts index 6e215db8591..7a770c27936 100644 --- a/packages/plugins/plugin-auth/src/sign-in-method-floor.ts +++ b/packages/plugins/plugin-auth/src/sign-in-method-floor.ts @@ -780,9 +780,10 @@ async function googleAfter( * Ahead of that, at `email_password_enabled` on a runtime where the host holds * email and password off ({@link emailPasswordHeldOffByHost}): a save of a value * that reads on. The settings service asks a predicate only about a change from - * the value it resolves, and with nothing stored that is the manifest default - * (on), so re-saving that default reaches no predicate; the settings pass is - * what keeps such a row from taking effect. + * the value it resolves; with nothing stored that is the deployment's + * declaration (off, `auth-settings-declared-defaults.ts`), so a save of on + * reaches this refusal. The settings pass still keeps a row stored on before + * this check from taking effect. */ export function signInMethodFloorPredicate(deps: SignInMethodFloorDeps, read: AuthSettingReader) { return async (input: SignInFloorWriteInput): Promise => { diff --git a/packages/services/service-settings/src/index.ts b/packages/services/service-settings/src/index.ts index 5fd28005f4e..bea075bf6e6 100644 --- a/packages/services/service-settings/src/index.ts +++ b/packages/services/service-settings/src/index.ts @@ -58,6 +58,8 @@ export { } from './local-crypto-provider.js'; export { type SettingsActionHandler, + // What the running deployment declares for a key while nothing is stored (ADR-0007 rung 4). + type SettingsDeclaredDefault, type SettingsLiveStatus, type SettingsLiveStatusProvider, type SettingsLiveValue, diff --git a/packages/services/service-settings/src/settings-declared-default.test.ts b/packages/services/service-settings/src/settings-declared-default.test.ts new file mode 100644 index 00000000000..66cacdc2af5 --- /dev/null +++ b/packages/services/service-settings/src/settings-declared-default.test.ts @@ -0,0 +1,158 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A deployment's declared default (`registerDeclaredDefault`, ADR-0007 + * §Resolution rung 4 as amended): what a key takes in the running system while + * nothing is stored answers the bottom rung of the cascade in place of the + * manifest `default`, still `source: 'default'`. + * + * Pinned: the read (`get`, `getNamespace`, the cascade chain); a stored value + * and an `OS_*` override still win; a clear returns to it; a write predicate + * sees it as the value in force (so a save of the manifest default is a + * change); `undefined` and a throwing provider leave the manifest default + * (the latter said once); a namespace with no provider is unchanged (CONTROL); + * registration refuses an unknown namespace or key. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { SettingsManifest } from '@objectstack/spec/system'; +import { SettingsService } from './settings-service.js'; +import { UnknownKeyError, UnknownNamespaceError } from './settings-service.types.js'; + +const manifest = (namespace: string): SettingsManifest => ({ + namespace, + label: namespace, + scope: 'global', + specifiers: [ + { type: 'toggle', key: 'feature_on', label: 'Feature', default: true }, + { type: 'number', key: 'limit', label: 'Limit', default: 5 }, + // No manifest default: its OS_* type comes from the declaration alone. + { type: 'toggle', key: 'bare', label: 'Bare' }, + ], +} as unknown as SettingsManifest); + +/** A switch with a required key shown only while it is not off. */ +const gated = { + namespace: 'gated', + label: 'gated', + scope: 'global', + specifiers: [ + { type: 'toggle', key: 'switch_on', label: 'Switch', default: true }, + { type: 'text', key: 'extra', label: 'Extra', required: true, visible: '${data.switch_on !== false}' }, + ], +} as unknown as SettingsManifest; + +function rig(env: Record = {}) { + const logger = { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }; + const svc = new SettingsService({ env, logger } as any); + svc.registerManifest(manifest('demo')); + svc.registerManifest(manifest('plain')); + svc.registerManifest(gated); + return { svc, logger }; +} + +describe('SettingsService declared default', () => { + it('answers the bottom rung while nothing is stored, as source default', async () => { + const { svc } = rig(); + let declared: unknown = false; + svc.registerDeclaredDefault('demo', 'feature_on', () => declared); + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: false, source: 'default', locked: false }); + const page = await svc.getNamespace('demo'); + expect(page.values.feature_on).toMatchObject({ value: false, source: 'default' }); + expect(page.values.feature_on.cascadeChain).toEqual([{ scope: 'default', value: false, effective: true }]); + // Asked on each read, never recorded. + declared = true; + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: true, source: 'default' }); + }); + + it('CONTROL: a key or namespace with no provider reads the manifest default', async () => { + const { svc } = rig(); + svc.registerDeclaredDefault('demo', 'feature_on', () => false); + expect(await svc.get('demo', 'limit')).toMatchObject({ value: 5, source: 'default' }); + expect(await svc.get('plain', 'feature_on')).toMatchObject({ value: true, source: 'default' }); + }); + + it('a stored value still wins, and a clear returns to the declaration', async () => { + const { svc } = rig(); + svc.registerDeclaredDefault('demo', 'feature_on', () => false); + await svc.setMany('demo', { feature_on: true }); + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: true, source: 'global' }); + await svc.setMany('demo', { feature_on: null }); + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: false, source: 'default' }); + }); + + it('an OS_* override still wins', async () => { + const { svc } = rig({ OS_DEMO_FEATURE_ON: 'true' }); + svc.registerDeclaredDefault('demo', 'feature_on', () => false); + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: true, source: 'env', locked: true }); + }); + + it('a write predicate sees the declaration as the value in force', async () => { + const { svc } = rig(); + svc.registerDeclaredDefault('demo', 'feature_on', () => false); + const predicate = vi.fn(() => undefined); + svc.registerWritePredicate('demo', 'feature_on', predicate); + // The manifest default is a change from the declaration: the predicate is asked. + await svc.setMany('demo', { feature_on: true }); + expect(predicate).toHaveBeenCalledTimes(1); + expect((predicate.mock.calls[0] as unknown[])[0]).toMatchObject({ current: false, next: true }); + + // Re-saving the declaration is no change. + const { svc: other } = rig(); + other.registerDeclaredDefault('demo', 'feature_on', () => false); + const quiet = vi.fn(() => undefined); + other.registerWritePredicate('demo', 'feature_on', quiet); + await other.setMany('demo', { feature_on: false }); + expect(quiet).not.toHaveBeenCalled(); + }); + + it('undefined leaves the manifest default; a throwing provider does too, said once', async () => { + const { svc, logger } = rig(); + svc.registerDeclaredDefault('demo', 'limit', () => undefined); + expect(await svc.get('demo', 'limit')).toMatchObject({ value: 5, source: 'default' }); + + svc.registerDeclaredDefault('demo', 'feature_on', () => { + throw new Error('manager gone'); + }); + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: true, source: 'default' }); + await svc.get('demo', 'feature_on'); + const said = logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes("'demo.feature_on'")); + expect(said).toHaveLength(1); + expect(said[0]).toContain('manager gone'); + }); + + it('a provider that answers a promise is a fault: the manifest default answers, said once', async () => { + const { svc, logger } = rig(); + svc.registerDeclaredDefault('demo', 'feature_on', () => Promise.resolve(false)); + expect(await svc.get('demo', 'feature_on')).toMatchObject({ value: true, source: 'default' }); + expect(logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('promise'))).toHaveLength(1); + }); + + it('a clear in a patch takes the declaration for the patch\'s visibility map', async () => { + // Declared off: clearing switch_on hides `extra`, so its `required` is not judged. + const { svc } = rig(); + svc.registerDeclaredDefault('gated', 'switch_on', () => false); + await svc.setMany('gated', { switch_on: true, extra: 'x' }); + await expect(svc.setMany('gated', { switch_on: null, extra: '' })).resolves.toBeDefined(); + // CONTROL: no provider, the clear falls back to the manifest default (on), so `extra` is required. + const { svc: plain } = rig(); + await plain.setMany('gated', { switch_on: false }); + await expect(plain.setMany('gated', { switch_on: null, extra: '' })).rejects.toMatchObject({ + code: 'SETTINGS_VALIDATION', + fields: [expect.objectContaining({ field: 'extra', code: 'required' })], + }); + }); + + it('an OS_* value is read as the type of the declaration where the manifest declares no default', async () => { + const { svc } = rig({ OS_DEMO_BARE: 'yes' }); + expect(await svc.get('demo', 'bare')).toMatchObject({ value: 'yes', source: 'env' }); + svc.registerDeclaredDefault('demo', 'bare', () => false); + expect(await svc.get('demo', 'bare')).toMatchObject({ value: true, source: 'env' }); + }); + + it('registration refuses an unknown namespace or key', () => { + const { svc } = rig(); + expect(() => svc.registerDeclaredDefault('nope', 'feature_on', () => false)).toThrow(UnknownNamespaceError); + expect(() => svc.registerDeclaredDefault('demo', 'nope', () => false)).toThrow(UnknownKeyError); + }); +}); diff --git a/packages/services/service-settings/src/settings-service.ts b/packages/services/service-settings/src/settings-service.ts index d4778e068c1..0ce754694af 100644 --- a/packages/services/service-settings/src/settings-service.ts +++ b/packages/services/service-settings/src/settings-service.ts @@ -32,6 +32,7 @@ import { } from './crypto-adapter.js'; import { type SettingsActionHandler, + type SettingsDeclaredDefault, type SettingsLiveStatus, type SettingsLiveStatusProvider, type SettingsLiveValue, @@ -1013,6 +1014,10 @@ export class SettingsService { private optionSourceVerdictsHeld = false; /** Sourced keys whose `OS_*` override was taken in force while held, `[namespace, key]`. */ private readonly heldOptionSourceVerdicts = new Map(); + /** Declared defaults by namespace, then key — see {@link registerDeclaredDefault}. */ + private readonly declaredDefaults = new Map>(); + /** Declared-default failures already said, `namespace.key` — see {@link defaultOf}. */ + private readonly reportedDeclaredDefaultFaults = new Set(); /** Write predicates by namespace, then key — see {@link registerWritePredicate}. */ private readonly writePredicates = new Map< string, @@ -1638,7 +1643,8 @@ export class SettingsService { const envRaw = this.env[envName]; if (typeof envRaw !== 'string') return null; - const value = coerceEnvValue(envRaw, reg.defaults.get(key)); + // The type the key's default has (ADR-0007 rung 4, see `defaultOf`). + const value = coerceEnvValue(envRaw, this.defaultOf(reg, key)); // Families are judged in the SAME order `validatePatch` judges them — // options (when no domain is declared) → pattern → valueDomain → bounds — @@ -2189,6 +2195,65 @@ export class SettingsService { }); } + /** + * Register (or replace) what the running deployment declares for one + * manifest key — the value the key takes in the running system while nothing + * is stored and no `OS_*` override is in force. See + * {@link SettingsDeclaredDefault}. The last registration wins, the same + * override rule as {@link registerAction}. + */ + registerDeclaredDefault(namespace: string, key: string, provider: SettingsDeclaredDefault): void { + const reg = this.registry.get(namespace); + if (!reg) throw new UnknownNamespaceError(namespace); + if (!reg.scopes.has(key)) throw new UnknownKeyError(namespace, key); + let byKey = this.declaredDefaults.get(namespace); + if (!byKey) this.declaredDefaults.set(namespace, (byKey = new Map())); + byKey.set(key, provider); + } + + /** + * The bottom rung of the cascade for one key (ADR-0007 §Resolution, rung 4, + * as amended): what the deployment declares for it + * ({@link registerDeclaredDefault}), else the manifest `default`. + * + * THE one place that answers it, for every site that reads the default: the + * cascade walk, a patch's clear, and the type an `OS_*` value is read as. + * Before, those three read the manifest default, so with nothing stored a + * key read as a console default the runtime never applied, and a save of + * that default was "no change" to every write predicate. + * + * Asked on each use, never cached, so it follows the deployment's state. A + * provider that throws is a functional degradation, not a durability one: + * nothing claimed persisted is lost, the page shows the manifest default as + * it did before this seam — so `warn`, once per key, naming the consequence. + */ + private defaultOf(reg: RegisteredManifest, key: string): unknown { + const namespace = reg.manifest.namespace; + const provider = this.declaredDefaults.get(namespace)?.get(key); + if (provider) { + try { + const declared = provider(); + // A provider is synchronous by contract (the cascade reads it inline); + // a promise would be served as the value, so it is a fault like a throw. + if (declared !== null && typeof declared === 'object' && typeof (declared as { then?: unknown }).then === 'function') { + throw new Error('the provider answered a promise; a declared default is answered synchronously'); + } + if (declared !== null && declared !== undefined) return declared; + } catch (err: any) { + const id = `${namespace}.${key}`; + if (!this.reportedDeclaredDefaultFaults.has(id)) { + this.reportedDeclaredDefaultFaults.add(id); + this.logger?.warn?.( + `SettingsService: the deployment's declared default for setting '${id}' could not be read, so with ` + + 'nothing stored it resolves to the manifest default, which may not be what runs. ' + + `Cause: ${err?.message ?? err}`, + ); + } + } + } + return reg.defaults.get(key); + } + /** * The namespace's live-status statement as an `info_banner` specifier, ready * to head the page, or `undefined` when no provider is registered or the @@ -2648,7 +2713,8 @@ export class SettingsService { } } - const def = reg.defaults.get(key); + // Rung 4: what the deployment declares, else the manifest default (`defaultOf`). + const def = this.defaultOf(reg, key); chain.push({ scope: 'default', value: def ?? null }); // Effective row: highest priority entry. Lock anywhere up the chain @@ -3563,7 +3629,7 @@ export class SettingsService { } for (const [key, value] of entries) { data[key] = value === null || typeof value === 'undefined' - ? reg.defaults.get(key) ?? null + ? this.defaultOf(reg, key) ?? null : value; } diff --git a/packages/services/service-settings/src/settings-service.types.ts b/packages/services/service-settings/src/settings-service.types.ts index fe173f5c4cc..a0f0a2235c3 100644 --- a/packages/services/service-settings/src/settings-service.types.ts +++ b/packages/services/service-settings/src/settings-service.types.ts @@ -551,6 +551,30 @@ export type SettingsLiveStatusProvider = (input: { locale?: string; }) => Promise | SettingsLiveStatus | undefined; +/** + * What the running deployment itself declares for one manifest key: the value + * the key takes in the running system while nothing is stored for it and no + * `OS_*` override is in force. A manifest `default` is the console's default; + * a package whose runtime takes a key from its own configuration when nothing + * is stored (plugin options, a host declaration) states that value here, so + * the bottom rung of the cascade answers what runs, not a default nothing + * applies (ADR-0007 §Resolution, rung 4, as amended). + * + * Answered with `undefined` (or `null`) when the deployment declares nothing + * for the key: the manifest `default` then stands, unchanged. Asked at the + * moment it is used, never recorded: on every read that reaches the bottom + * rung (`get`, `getMany`, `getNamespace`, and through them a write's change + * test), when a patch clears the key, and as the type an `OS_*` value is read + * as. Answered synchronously: a provider that throws, or that answers a + * promise, is reported once and the manifest `default` answers in its place. + * The answer is not judged against the specifier's type or options: it is the + * running system's own value, and the provider owns its shape. + * + * The answer still reports `source: 'default'`: the value is the deployment's + * default, nothing is stored, and a clear returns to it. + */ +export type SettingsDeclaredDefault = () => unknown; + /** One option a {@link SettingsOptionSource} serves: the stored value and its name. */ export interface SettingsServedOption { value: string; diff --git a/packages/spec/src/system/settings-manifest.zod.ts b/packages/spec/src/system/settings-manifest.zod.ts index 95350d0c798..3cc31ada076 100644 --- a/packages/spec/src/system/settings-manifest.zod.ts +++ b/packages/spec/src/system/settings-manifest.zod.ts @@ -26,7 +26,8 @@ import { LIFECYCLE_DURATION_REGEX } from '../data/object.zod'; * 1. process.env override (source='env', locked=true) * 2. sys_setting scope=tenant * 3. sys_setting scope=user - * 4. manifest specifier.default + * 4. what the running deployment declares for the key, else the manifest + * specifier.default (source='default'; ADR-0007 rung 4 as amended) */ // --------------------------------------------------------------------------- @@ -162,7 +163,8 @@ export type SpecifierHandlerParsed = z.infer; * * Specifier resolution scopes. Listed in cascade order (low → high * priority): `env` always wins, then walk down `global → tenant → user`, - * falling back to `default` (declared on the specifier). Adding a new + * falling back to `default` (what the running deployment declares for the + * key, else the specifier's own `default`). Adding a new * scope here requires updating the SettingsService cascade resolver and * the source-badge i18n entries on the UI side. *