Skip to content

Commit ee52361

Browse files
committed
fix(plugin-auth): Setup > Authentication states email and password sign-in as it runs
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK
1 parent 815e882 commit ee52361

3 files changed

Lines changed: 524 additions & 2 deletions

File tree

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ import {
159159
ssoProviderDeleteRefusal,
160160
type SignInMethodFloorDeps,
161161
} from './sign-in-method-floor.js';
162+
import { describeEmailPasswordLiveStatus, type AuthLiveStatus } from './auth-settings-live-status.js';
162163
import { judgePlatformAdmin, judgeHeldSession, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js';
163164
import {
164165
decideDemoStaffEnvironmentGate,
@@ -255,6 +256,15 @@ interface SettingsReadSurface {
255256
predicate: (input: unknown) => unknown,
256257
options?: { requestHeaders?: readonly string[] },
257258
): void;
259+
/**
260+
* State what runs at the top of the namespace's page, read on each page
261+
* request (`SettingsService.registerLiveStatus`). Optional, like `subscribe`.
262+
* See auth-settings-live-status.ts.
263+
*/
264+
registerLiveStatus?(
265+
namespace: string,
266+
provider: (input: { ctx: Record<string, unknown>; locale?: string }) => Promise<AuthLiveStatus | undefined>,
267+
): void;
258268
}
259269

260270
/** [#23367] The auth setting that records when the API-key lifecycle policy took effect. */
@@ -3159,10 +3169,41 @@ export class AuthPlugin implements Plugin {
31593169
// the one-off moves of the toggle-era values onto the levels.
31603170
await this.bindOrganizationAccessPolicy(ctx, settings);
31613171

3162-
await applySettings();
3172+
// The pass a change event started, so the page's statement below reads the
3173+
// running config after it, not mid-way.
3174+
let pass: Promise<void> = Promise.resolve();
3175+
const runPass = (): Promise<void> => (pass = applySettings());
3176+
3177+
// Setup → Authentication states what runs when the switch says otherwise:
3178+
// with nothing stored the switch shows the manifest default while the
3179+
// running config takes the deployment's declaration. See auth-settings-live-status.ts.
3180+
if (typeof settings.registerLiveStatus === 'function') {
3181+
const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager);
3182+
try {
3183+
settings.registerLiveStatus('auth', async ({ ctx: pageCtx, locale }) => {
3184+
await pass;
3185+
const manager = this.authManager;
3186+
if (!manager) return undefined;
3187+
return describeEmailPasswordLiveStatus({
3188+
running: manager.getPublicConfig().emailPassword.enabled,
3189+
shown: await settings.get('auth', 'email_password_enabled', pageCtx),
3190+
heldOffByHost: emailPasswordHeldOffByHost(floorDeps),
3191+
locale,
3192+
});
3193+
});
3194+
} catch (err: any) {
3195+
ctx.logger.warn(
3196+
'[auth] Setup → Authentication: the live status was NOT registered '
3197+
+ `(${String(err?.message ?? err)}), so where the deployment declares email and password sign-in off `
3198+
+ 'with nothing saved, the page shows the switch on with nothing saying it is off.',
3199+
);
3200+
}
3201+
}
3202+
3203+
await runPass();
31633204
if (typeof settings.subscribe === 'function') {
31643205
settings.subscribe('auth', () => {
3165-
void applySettings();
3206+
void runPass();
31663207
});
31673208
ctx.logger.info('Auth: bound to settings namespace=auth');
31683209
}
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Setup → Authentication says what runs when the email and password switch
5+
* says otherwise (`auth-settings-live-status.ts`).
6+
*
7+
* Through the REAL settings service (`@objectstack/service-settings`, aliased
8+
* to its source) and its real `GET /api/settings/:namespace` route, the one
9+
* the settings page reads, over the real `AuthPlugin` / `AuthManager`.
10+
*
11+
* Pinned:
12+
* 1. a deployment that declares email and password off, with nothing stored:
13+
* the switch still resolves to the manifest default (`true`, `source:
14+
* 'default'`) while the runtime runs it off, and the page is headed by a
15+
* live-status banner saying it is off on this deployment, in the caller's
16+
* language (measured before the change: no banner);
17+
* 2. CONTROL: email and password declared on (the default), nothing stored:
18+
* no banner;
19+
* 3. a stored value still wins where it is applied: saved on over a declared
20+
* off, or saved off over a declared on, and the page states nothing;
21+
* 4. on a cloud-managed runtime that holds it off: the banner says so, `info`
22+
* with nothing stored, `warning` over a stored on that is not applied.
23+
*/
24+
25+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
26+
// Paid during collection, not inside a clocked case: the auth manager loads it lazily.
27+
import '@objectstack/core/egress';
28+
import { resetCloudManagedForTesting, type PluginContext } from '@objectstack/core';
29+
import type { IHttpRequest, IHttpResponse, IHttpServer, RouteHandler } from '@objectstack/spec/contracts';
30+
import {
31+
SETTINGS_LIVE_STATUS_BANNER_ID,
32+
SettingsService,
33+
builtinSettingsManifests,
34+
registerSettingsRoutes,
35+
} from '@objectstack/service-settings';
36+
import { AuthPlugin } from './auth-plugin.js';
37+
import type { AuthManager } from './auth-manager.js';
38+
import { AUTH_LIVE_STATUS_COPY, describeEmailPasswordLiveStatus } from './auth-settings-live-status.js';
39+
40+
const SECRET = 'test-secret-at-least-32-chars-long';
41+
const ADMIN = { enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' };
42+
const ENV_KEYS = ['OS_CLOUD_MANAGED', 'OS_AUTH_EMAIL_PASSWORD_ENABLED', 'OS_AUTH_SSO_ONLY'] as const;
43+
44+
describe('Setup → Authentication states email and password sign-in as it runs', () => {
45+
const savedEnv: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>> = {};
46+
47+
const setManaged = (on: boolean) => {
48+
if (on) process.env.OS_CLOUD_MANAGED = '1';
49+
else delete process.env.OS_CLOUD_MANAGED;
50+
// `isCloudManaged()` memoizes its first read.
51+
resetCloudManagedForTesting();
52+
};
53+
54+
beforeEach(() => {
55+
for (const key of ENV_KEYS) {
56+
savedEnv[key] = process.env[key];
57+
delete process.env[key];
58+
}
59+
setManaged(false);
60+
});
61+
62+
afterEach(() => {
63+
for (const key of ENV_KEYS) {
64+
if (savedEnv[key] === undefined) delete process.env[key];
65+
else process.env[key] = savedEnv[key];
66+
}
67+
resetCloudManagedForTesting();
68+
vi.restoreAllMocks();
69+
});
70+
71+
/** Boot as a host does (init → start → kernel:ready), with email and password declared as given. */
72+
const boot = async (opts: { emailPassword?: boolean; hostSignInHandoff?: boolean } = {}) => {
73+
const settings = new SettingsService({ env: {} });
74+
settings.registerManifest(builtinSettingsManifests.find((m) => m.namespace === 'auth')!);
75+
const hooks = new Map<string, Array<() => Promise<void>>>();
76+
const ctx = {
77+
registerService: vi.fn(),
78+
getService: vi.fn((name: string) => {
79+
if (name === 'manifest') return { register: vi.fn() };
80+
if (name === 'settings') return settings;
81+
return undefined;
82+
}),
83+
getServices: vi.fn(() => new Map()),
84+
hook: vi.fn((name: string, handler: () => Promise<void>) => {
85+
hooks.set(name, [...(hooks.get(name) ?? []), handler]);
86+
}),
87+
trigger: vi.fn(),
88+
logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
89+
getKernel: vi.fn(),
90+
} as unknown as PluginContext;
91+
const plugin = new AuthPlugin({
92+
secret: SECRET,
93+
baseUrl: 'http://localhost:3000',
94+
...(opts.emailPassword === undefined ? {} : { emailAndPassword: { enabled: opts.emailPassword } }),
95+
...(opts.hostSignInHandoff ? { hostSignInHandoff: true } : {}),
96+
});
97+
await plugin.init(ctx);
98+
const manager = (ctx.registerService as any).mock.calls.find(([name]: [string]) => name === 'auth')?.[1] as AuthManager;
99+
await plugin.start(ctx);
100+
for (const handler of hooks.get('kernel:ready') ?? []) await handler();
101+
return { settings, manager };
102+
};
103+
104+
/** `GET /api/settings/auth` through the real settings route: the page's own read. */
105+
const readPage = async (settings: SettingsService, headers: Record<string, string> = {}) => {
106+
const routes = new Map<string, RouteHandler>();
107+
const add = (method: string) => (path: string, handler: RouteHandler) => {
108+
routes.set(`${method} ${path}`, handler);
109+
return http;
110+
};
111+
const http = {
112+
get: add('GET'), post: add('POST'), put: add('PUT'), delete: add('DELETE'), patch: add('PATCH'),
113+
use: () => http, listen: async () => {}, close: async () => {}, getInstance: () => null,
114+
} as unknown as IHttpServer;
115+
registerSettingsRoutes(http, settings, { contextFromRequest: () => ({ ...ADMIN }) });
116+
const state: { status: number; body?: any } = { status: 200 };
117+
const res = {
118+
json: vi.fn((data: unknown) => { state.body = data; }),
119+
send: vi.fn(),
120+
status: vi.fn((code: number) => { state.status = code; return res; }),
121+
header: vi.fn(() => res),
122+
} as unknown as IHttpResponse;
123+
const req = {
124+
params: { namespace: 'auth' }, query: {}, headers, method: 'GET', path: '/api/settings/auth',
125+
} as unknown as IHttpRequest;
126+
await routes.get('GET /api/settings/:namespace')!(req, res);
127+
expect(state.status).toBe(200);
128+
const page = state.body?.data ?? state.body;
129+
const banner = (page.manifest.specifiers as Array<Record<string, unknown>>)
130+
.find((spec) => spec.id === SETTINGS_LIVE_STATUS_BANNER_ID);
131+
return { page, banner };
132+
};
133+
134+
const passwordOn = (manager: AuthManager) => manager.getPublicConfig().emailPassword.enabled;
135+
/** Let the settings pass a write's change event started run to its end. */
136+
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
137+
138+
it('declared off with nothing stored: the switch reads the default, and the page says it is off', async () => {
139+
const { settings, manager } = await boot({ emailPassword: false });
140+
expect(passwordOn(manager)).toBe(false);
141+
// The stored-value read is unchanged: nothing is stored, so the manifest default.
142+
expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'default' });
143+
144+
const { page, banner } = await readPage(settings);
145+
expect(page.values.email_password_enabled).toMatchObject({ value: true, source: 'default' });
146+
expect(banner).toMatchObject({
147+
type: 'info_banner',
148+
label: AUTH_LIVE_STATUS_COPY.en.declaredOffLabel,
149+
bannerText: AUTH_LIVE_STATUS_COPY.en.declaredOffText,
150+
bannerSeverity: 'info',
151+
});
152+
// It heads the page.
153+
expect(page.manifest.specifiers[0].id).toBe(SETTINGS_LIVE_STATUS_BANNER_ID);
154+
155+
// In the caller's language.
156+
const zh = await readPage(settings, { 'accept-language': 'zh-CN' });
157+
expect(zh.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY['zh-CN'].declaredOffLabel });
158+
});
159+
160+
it('CONTROL: declared on with nothing stored, the page states nothing', async () => {
161+
const { settings, manager } = await boot();
162+
expect(passwordOn(manager)).toBe(true);
163+
const { page, banner } = await readPage(settings);
164+
expect(page.values.email_password_enabled).toMatchObject({ value: true, source: 'default' });
165+
expect(banner).toBeUndefined();
166+
});
167+
168+
it('a stored value still wins where it is applied, and the page states nothing', async () => {
169+
const off = await boot({ emailPassword: false });
170+
await off.settings.setMany('auth', { email_password_enabled: true });
171+
await vi.waitFor(() => expect(passwordOn(off.manager)).toBe(true));
172+
const savedOn = await readPage(off.settings);
173+
expect(savedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' });
174+
expect(savedOn.banner).toBeUndefined();
175+
176+
// Saved off over a declared on; the host's sign-in handoff keeps a way in, so the sign-in floor lets it through.
177+
const on = await boot({ hostSignInHandoff: true });
178+
expect(passwordOn(on.manager)).toBe(true);
179+
await on.settings.setMany('auth', { email_password_enabled: false });
180+
await vi.waitFor(() => expect(passwordOn(on.manager)).toBe(false));
181+
const savedOff = await readPage(on.settings);
182+
expect(savedOff.page.values.email_password_enabled).toMatchObject({ value: false, source: 'global' });
183+
expect(savedOff.banner).toBeUndefined();
184+
});
185+
186+
it('a cloud-managed runtime that holds it off says so: info with nothing stored, warning over a stored on', async () => {
187+
setManaged(true);
188+
const { settings, manager } = await boot({ emailPassword: false });
189+
const nothingStored = await readPage(settings);
190+
expect(nothingStored.banner).toMatchObject({
191+
label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel,
192+
bannerText: AUTH_LIVE_STATUS_COPY.en.managedOffText,
193+
bannerSeverity: 'info',
194+
});
195+
196+
// A re-save of the default is stored and not applied (the settings pass's managed hold).
197+
await settings.setMany('auth', { email_password_enabled: true });
198+
await settle();
199+
expect(passwordOn(manager)).toBe(false);
200+
const storedOn = await readPage(settings);
201+
expect(storedOn.page.values.email_password_enabled).toMatchObject({ value: true, source: 'global' });
202+
expect(storedOn.banner).toMatchObject({ label: AUTH_LIVE_STATUS_COPY.en.managedOffLabel, bannerSeverity: 'warning' });
203+
});
204+
});
205+
206+
describe('describeEmailPasswordLiveStatus', () => {
207+
it('states nothing while the switch and the running value agree', () => {
208+
for (const running of [true, false]) {
209+
expect(describeEmailPasswordLiveStatus({
210+
running, shown: { value: running, source: 'global' }, heldOffByHost: false,
211+
})).toBeUndefined();
212+
}
213+
expect(describeEmailPasswordLiveStatus({ running: true, shown: undefined, heldOffByHost: false })).toBeUndefined();
214+
});
215+
216+
it('any other disagreement is stated as a warning naming what runs', () => {
217+
expect(describeEmailPasswordLiveStatus({
218+
running: true, shown: { value: false, source: 'global' }, heldOffByHost: false,
219+
})).toEqual({
220+
label: AUTH_LIVE_STATUS_COPY.en.differsLabel(true),
221+
bannerText: AUTH_LIVE_STATUS_COPY.en.differsText,
222+
bannerSeverity: 'warning',
223+
});
224+
// Off by something other than the declaration (stored on, not applied, self-hosted).
225+
expect(describeEmailPasswordLiveStatus({
226+
running: false, shown: { value: true, source: 'global' }, heldOffByHost: false,
227+
})).toMatchObject({ label: AUTH_LIVE_STATUS_COPY.en.differsLabel(false), bannerSeverity: 'warning' });
228+
});
229+
230+
it('every language on the copy table carries every sentence', () => {
231+
const keys = Object.keys(AUTH_LIVE_STATUS_COPY.en).sort();
232+
for (const [locale, copy] of Object.entries(AUTH_LIVE_STATUS_COPY)) {
233+
expect(Object.keys(copy).sort(), locale).toEqual(keys);
234+
for (const [key, value] of Object.entries(copy)) {
235+
const text = typeof value === 'function' ? value(false) : value;
236+
expect(typeof text === 'string' && text.length > 0, `${locale}.${key}`).toBe(true);
237+
}
238+
}
239+
});
240+
});

0 commit comments

Comments
 (0)