Compare commits

...
Author SHA1 Message Date
jason.woltje 29daa4c4bf test(webui): settings-backend-a3 proof: the settings-review fixture's accounts answer carries the providers list, since with no list the Model setup page shows no sign-in button (F10 clicked it) (#1873, lane settings-backend-a3) 2026-11-20 02:21:46 -06:00
jason.woltje c8db3665cf fix(bus): settings-backend-a3 review: a provider list entry counts only with what its door needs, a sign-in host or a key base URL, so one missing it is refused provider-not-allowed before any proxy call (no sign-in opened at the proxy that the page cannot cancel), and a key group with no base URL is no provider's (P3-1) (#1873, lane settings-backend-a3) 2026-11-20 02:21:46 -06:00
jason.woltje f2c262cf40 feat(model-proxy,bus,webui): settings-backend A3: the provider list comes from the cliproxy plugin's PROVIDERS (id, label, sign-in kind, the sign-in host for a subscription, the base URL for the key provider); the management client's oauthStart, the bus proxy page's names, login allow list, sign-in host check and key allow list read it, with the same refusals (proxy-client-invalid, provider-not-allowed); the setup status and the accounts answer carry providers as id, label and sign-in kind only; the Model setup page builds the provider select and its help text from them, and with no list, an empty one or a failed read it shows no select and says the providers could not be read; an architecture test holds that no provider id, sign-in host or key base URL is written out in client.mjs, proxy-page.mjs or display.js (#1873, lane settings-backend-a3) 2026-11-20 02:21:45 -06:00
13 changed files with 368 additions and 45 deletions

No files matched your search

+27 -19
View File
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { sha256, refuse } from '../../model-proxy/src/common.mjs';
import { PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
import { ZAI_URL, MODEL_ID } from '../../plugins/model-provider/cliproxy/index.mjs';
import { MODEL_ID, PROVIDERS, publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
export { PROXY_PAGE_VERBS, PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
function fields(args, names) {
@@ -13,11 +13,16 @@ const priorityOk = n => Number.isInteger(n) && n >= -1000 && n <= 1000;
const identifier = x => typeof x === 'string' && x.length > 0 && x.length <= 512;
const stateOk = x => typeof x === 'string' && /^[a-zA-Z0-9_-]{1,512}$/.test(x);
const keyId = value => sha256(value).slice(0, 12);
const providerName = provider => ({ claude: 'Claude', codex: 'Codex', 'z.ai': 'z.ai', other: 'Other' })[provider];
// #1873 settings-backend-a3: provider names, the login allow list and the key allow list all come
// from the plugin's PROVIDERS. An account the list does not name reads Other.
// An entry counts only with what its door needs: a sign-in host, or a key base URL.
const usable = p => p.signIn === 'oauth' ? typeof p.signInHost === 'string' : p.signIn === 'apikey' && typeof p.baseUrl === 'string';
const listed = (providers, id, signIn) => providers.find(p => p.id === id && p.signIn === signIn && usable(p)) ?? null;
const providerName = (providers, provider) => providers.find(p => p.id === provider)?.label ?? 'Other';
// Credential labels/emails and group names are arbitrary upstream strings. A stable
// generated display name provides identification without reflecting a misplaced token.
function view(id, provider, status, priority) {
return { accountId: keyId(id), provider, displayName: `${providerName(provider)} account ${keyId(id)}`,
function view(providers, id, provider, status, priority) {
return { accountId: keyId(id), provider, displayName: `${providerName(providers, provider)} account ${keyId(id)}`,
status, priority: priorityOk(priority) ? priority : 0 };
}
// #1873 chat-fail F3: one plain line under an account the proxy reports as not working, with
@@ -57,11 +62,12 @@ function accountReason(row, now) {
return NO_REASON;
}
export class ProxyPage {
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #pending = new Map(); #writes = Promise.resolve();
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null }) {
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #providers; #pending = new Map(); #writes = Promise.resolve();
// providers: the plugin's PROVIDERS; a test passes a copy with one taken out.
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null, providers = PROVIDERS }) {
if (!client || !/^[a-zA-Z0-9_-]{1,64}$/.test(instanceTag) || typeof keyRecords !== 'function' || typeof now !== 'function'
|| typeof onChange !== 'function' || !Number.isSafeInteger(loginTimeoutSeconds) || loginTimeoutSeconds <= 0) throw new TypeError('invalid proxy page settings');
this.#lock = lock; this.#org = org;
|| typeof onChange !== 'function' || !Number.isSafeInteger(loginTimeoutSeconds) || loginTimeoutSeconds <= 0 || !Array.isArray(providers)) throw new TypeError('invalid proxy page settings');
this.#lock = lock; this.#org = org; this.#providers = providers;
this.#client = client; this.#tag = instanceTag; this.#records = keyRecords; this.#now = now; this.#timeout = loginTimeoutSeconds * 1000; this.#onChange = onChange;
}
// Serializes read-modify-write provider config within the bus. P2 owns the
@@ -84,10 +90,10 @@ export class ProxyPage {
const rows = [];
for (const row of response.files) {
if (!identifier(row?.id) || !identifier(row?.name)) continue;
const provider = ['claude', 'codex'].includes(row.provider) ? row.provider : 'other';
const provider = listed(this.#providers, row.provider, 'oauth') ? row.provider : 'other';
const status = row.disabled === true ? 'disabled' : row.unavailable === true ? 'unavailable'
: ['ready', 'active', 'error', 'disabled', 'unavailable'].includes(row.status) ? row.status : 'unknown';
rows.push({ ...view(row.id, provider, status, row.priority), source: 'oauth', name: row.name,
rows.push({ ...view(this.#providers, row.id, provider, status, row.priority), source: 'oauth', name: row.name,
...(['unavailable', 'error'].includes(status) ? { reason: accountReason(row, this.#now()) } : {}) });
}
for (const [groupIndex, group] of groups.entries()) {
@@ -95,18 +101,18 @@ export class ProxyPage {
for (const [keyIndex, key] of group.keys.entries()) {
// auth_index is generated by the proxy. Never fall back to hashing api-key.
if (!identifier(key?.auth_index)) continue;
const provider = group['base-url'] === ZAI_URL ? 'z.ai' : 'other';
const provider = this.#providers.find(p => p.signIn === 'apikey' && usable(p) && p.baseUrl === group['base-url'])?.id ?? 'other';
const status = key.disabled === true || group.disabled === true ? 'disabled' : 'active';
const configured = group.models ?? [];
if (!Array.isArray(configured) || configured.length > 32 || configured.some(m => !m || typeof (m.alias || m.name) !== 'string' || !MODEL_ID.test(m.alias || m.name))) refuse('proxy-down');
rows.push({ ...view(key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
rows.push({ ...view(this.#providers, key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
}
}
return { rows, groups };
}
#public(row) {
const { accountId, provider, displayName, status, priority } = row;
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && provider === 'z.ai' ? { models: row.models } : {}),
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && listed(this.#providers, provider, 'apikey') ? { models: row.models } : {}),
...(typeof row.reason === 'string' ? { reason: row.reason } : {}) };
}
#session(state, scope, { reportTimeout = false } = {}) {
@@ -131,17 +137,18 @@ export class ProxyPage {
async #request(verb, args, scope) {
if (verb === 'proxy.accounts') {
fields(args, []);
return { accounts: (await this.#accounts()).rows.map(row => this.#public(row)) };
// The provider list rides along for the page's select: id, label and sign-in kind only.
return { accounts: (await this.#accounts()).rows.map(row => this.#public(row)), providers: publicProviders(this.#providers) };
}
if (verb === 'proxy.login.start') {
fields(args, ['provider']);
if (!['claude', 'codex'].includes(args.provider)) refuse('provider-not-allowed');
const oauth = listed(this.#providers, args.provider, 'oauth');
if (!oauth) refuse('provider-not-allowed');
for (const [state, value] of this.#pending) if (value.expires <= this.#now()) this.#pending.delete(state);
if (this.#pending.size >= 128) refuse('proxy-down');
const answer = await (this.#lock ? this.#write(() => this.#client.oauthStart(args.provider)) : this.#client.oauthStart(args.provider));
let url; try { url = new URL(answer.url); } catch { refuse('proxy-down'); }
const host = args.provider === 'claude' ? 'claude.ai' : 'auth.openai.com';
if (url.protocol !== 'https:' || url.hostname !== host || url.username || url.password || url.port
if (url.protocol !== 'https:' || typeof oauth.signInHost !== 'string' || url.hostname !== oauth.signInHost || url.username || url.password || url.port
|| url.href.length > 8192 || !stateOk(answer.state) || url.searchParams.getAll('state').length !== 1
|| url.searchParams.get('state') !== answer.state || this.#pending.has(answer.state)) refuse('proxy-down');
this.#pending.set(answer.state, { business: scope.business, human: scope.human, expires: this.#now() + this.#timeout });
@@ -186,12 +193,13 @@ export class ProxyPage {
}
if (verb === 'proxy.apikey.add') {
fields(args, ['provider', 'key']);
if (args.provider !== 'z.ai') refuse('provider-not-allowed');
const keyed = listed(this.#providers, args.provider, 'apikey');
if (!keyed) refuse('provider-not-allowed');
if (typeof args.key !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(args.key)) refuse('apikey-invalid');
return this.#write(async () => {
const groups = await this.#client.getUpstreamGroups();
if (!Array.isArray(groups)) refuse('proxy-down');
const group = { name: `mosaic-zai-${randomBytes(6).toString('hex')}`, 'base-url': ZAI_URL,
const group = { name: `mosaic-${keyed.id.replace(/[^a-z0-9]/g, '')}-${randomBytes(6).toString('hex')}`, 'base-url': keyed.baseUrl,
priority: 0, keys: [{ 'api-key': args.key }] };
if (this.#lock && !isDeepStrictEqual(await this.#client.getUpstreamGroups(), groups)) refuse('proxy-down');
this.#beforeMutation('proxy.apikey.add');
@@ -4,6 +4,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { fakeManagement } from './proxy-page-fixture.mjs';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const id = value => createHash('sha256').update(value).digest('hex').slice(0, 12);
const oauth = extra => ({ id: 'oauth-one.json', name: 'oauth-one.json', provider: 'claude', label: 'p4-private-label',
email: 'p4-private-email', token: 'p4-private-token', status: 'ready', priority: 3, ...extra });
@@ -11,7 +12,9 @@ test('accounts have exactly the allowlisted public fields, id from credential id
const s = await fakeManagement(t, { files: [oauth()] });
const result = await s.call('proxy.accounts');
assert.deepEqual(result, { accounts: [{ accountId: id('oauth-one.json'), provider: 'claude',
displayName: `Claude account ${id('oauth-one.json')}`, status: 'ready', priority: 3 }] });
displayName: `Claude account ${id('oauth-one.json')}`, status: 'ready', priority: 3 }],
// settings-backend-a3: the provider list rides along, id, label and sign-in kind only.
providers: PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })) });
for (const value of ['p4-private-label', 'p4-private-email', 'p4-private-token']) {
assert.equal(JSON.stringify(result).includes(value), false);
assert.notEqual(result.accounts[0].accountId, id(value));
@@ -0,0 +1,106 @@
// #1873 settings-backend-a3: the proxy page's provider names, login allow list, sign-in host and key
// allow list all come from the plugin's PROVIDERS. A provider a test copy of the list leaves out is
// refused at each door with the same code as before; one a copy adds is let through. The accounts
// answer carries the list as id, label and sign-in kind only.
import test from 'node:test';
import assert from 'node:assert/strict';
import { ProxyPage } from '../src/proxy-page.mjs';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const owner = { business: 'demo', human: 'owner' };
function setup(options = {}) {
const calls = [], state = { files: [], groups: [] };
const client = Object.fromEntries(['getCredentials', 'oauthStart', 'oauthCallback', 'oauthStatus', 'oauthCancel', 'getUpstreamGroups', 'putUpstreamGroups'].map(name => [name, async (...args) => {
calls.push([name, ...args]);
if (name === 'oauthStart') return { status: 'ok', state: `s-${calls.length}`, url: `https://${options.hosts?.[args[0]] ?? 'nowhere.invalid'}/oauth/authorize?state=s-${calls.length}` };
if (name === 'getCredentials') return { files: state.files };
if (name === 'getUpstreamGroups') return structuredClone(state.groups);
if (name === 'putUpstreamGroups') { state.groups = args[0].map((g, i) => ({ ...g, keys: g.keys.map((k, j) => ({ ...k, auth_index: `idx-${i}-${j}` })) })); return { status: 'ok' }; }
return { status: 'ok' };
}]));
const p = new ProxyPage({ client, instanceTag: 'fixture', ...(options.providers ? { providers: options.providers } : {}) });
return { calls, state, call: (verb, args = {}) => p.request(verb, args, owner) };
}
const hosts = Object.fromEntries(PROVIDERS.filter(p => p.signIn === 'oauth').map(p => [p.id, p.signInHost]));
const door = p => p.signIn === 'oauth' ? ['proxy.login.start', { provider: p.id }] : ['proxy.apikey.add', { provider: p.id, key: 'fixture-key' }];
const otherDoor = p => p.signIn === 'oauth' ? ['proxy.apikey.add', { provider: p.id, key: 'fixture-key' }] : ['proxy.login.start', { provider: p.id }];
test('a3: each provider in PROVIDERS passes its own door and is refused at the other with provider-not-allowed', async () => {
assert.ok(PROVIDERS.some(p => p.signIn === 'oauth') && PROVIDERS.some(p => p.signIn === 'apikey'));
for (const p of PROVIDERS) {
const s = setup({ hosts });
const answer = await s.call(...door(p));
if (p.signIn === 'oauth') assert.equal(new URL(answer.url).hostname, p.signInHost, p.id);
else { assert.deepEqual(answer, { added: true }); assert.equal(s.state.groups.at(-1)['base-url'], p.baseUrl); }
const before = s.calls.length;
await assert.rejects(s.call(...otherDoor(p)), { code: 'provider-not-allowed' }, p.id);
assert.equal(s.calls.length, before, `${p.id}: a refusal reaches no proxy call`);
}
for (const [verb, args] of [['proxy.login.start', { provider: 'other' }], ['proxy.apikey.add', { provider: 'other', key: 'fixture-key' }]]) {
const s = setup({ hosts });
await assert.rejects(s.call(verb, args), { code: 'provider-not-allowed' }); assert.equal(s.calls.length, 0);
}
});
test('a3: a provider taken out of a test copy of the list is refused at its door, reads Other and leaves the providers answer', async () => {
for (const gone of PROVIDERS) {
const s = setup({ hosts, providers: PROVIDERS.filter(p => p !== gone) });
await assert.rejects(s.call(...door(gone)), { code: 'provider-not-allowed' }, gone.id);
assert.equal(s.calls.length, 0, `${gone.id}: refused before any proxy call`);
if (gone.signIn === 'oauth') s.state.files = [{ id: 'one.json', name: 'one.json', provider: gone.id, status: 'ready' }];
else s.state.groups = [{ name: 'g', 'base-url': gone.baseUrl, keys: [{ auth_index: 'idx-0-0' }], models: [{ name: 'm1' }] }];
const answer = await s.call('proxy.accounts');
assert.equal(answer.accounts.length, 1);
assert.equal(answer.accounts[0].provider, 'other', gone.id);
assert.match(answer.accounts[0].displayName, /^Other account /);
assert.equal(Object.hasOwn(answer.accounts[0], 'models'), false, `${gone.id}: an unlisted group shows no models`);
assert.deepEqual(answer.providers.map(p => p.id), PROVIDERS.filter(p => p !== gone).map(p => p.id));
}
});
test('a3: a provider a test copy adds is let through: key group from its base URL, sign-in on its host, name from its label', async () => {
const extra = [{ id: 'fixture.ai', label: 'Fixture AI', signIn: 'apikey', baseUrl: 'https://api.fixture.invalid/v1' },
{ id: 'fixture-sso', label: 'Fixture SSO', signIn: 'oauth', signInHost: 'sso.fixture.invalid' }];
const s = setup({ providers: [...PROVIDERS, ...extra], hosts: { ...hosts, 'fixture-sso': 'sso.fixture.invalid' } });
assert.deepEqual(await s.call('proxy.apikey.add', { provider: 'fixture.ai', key: 'fixture-key' }), { added: true });
assert.equal(s.state.groups[0]['base-url'], 'https://api.fixture.invalid/v1');
assert.match(s.state.groups[0].name, /^mosaic-fixtureai-[0-9a-f]{12}$/);
assert.equal(new URL((await s.call('proxy.login.start', { provider: 'fixture-sso' })).url).hostname, 'sso.fixture.invalid');
s.state.files = [{ id: 'sso.json', name: 'sso.json', provider: 'fixture-sso', status: 'ready' }];
const { accounts } = await s.call('proxy.accounts');
assert.deepEqual(accounts.map(a => [a.provider, a.displayName.replace(/ [0-9a-f]{12}$/, '')]), [['fixture-sso', 'Fixture SSO account'], ['fixture.ai', 'Fixture AI account']]);
assert.deepEqual(accounts[1].models, []);
});
test('a3: the sign-in address must be on the host the list names for that provider', async () => {
const codex = PROVIDERS.find(p => p.id === 'codex');
const moved = PROVIDERS.map(p => p === codex ? { ...p, signInHost: 'elsewhere.invalid' } : p);
const s = setup({ hosts, providers: moved });
await assert.rejects(s.call('proxy.login.start', { provider: 'codex' }), { code: 'proxy-down' });
const t = setup({ hosts: { ...hosts, codex: 'elsewhere.invalid' }, providers: moved });
assert.equal(new URL((await t.call('proxy.login.start', { provider: 'codex' })).url).hostname, 'elsewhere.invalid');
});
test('a3: the accounts answer carries the providers as id, label and sign-in kind only, no URL, host or key', async () => {
const s = setup({ hosts });
await s.call('proxy.apikey.add', { provider: 'z.ai', key: 'a3-canary-key-value' });
const answer = await s.call('proxy.accounts');
assert.deepEqual(answer.providers, PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })));
for (const p of answer.providers) assert.deepEqual(Object.keys(p).sort(), ['id', 'label', 'signIn']);
const text = JSON.stringify(answer.providers);
for (const word of ['a3-canary-key-value', 'https://', 'api.z.ai', 'claude.ai', 'auth.openai.com', 'baseUrl', 'signInHost']) assert.equal(text.includes(word), false, word);
});
// Review P3-1: an entry missing what its door needs is refused before any proxy call, so no sign-in
// is opened at the proxy that the page could not cancel; a key group with no base URL is no provider's.
test('a3: an entry with no sign-in host or no key base URL is refused before any proxy call and names no group', async () => {
const bare = [{ id: 'nohost', label: 'No Host', signIn: 'oauth' }, { id: 'nourl', label: 'No URL', signIn: 'apikey' }];
const s = setup({ providers: [...PROVIDERS, ...bare], hosts: { ...hosts, nohost: 'nohost.invalid' } });
await assert.rejects(s.call('proxy.login.start', { provider: 'nohost' }), { code: 'provider-not-allowed' });
await assert.rejects(s.call('proxy.apikey.add', { provider: 'nourl', key: 'fixture-key' }), { code: 'provider-not-allowed' });
assert.equal(s.calls.length, 0);
s.state.groups = [{ name: 'g', keys: [{ auth_index: 'idx-0-0' }], models: [{ name: 'm1' }] }];
s.state.files = [{ id: 'one.json', name: 'one.json', provider: 'nohost', status: 'ready' }];
const { accounts } = await s.call('proxy.accounts');
assert.deepEqual(accounts.map(a => a.provider), ['other', 'other']);
assert.equal(accounts.some(a => Object.hasOwn(a, 'models')), false);
});
+4 -1
View File
@@ -11,6 +11,7 @@ import { releaseState, initState, fenceState, initLockStatus, clearInitLock, app
import { secretValues } from './redact.mjs';
import { discoverModules, hasModule } from '../../plugins/src/loader.mjs';
import { readPluginLock } from '../../plugins/src/pinned.mjs';
import { PROVIDERS, publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
const failure = code => Object.assign(new Error(code), { code });
@@ -79,7 +80,7 @@ const isoTime = value => (typeof value === 'string' && /^[0-9]{4}-[0-9]{2}-[0-9]
// reads it ({document, revision}), read only. `harnesses()` lists the installed harness programs.
// `rootAgents()` reads the root agent file (loadRootAgents); with none given, or one that throws,
// no organization that has the program on is written (unreadable).
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN }) {
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN, providers = PROVIDERS }) {
const port = () => { try { return initState(configDir, dataRoot).settings?.port ?? null; } catch { return null; } };
const control = unit ?? createUnitControl({ instance, unitDir, port, env });
let job = { state: 'idle', step: null, receipt: null, error: null };
@@ -273,6 +274,8 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
initLock: lock,
fetch: fetchJob,
restart: restarted ? { confirmed: true, observedAt: restarted.observedAt, pid: restarted.after.pid } : null,
// #1873 settings-backend-a3: the page's provider select, from the plugin. Id, label and sign-in kind only.
providers: publicProviders(providers),
busy,
receipts: recentReceipts(dataRoot),
organizations,
+7 -5
View File
@@ -3,17 +3,19 @@ import http from 'node:http';
import { ProxyError, refuse, sha256, regularBytes, validManagementKey } from './common.mjs';
import { lstatSync } from 'node:fs';
import { join } from 'node:path';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const KEY_PATH = '/v8/management/config/access/api-keys';
const validKeys = value => Array.isArray(value) && value.length <= 100000 && value.every(k => typeof k === 'string' && k.length > 0 && k.length <= 4096 && !/[\r\n\x00]/.test(k));
export class ManagementClient {
#base; #key; #receipt; #timeout;
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000 }) {
#base; #key; #receipt; #timeout; #providers;
// providers: the plugin's PROVIDERS; a test passes a copy with one taken out.
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000, providers = PROVIDERS }) {
let u; try { u = new URL(baseUrl); } catch { refuse('proxy-client-invalid'); }
if (u.protocol !== 'http:' || u.hostname !== '127.0.0.1' || !u.port || Number(u.port) < 1024 || u.port === '8317'
|| u.username || u.password || u.pathname !== '/' || u.search || u.hash
|| !validManagementKey(key)
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0) refuse('proxy-client-invalid');
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout;
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0 || !Array.isArray(providers)) refuse('proxy-client-invalid');
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout; this.#providers = providers;
}
#request(method, endpoint, payload, onStatus) {
// node:http addresses the fixed numeric loopback directly. An ambient fetch
@@ -107,7 +109,7 @@ export class ManagementClient {
}
patchCredential(name, priority) { return this.#page('PATCH', '/v8/management/credentials/fields', { name, priority }, 200); }
oauthStart(provider) {
if (!['claude', 'codex'].includes(provider)) refuse('proxy-client-invalid');
if (!this.#providers.some(p => p.id === provider && p.signIn === 'oauth')) refuse('proxy-client-invalid');
return this.#page('GET', `/v8/management/oauth/auth-url?provider=${provider}`);
}
oauthCallback(redirect_url) { return this.#page('POST', '/v8/management/oauth/callback', { redirect_url }); }
@@ -0,0 +1,73 @@
// #1873 settings-backend-a3: the management client's sign-in allow list and the setup status's
// provider field both come from the plugin's PROVIDERS. oauthStart refuses the key provider and any
// provider a test copy of the list leaves out, before any request. The status field carries id,
// label and sign-in kind only: no base URL, no sign-in host, no key text.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { ManagementClient } from '../src/client.mjs';
import { createProxyAdmin } from '../src/admin-control.mjs';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const code = name => error => error.code === name;
async function server(t) {
const asked = [];
const s = http.createServer((q, r) => { asked.push(new URL(q.url, 'http://x').searchParams.get('provider')); r.setHeader('content-type', 'application/json'); r.end(JSON.stringify({ status: 'ok', state: 's', url: 'https://claude.ai/x?state=s' })); });
await new Promise(r => s.listen(0, '127.0.0.1', r)); t.after(() => new Promise(r => s.close(r)));
return { asked, baseUrl: `http://127.0.0.1:${s.address().port}` };
}
test('a3: oauthStart asks the proxy for each sign-in provider in PROVIDERS and refuses the key provider before any request', async t => {
const { asked, baseUrl } = await server(t);
const c = new ManagementClient({ baseUrl, key: 'a3-management' });
for (const p of PROVIDERS.filter(p => p.signIn === 'oauth')) await c.oauthStart(p.id);
assert.deepEqual(asked, PROVIDERS.filter(p => p.signIn === 'oauth').map(p => p.id));
const keyed = PROVIDERS.filter(p => p.signIn === 'apikey');
assert.ok(keyed.length > 0);
for (const p of keyed) await assert.rejects(async () => c.oauthStart(p.id), code('proxy-client-invalid'), p.id);
for (const id of ['other', '', 'claude&x=1', undefined]) await assert.rejects(async () => c.oauthStart(id), code('proxy-client-invalid'));
assert.equal(asked.length, PROVIDERS.filter(p => p.signIn === 'oauth').length, 'no refused provider reached the proxy');
});
test('a3: oauthStart refuses a sign-in provider a test copy of the list leaves out, and asks for one it adds', async t => {
const { asked, baseUrl } = await server(t);
for (const gone of PROVIDERS.filter(p => p.signIn === 'oauth')) {
const c = new ManagementClient({ baseUrl, key: 'a3-management', providers: PROVIDERS.filter(p => p !== gone) });
await assert.rejects(async () => c.oauthStart(gone.id), code('proxy-client-invalid'), gone.id);
}
assert.deepEqual(asked, []);
const c = new ManagementClient({ baseUrl, key: 'a3-management', providers: [...PROVIDERS, { id: 'fixture-sso', label: 'Fixture SSO', signIn: 'oauth', signInHost: 'sso.fixture.invalid' }] });
await c.oauthStart('fixture-sso');
assert.deepEqual(asked, ['fixture-sso']);
assert.throws(() => new ManagementClient({ baseUrl, key: 'a3-management', providers: null }), code('proxy-client-invalid'));
});
function admin(t, extra = {}) {
const root = fs.mkdtempSync(join(tmpdir(), 'a3-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const unit = { unit: 'mosaic-proxy-a3.service', status: async () => ({ unit: 'mosaic-proxy-a3.service', installed: false, active: 'inactive', healthy: false }) };
return createProxyAdmin({ dataRoot, configDir, unit, buses: async () => ({ stopped: true, running: [] }), fetch: async () => ({}), now: () => new Date(0),
orgs: async () => [], harnesses: () => [], rootAgents: () => ({ state: 'absent', agents: {}, assistant: null }), ...extra });
}
test('a3: the status lists the providers as id, label and sign-in kind only, in the plugin\'s order', async t => {
const status = await admin(t).status();
assert.deepEqual(status.providers, PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })));
for (const p of status.providers) assert.deepEqual(Object.keys(p).sort(), ['id', 'label', 'signIn']);
const text = JSON.stringify(status.providers);
for (const word of ['https://', 'api.z.ai', 'claude.ai', 'auth.openai.com', 'baseUrl', 'signInHost']) assert.equal(text.includes(word), false, word);
});
test('a3: the status field holds no key text, even from a list entry that carries a key, and a provider left out is gone', async t => {
const canary = 'a3-status-canary-key-0123456789';
const list = [...PROVIDERS.filter(p => p.id !== 'codex'), { id: 'fixture.ai', label: 'Fixture AI', signIn: 'apikey', baseUrl: `https://${canary}.invalid/`, key: canary, apiKey: canary }];
const status = await admin(t, { providers: list }).status();
assert.deepEqual(status.providers.map(p => p.id), ['claude', 'z.ai', 'fixture.ai']);
assert.equal(JSON.stringify(status.providers).includes(canary), false);
assert.equal(JSON.stringify(status).includes(canary), false);
});
@@ -1,6 +1,18 @@
// Provider configuration and transport declarations owned by the proxy module.
export const interfaceVersion = 1;
export const ZAI_URL = 'https://api.z.ai/api/anthropic';
// #1873 settings-backend-a3: the one list of providers an account can be added for. The bus proxy
// page, the management client and the Console's provider select all read it; a provider not here
// is refused. `id` is the value the page sends and an account row carries. An OAuth provider names
// the host its sign-in address must be on; the key provider names the base URL its key group uses.
// The setup status and the accounts read pass on only id, label and sign-in kind.
export const PROVIDERS = Object.freeze([
Object.freeze({ id: 'claude', label: 'Claude', signIn: 'oauth', signInHost: 'claude.ai' }),
Object.freeze({ id: 'codex', label: 'ChatGPT / Codex', signIn: 'oauth', signInHost: 'auth.openai.com' }),
Object.freeze({ id: 'z.ai', label: 'z.ai', signIn: 'apikey', baseUrl: ZAI_URL }),
]);
// What a page may see of the list: no URL, no host, nothing else.
export const publicProviders = (list = PROVIDERS) => list.map(({ id, label, signIn }) => ({ id, label, signIn }));
export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
const MODEL = MODEL_ID;
const MAX_MODELS = 10000;
+33 -12
View File
@@ -603,13 +603,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<details id="proxy-account-order"><summary>Account order</summary><div class="inside"><p class="small muted">Higher priority is used first. Credential values are never shown.</p><ul id="proxy-order" class="rows proxy-order"></ul></div></details>'
+ '<details id="proxy-offered"><summary>Models offered</summary><div class="inside" id="proxy-offered-list"></div></details>'
+ '<details id="proxy-add-box"><summary>Add an account</summary><div class="inside">'
+ '<form id="proxy-login-start" class="settings-form"><fieldset data-write disabled><div class="field"><label for="proxy-provider">Provider</label>'
+ '<select id="proxy-provider" name="provider"><option value="claude">Claude (subscription)</option><option value="codex">ChatGPT / Codex (subscription)</option><option value="z.ai">z.ai (API key)</option></select>'
+ '<p class="help small muted">Claude and ChatGPT / Codex: you sign in on the provider\'s site in a new tab. Nothing you type there comes to this page. z.ai: you paste an API key from your z.ai account.</p></div>'
+ '<div class="form-foot"><button type="submit" id="proxy-login-go">Sign in to Claude</button></div></fieldset></form>'
+ '<form id="proxy-apikey" class="settings-form" hidden><fieldset data-write disabled><div class="field"><label for="proxy-apikey-key" id="proxy-apikey-label">z.ai API key</label>'
+ '<form id="proxy-login-start" class="settings-form"><fieldset data-write disabled><div class="field"><label for="proxy-provider" hidden>Provider</label>'
// settings-backend-a3: the options and this help text come from the plugin's provider list (setProviders).
+ '<select id="proxy-provider" name="provider" hidden></select><p id="proxy-provider-help" class="help small muted">Reading providers…</p></div>'
+ '<div class="form-foot"><button type="submit" id="proxy-login-go" hidden>Sign in</button></div></fieldset></form>'
+ '<form id="proxy-apikey" class="settings-form" hidden><fieldset data-write disabled><div class="field"><label for="proxy-apikey-key" id="proxy-apikey-label">API key</label>'
+ '<input id="proxy-apikey-key" name="key" type="password" autocomplete="off" spellcheck="false" maxlength="4096" required>'
+ '<p class="help small muted">Mosaic checks it with z.ai, keeps it in your model service, and never shows it again.</p></div>'
+ '<p class="help small muted">Mosaic checks it with <span id="proxy-apikey-provider">the provider</span>, keeps it in your model service, and never shows it again.</p></div>'
+ '<div class="form-foot"><button type="submit">Check and add</button><button type="button" id="proxy-apikey-cancel">Cancel</button></div></fieldset><p id="proxy-apikey-message" role="status"></p></form>'
+ '</div></details>'
+ '<div id="proxy-signin" hidden><ol id="proxy-signin-progress" class="progress" aria-label="Sign-in progress"></ol>'
@@ -687,7 +687,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
const cell = value => { const td = document.createElement('td'); td.textContent = value ?? '—'; return td; };
const el = (tag, text, className) => { const e = document.createElement(tag); if (text !== undefined) e.textContent = text; if (className) e.className = className; return e; };
// The provider select is this page's one list of providers: rows and buttons take their names
// and kinds (subscription or API key) from its option labels.
// and kinds (subscription or API key) from its option labels. Its options come from the plugin's
// list (setProviders), read with the setup status for the instance owner, with the accounts for anyone else.
const providerSelect = $('proxy-provider');
const providerLabel = p => [...providerSelect.options].find(o => o.value === p)?.textContent ?? String(p ?? 'Unknown');
const providerShort = p => providerLabel(p).replace(/\s*\([^)]*\)$/, '');
@@ -801,6 +802,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
}
async function refresh() {
const accounts = await call('accounts');
if (!proxyAdmin) setProviders(accounts?.providers);
accountList = Array.isArray(accounts?.accounts) ? accounts.accounts : [];
accountsDown = null;
paintAccounts(); paintOrder();
@@ -847,9 +849,28 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
$('proxy-offered').addEventListener('toggle', () => { if ($('proxy-offered').open) readOffered(); });
// Add an account: the provider picks a sign-in or an API key.
function paintProvider() {
const p = providerSelect.value, apikey = keyed(p);
const go = $('proxy-login-go'); go.textContent = `Sign in to ${providerShort(p)}`; go.hidden = apikey;
const p = providerSelect.value, apikey = Boolean(p) && keyed(p);
const go = $('proxy-login-go'); go.textContent = `Sign in to ${providerShort(p)}`; go.hidden = apikey || !p;
$('proxy-apikey').hidden = !apikey; $('proxy-apikey-label').textContent = `${providerShort(p)} API key`;
$('proxy-apikey-provider').textContent = providerShort(p);
}
// settings-backend-a3: no list, or an empty one, leaves no select and one line saying so.
let providerKey = null;
function setProviders(list) {
const items = Array.isArray(list) ? list.filter(p => typeof p?.id === 'string' && p.id && typeof p.label === 'string' && ['oauth', 'apikey'].includes(p.signIn)) : [];
const key = JSON.stringify(items.map(p => [p.id, p.label, p.signIn]));
if (key === providerKey) return; providerKey = key;
const kept = providerSelect.value;
providerSelect.replaceChildren(...items.map(p => el('option', `${p.label} (${p.signIn === 'oauth' ? 'subscription' : 'API key'})`)));
items.forEach((p, i) => { providerSelect.options[i].value = p.id; });
if (items.some(p => p.id === kept)) providerSelect.value = kept;
providerSelect.hidden = !items.length; for (const label of providerSelect.labels) label.hidden = !items.length;
const oauth = items.filter(p => p.signIn === 'oauth').map(p => p.label);
$('proxy-provider-help').textContent = !items.length ? 'The providers could not be read, so no account can be added here.'
: [oauth.length ? `${new Intl.ListFormat('en').format(oauth)}: you sign in on the provider's site in a new tab. Nothing you type there comes to this page.` : '',
...items.filter(p => p.signIn === 'apikey').map(p => `${p.label}: you paste an API key from your ${p.label} account.`)].filter(Boolean).join(' ');
paintProvider();
if (accountList) { paintAccounts(); paintOrder(); }
}
providerSelect.addEventListener('change', paintProvider);
function paintSignin() {
@@ -1669,8 +1690,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
// True once the answer is painted, so a caller can say the list on the page is the new one.
async function load() {
if (!enabled || loading) return false; loading = true; let painted = false;
try { state = await admin('status'); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.init.initialized) await accountsReady(); }
catch (error) { say(error.message, 'error'); }
try { state = await admin('status'); setProviders(state.providers); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.init.initialized) await accountsReady(); }
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); }
finally { loading = false; }
return painted;
}
@@ -1786,7 +1807,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
if (proxyAdmin) { root.querySelectorAll('[data-admin]').forEach(part => { part.hidden = false; }); setup.start(config); }
paintAccountCard();
return refresh();
}).then(() => message('')).catch(error => { message(error.message);
}).then(() => message('')).catch(error => { message(error.message); if (!proxyAdmin && providerKey === null) setProviders(null);
// #1873: on the setup page a stopped proxy hides the account parts like an unconfigured one,
// and the setup load brings them back once the service answers.
// Any failed read hides them, not only proxy-down: a proxy that is initialized but not yet answering
@@ -10,3 +10,21 @@ test('Console production module graph cannot import the model-proxy client', asy
platform: 'node', format: 'esm', splitting: true, outdir: '/unused-proxy-architecture', write: false, metafile: true, logLevel: 'silent' });
assert.equal(Object.keys(result.metafile.inputs).some(file => file.endsWith('/model-proxy/src/client.mjs')), false);
});
// #1873 settings-backend-a3: the provider list lives in the cliproxy plugin's PROVIDERS. The
// management client, the bus proxy page and the settings page read it; none of them writes the
// provider ids, sign-in hosts or key base URL out as its own list.
test('a3: no provider id, sign-in host or key base URL is written out in client.mjs, proxy-page.mjs or display.js', async () => {
const { readFileSync } = await import('node:fs');
const { PROVIDERS } = await import('../../plugins/model-provider/cliproxy/index.mjs');
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const words = PROVIDERS.flatMap(p => [p.id, p.signInHost, p.baseUrl]).filter(Boolean);
assert.ok(words.length >= PROVIDERS.length + 2);
const quoted = new RegExp(`['"\`](${words.map(escape).join('|')})['"\`]`);
const keyed = new RegExp(`[{,]\\s*(${PROVIDERS.map(p => escape(p.id)).join('|')})\\s*:`);
for (const file of ['../../model-proxy/src/client.mjs', '../../bus/src/proxy-page.mjs', '../src/public/display.js']) {
const text = readFileSync(new URL(file, import.meta.url), 'utf8');
assert.equal(quoted.exec(text)?.[0], undefined, `${file} writes a provider value out`);
assert.equal(keyed.exec(text)?.[0], undefined, `${file} keys an object by provider id`);
assert.equal(/<option value=/.test(text), false, `${file} writes a provider option out`);
}
});
+37 -4
View File
@@ -6,8 +6,9 @@ import http from 'node:http';
import { readFileSync, existsSync } from 'node:fs';
import { resolve, extname } from 'node:path';
import { browser } from './browser.mjs';
async function setup(t, readonly = false, refusal = null) {
const state = { routes: [], loginStatus: 'wait', receivedKey: false, release: null, priority: 0, models: ['fixture-old'] };
import { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
async function setup(t, readonly = false, refusal = null, providers = publicProviders()) {
const state = { routes: [], loginStatus: 'wait', receivedKey: false, keyProvider: null, release: null, priority: 0, models: ['fixture-old'] };
const server = http.createServer(async (req, res) => {
const send = value => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(value)); };
if (req.url === '/api/config') return send({ send: !readonly, devOwner: true });
@@ -16,10 +17,10 @@ async function setup(t, readonly = false, refusal = null) {
if (refusal && req.url.endsWith(refusal)) { res.statusCode = 503; return send({ error: 'not-configured' }); }
const chunks = []; for await (const c of req) chunks.push(c);
const args = chunks.length ? JSON.parse(Buffer.concat(chunks)) : {};
if (req.url.endsWith('/accounts')) return send({ accounts: [{ accountId: 'a'.repeat(12), provider: 'claude', displayName: '<img src=x onerror="window.injected=true">', status: 'ready', priority: state.priority }, { accountId: 'c'.repeat(12), provider: 'z.ai', displayName: 'Fixture z.ai account', status: 'active', priority: 0, models: state.models }] });
if (req.url.endsWith('/accounts')) return send({ accounts: [{ accountId: 'a'.repeat(12), provider: 'claude', displayName: '<img src=x onerror="window.injected=true">', status: 'ready', priority: state.priority }, { accountId: 'c'.repeat(12), provider: 'z.ai', displayName: 'Fixture z.ai account', status: 'active', priority: 0, models: state.models }], ...(providers === 'none' ? {} : { providers }) });
if (req.url.endsWith('/keys')) return send({ keys: [{ keyId: 'b'.repeat(12), management: 'sentinel', agent: null, issuedAt: '2026-11-07T02:24:02.021Z', state: null }] });
if (req.url.endsWith('/apikey/add')) {
state.receivedKey = args.key === 'p4-browser-key';
state.receivedKey = args.key === 'p4-browser-key'; state.keyProvider = args.provider;
await new Promise(r => { state.release = r; }); return send({ added: true });
}
if (req.url.endsWith('/login/start')) return send({ url: 'https://claude.ai/oauth/authorize?state=p4-state', state: 'p4-state' });
@@ -113,3 +114,35 @@ test('settings-s4: Model setup shows no client keys table and reads no keys (des
assert.doesNotMatch(await b.evaluate('document.body.innerText'),/Client keys|Accounts and client keys/);
assert.equal(state.routes.some(r=>r.startsWith('/api/proxy/keys')),false);
});
// #1873 settings-backend-a3: anyone but the instance owner reads no setup status, so the select comes
// from the providers the accounts answer carries (the plugin's list as id, label and sign-in kind).
const selectNow = b => b.evaluate(`(() => { const s = document.querySelector("#proxy-provider"); return { options: [...s.options].map(o => [o.value, o.textContent]),
hidden: s.hidden, help: document.querySelector("#proxy-provider-help").textContent, go: document.querySelector("#proxy-login-go").hidden }; })()`);
test('settings-backend-a3: the select is built from the accounts answer\'s providers, and a key goes to the provider picked', { timeout: 60000 }, async t => {
const { b, state, wait } = await setup(t);
assert.deepEqual((await selectNow(b)).options, publicProviders().map(p => [p.id, `${p.label} (${p.signIn === 'oauth' ? 'subscription' : 'API key'})`]));
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li[data-account]")].map(li => [li.children[0].textContent, li.children[1].firstChild.textContent])'),
[['Claude', 'Subscription'], ['z.ai', 'API key']], 'a row takes its provider name and kind from the list');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); document.querySelector("#proxy-apikey input").value = "p4-browser-key"; document.querySelector("#proxy-apikey").requestSubmit(); return true; })()');
for (let n = 0; n < 100 && !state.release; n++) await new Promise(r => setTimeout(r, 20));
assert.equal(state.keyProvider, 'z.ai'); state.release();
await wait('document.querySelector("#proxy-message").textContent.includes("added")');
});
test('settings-backend-a3: a provider the accounts answer leaves out is not in the select', { timeout: 60000 }, async t => {
const { b } = await setup(t, false, null, publicProviders().filter(p => p.id !== 'claude'));
const now = await selectNow(b);
assert.deepEqual(now.options, [['codex', 'ChatGPT / Codex (subscription)'], ['z.ai', 'z.ai (API key)']]);
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to ChatGPT / Codex');
});
for (const [name, providers] of [['no providers', 'none'], ['an empty list', []]]) {
test(`settings-backend-a3: an accounts answer with ${name} shows no select and says the providers could not be read`, { timeout: 60000 }, async t => {
const { b } = await setup(t, false, null, providers);
assert.deepEqual(await selectNow(b), { options: [], hidden: true, help: 'The providers could not be read, so no account can be added here.', go: true });
assert.equal(await b.evaluate('document.querySelector("#proxy-apikey").hidden'), true);
});
}
test('settings-backend-a3: an accounts read that fails says the providers could not be read', { timeout: 60000 }, async t => {
const { b, wait } = await setup(t, false, '/accounts');
await wait('!/^Reading/.test(document.querySelector("#proxy-provider-help").textContent)');
assert.deepEqual(await selectNow(b), { options: [], hidden: true, help: 'The providers could not be read, so no account can be added here.', go: true });
});
@@ -5,6 +5,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { w15Fixture } from './w15-fixture.mjs';
import { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
const T = '2026-11-11T12:00:00.000Z';
const base = {
@@ -15,7 +16,7 @@ const base = {
fetch: { state: 'idle' }, restart: null, busy: null,
organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }],
ownProxy: { available: false, state: 'not built', reason: 'The configuration has one proxy per instance.' },
next: ['fetch'],
next: ['fetch'], providers: publicProviders(),
};
const fetched = { ...base, release: { ...base.release, fetched: true, verified: true }, next: ['init'] };
const fenced = { ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
@@ -1,12 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {w15Fixture} from './w15-fixture.mjs';
import {publicProviders} from '../../plugins/model-provider/cliproxy/index.mjs';
const rev='a'.repeat(64), long='a'.repeat(64);
const instances={revision:rev,launch:true,instances:{pm:{definition:'coder',launched:true,kept:false,running:['run-1'],protected:false,endProtected:false},[long]:{definition:'coder',launched:true,kept:false,running:[long],protected:false,endProtected:false}},definitions:{coder:{accepted:true,services:[]}},noHire:[],retired:[]};
const launch={revision:rev,models:{opus:{provider:'anthropic',model:'opus'}},limits:{},usage:{},assistants:{assistant:{definition:'assistant',vars:{},tracker:null}}};
const routes={revision:rev,harnesses:['claude-code','codex'],models:['opus'],levels:{'claude-code':['high','xhigh'],codex:['high','xhigh']},instances:{pm:{harness:'claude-code',model:'opus',thinking:'high'}}};
const scenario={'/api/config':{devOwner:true,send:true,decide:true,edit:true},'/api/settings':{launch,notifier:{binding:null}},'/api/bus/instances':{rows:[instances]},'/api/bus/routes':{rows:[routes]},'/api/bus/names':{rows:[{instance:'assistant',name:'Piper'}]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]},'/api/proxy/accounts':{accounts:[{accountId:'fixture',displayName:'Fixture',provider:'claude',status:'ready',priority:100}]},'/api/proxy/keys':{keys:[]}};
const scenario={'/api/config':{devOwner:true,send:true,decide:true,edit:true},'/api/settings':{launch,notifier:{binding:null}},'/api/bus/instances':{rows:[instances]},'/api/bus/routes':{rows:[routes]},'/api/bus/names':{rows:[{instance:'assistant',name:'Piper'}]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]},'/api/proxy/accounts':{accounts:[{accountId:'fixture',displayName:'Fixture',provider:'claude',status:'ready',priority:100}],providers:publicProviders()},'/api/proxy/keys':{keys:[]}};
async function page(t,section,width=1440,options={}) {
const x=await w15Fixture(t,{scenario}); const {b,f,wait}=x;
if(options.poll)await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{const original=setTimeout;window.setTimeout=(fn,ms,...args)=>{if(ms===10000)window.__pollRefresh=fn;return original(fn,ms,...args)}})()`});
@@ -7,6 +7,7 @@
// Part B is the single-business Console with every API answer explicit (w15-fixture.mjs).
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
@@ -57,7 +58,7 @@ async function orgFixture() {
// The instance owner's flags on /api/config and the model service status, by path suffix (display.js
// scopes some reads under /api/orgs/<id>/). Everything else is the real server.
const SERVICE_UP = { next: ['accounts'], init: { initialized: true, files: [] }, release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] };
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [], providers: publicProviders() };
const ownerStub = (service = SERVICE_UP, extra = {}) => `(() => {
const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service, accounts: [], routes: null, posts: {}, ...extra })}; window.__writes = [];
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
@@ -205,12 +206,53 @@ test('settings-s4 review N8: no paused mark while the service runs and only a fe
// ---- Part B: Model setup ---------------------------------------------------------------------
const T = '2026-11-11T12:00:00.000Z';
// #1873 settings-backend-a3: the provider select and its help text come from status.providers, the
// plugin's list as id, label and sign-in kind. No list, or an empty one, leaves no select and one line.
const selectNow = b => b.evaluate(`(() => { const s = document.querySelector("#proxy-provider"); return { options: [...s.options].map(o => [o.value, o.textContent]),
hidden: s.hidden, labels: [...s.labels].map(l => l.hidden), help: document.querySelector("#proxy-provider-help").textContent, go: document.querySelector("#proxy-login-go").hidden }; })()`);
const READING = '!/^Reading/.test(document.querySelector("#proxy-provider-help")?.textContent ?? "Reading")';
test('settings-backend-a3: the provider select\'s options are status.providers, with the help text built from them', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup' });
await wait(READING);
const now = await selectNow(b);
assert.deepEqual(now.options, SERVICE_UP.providers.map(p => [p.id, `${p.label} (${p.signIn === 'oauth' ? 'subscription' : 'API key'})`]));
assert.deepEqual([now.hidden, now.labels, now.go], [false, [false], false]);
assert.equal(now.help, "Claude and ChatGPT / Codex: you sign in on the provider's site in a new tab. Nothing you type there comes to this page. z.ai: you paste an API key from your z.ai account.");
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-apikey").hidden, document.querySelector("#proxy-login-go").hidden, document.querySelector("#proxy-apikey-label").textContent, document.querySelector("#proxy-apikey-provider").textContent]'),
[false, true, 'z.ai API key', 'z.ai']);
});
test('settings-backend-a3: a provider the status leaves out is gone from the select and its help text', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: { ...SERVICE_UP, providers: SERVICE_UP.providers.filter(p => p.id !== 'codex') } });
await wait(READING);
const now = await selectNow(b);
assert.deepEqual(now.options, [['claude', 'Claude (subscription)'], ['z.ai', 'z.ai (API key)']]);
assert.equal(now.help, "Claude: you sign in on the provider's site in a new tab. Nothing you type there comes to this page. z.ai: you paste an API key from your z.ai account.");
});
for (const [name, providers] of [['no providers field', undefined], ['an empty list', []], ['a list of nothing usable', [{ id: 'x' }, null, 'claude']]]) {
test(`settings-backend-a3: a status with ${name} shows no select and says the providers could not be read`, { timeout: 90000 }, async t => {
const { providers: _, ...rest } = SERVICE_UP;
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: providers === undefined ? rest : { ...rest, providers } });
await wait(READING);
const now = await selectNow(b);
assert.deepEqual(now, { options: [], hidden: true, labels: [true], help: 'The providers could not be read, so no account can be added here.', go: true });
assert.equal(await b.evaluate('document.querySelector("#proxy-apikey").hidden'), true);
});
}
test('settings-backend-a3: a status read that fails (an answer that is no status) says the providers could not be read', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: null });
await wait(READING);
assert.deepEqual(await selectNow(b), { options: [], hidden: true, labels: [true], help: 'The providers could not be read, so no account can be added here.', go: true });
});
const fresh = {
release: { fetched: false, verified: false, version: '8.0.42', panelVersion: '1.26.7' },
init: { initialized: false, partial: false, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' },
fence: { set: false }, initLock: { present: false, clearable: false, blockers: [] }, fetch: { state: 'idle' }, restart: null, busy: null,
organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }], ownProxy: { available: false, state: 'not built', reason: 'One proxy per instance.' }, next: ['fetch'],
providers: publicProviders(),
};
const fetched = { ...fresh, release: { ...fresh.release, fetched: true, verified: true }, fetch: { state: 'done', receipt: { op: 'fetch', time: T, version: '8.0.42' } }, next: ['init'] };
const configured = { ...fetched, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, next: ['unit-install'] };