Phase A slice A1, no authority change. Agents are defined at three levels: the user's root (<configDir>/agents.json), the organization (roles) and the project (projects.<p>.agents in the organization file). A project's agents are their union, the most specific level winning. - organization: agent-levels.mjs loads and checks the root file (no link, owner uid, no group or other write) and project entries (define, narrow intersect keys only, exclude), and resolves the union. The organization file checks project agents for every reader and leaves them out of the loaded business, so buses see what they saw before. Old-path re-export in packages/business. - webui: GET /api/agents/levels, owner only, with no host path, credential reference or var other than the model in its body. display.js leaves it unscoped. SERVER_PROJECT_KEYS holds agents. - Agents grid: the level band, a project picker, and per agent its level, the file that defines it, memory, status and model, with narrowed keys, overrides and what the project does not get. - Design: docs/plans/2026-11-10_agent-levels-design.md. The roles/ change is a proposal outside this branch.
603 lines
44 KiB
JavaScript
603 lines
44 KiB
JavaScript
// Stream S6: create an organization in the Console and finish its setup there.
|
|
//
|
|
// The browser edits one business document. The server derives every path: a
|
|
// project's root, repository and Git record never come from the browser, and
|
|
// neither does a token file. Only secret references ({ env } or { store }) are
|
|
// accepted. Each write calls the same C2/C3 functions as the CLI verb it names.
|
|
//
|
|
// Routes (owner only, writes need --send and today's origin fencing):
|
|
// GET /api/org-template?id=ID C2 templateRender
|
|
// POST /api/org-validate C2 validateOrg plus the browser scan
|
|
// GET /api/org-admin C1 listOrgs, for the edit picker
|
|
// POST /api/orgs C2 createOrg mosaic org create
|
|
// GET /api/orgs/ID/admin C2 showOrg
|
|
// POST /api/orgs/ID/admin C2 updateOrg mosaic org update --if-revision
|
|
// GET /api/orgs/ID/setup read-back of every setup step (resume)
|
|
// POST /api/orgs/ID/setup/queue C2 queueInit mosaic org queue init
|
|
// POST /api/orgs/ID/setup/project/P C2 projectRepoInit mosaic org project repo init
|
|
// POST /api/orgs/ID/setup/bus C3 busStart mosaic bus start --detach
|
|
// POST /api/orgs/ID/restart/bus C3 busRestart mosaic bus restart (F3; busStart when stopped)
|
|
//
|
|
// GET /api/orgs (the list) and other /api/orgs/ID/... routes are S5's; this
|
|
// handler returns false for them.
|
|
|
|
import { open } from 'node:fs/promises';
|
|
import { lstatSync } from 'node:fs';
|
|
import { checkProject, initProject, projectRepo, recordContext } from '../../project/src/index.mjs';
|
|
import { refuseInsideAgent } from '../../cli/src/transport.mjs';
|
|
import { join } from 'node:path';
|
|
import { actor } from './action-trail.mjs';
|
|
|
|
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
const MAX_BODY = 64 * 1024;
|
|
const ROUTE = /^\/api\/orgs\/([^/]+)\/(admin|setup|delete|archive|restore|restart)(?:\/(queue|bus|project\/([^/]+)|records\/([^/]+)))?$/;
|
|
// The org-template placeholder (packages/organization/src/org-service.mjs templateRender).
|
|
export const placeholderRoot = (id, project) => `/__mosaic_org__/${id}/projects/${project}`;
|
|
// Project fields the server owns. The browser never sees or sends them. `agents` (#1873 A1) is
|
|
// the project's agent level: read-only in A1, so the draft editor can't change it either.
|
|
const SERVER_PROJECT_KEYS = ['root', 'repo', 'git', 'agents'];
|
|
|
|
// The CLI verb each step equals (r4 section 2).
|
|
export function verbFor(step, id, opts = {}) {
|
|
const tail = opts.mode === 'remote' ? `--remote ${opts.remote ?? '<https-url>'}` : '--local-only --accept-local-loss-risk';
|
|
if (step === 'create') return `mosaic org create ${id} --from <file>`;
|
|
if (step === 'update') return `mosaic org update ${id} --from <file> --if-revision ${opts.revision ?? '<revision>'}`;
|
|
if (step === 'queue') return `mosaic org queue init ${id} ${tail}`;
|
|
if (step === 'project') return `mosaic org project repo init ${id} ${opts.project} ${tail}`;
|
|
if (step === 'archive' || step === 'restore') return `mosaic org ${step} ${id} --if-revision ${opts.revision}`;
|
|
if (step === 'delete') return `mosaic org delete ${id} --confirm ${id} --if-revision ${opts.revision}`;
|
|
if (step === 'records') return `mosaic project init ${id} ${opts.project}`;
|
|
if (step === 'bus') return `mosaic bus start ${id} --dev-local-owner --detach`;
|
|
if (step === 'bus-restart') return `mosaic bus restart ${id}`;
|
|
throw new Error(`unknown step ${step}`);
|
|
}
|
|
|
|
// Receipts name host directories (the checkout root, the bus socket). The
|
|
// browser sees them relative to the instance's data and config directories,
|
|
// so no absolute host path reaches the page.
|
|
// Role files are read from the repository; their paths reach the page relative to it.
|
|
const REPO_ROOT = decodeURIComponent(new URL('../../..', import.meta.url).pathname).replace(/\/$/, '');
|
|
export function forReceipt(ctx, receipt) {
|
|
if (!receipt || typeof receipt !== 'object') return receipt;
|
|
const bases = [[ctx?.dataRoot, '<data root>'], [ctx?.configDir, '<config dir>']].filter(([b]) => typeof b === 'string' && b.startsWith('/'));
|
|
const map = v => {
|
|
if (typeof v === 'string') { for (const [b, label] of bases) if (v === b || v.startsWith(`${b}/`)) return label + v.slice(b.length); if (v.startsWith(`${REPO_ROOT}/`)) return v.slice(REPO_ROOT.length + 1); return v.startsWith('/') ? '<host path>' : v; }
|
|
if (Array.isArray(v)) return v.map(map);
|
|
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, map(x)]));
|
|
return v;
|
|
};
|
|
return map(receipt);
|
|
}
|
|
// A message for the page: host directories become relative, any other
|
|
// absolute path is withheld.
|
|
export function plainMessage(ctx, text) {
|
|
return String(text ?? '').replace(/(?<=^|[\s'"`(=])\/[^\s'"`;,)]+/g, m => forReceipt(ctx, { v: m }).v);
|
|
}
|
|
const isCliError = e => e?.name === 'CliError' && Number.isInteger(e.exitCode);
|
|
// A bus host that stopped at boot writes its own refusal to <root>/bus-host/host.log
|
|
// as one "mosaic: ..." line (packages/cli/src/cli.mjs). The page cannot open that
|
|
// log, so the last such line (from the final 4 KiB) is shown with the failure.
|
|
async function hostRefusal(root) {
|
|
if (typeof root !== 'string' || !root.startsWith('/')) return null;
|
|
let fh;
|
|
try {
|
|
fh = await open(join(root, 'bus-host', 'host.log'), 'r');
|
|
const { size } = await fh.stat(), len = Math.min(size, 4096), buf = Buffer.alloc(len);
|
|
await fh.read(buf, 0, len, size - len);
|
|
const line = buf.toString('utf8').split('\n').map(l => l.trim()).filter(l => l.startsWith('mosaic: ')).pop();
|
|
return line ? line.slice(8, 8 + 600) : null;
|
|
} catch { return null; } finally { await fh?.close().catch(() => {}); }
|
|
}
|
|
|
|
// A done step's verb repeats what its receipt records, not the default choice.
|
|
const doneVerb = (step, id, receipt, extra = {}) => verbFor(step, id, { ...extra, ...(receipt?.mode === 'remote' ? { mode: 'remote', remote: receipt.remote } : {}) });
|
|
|
|
function json(res, status, body) {
|
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
res.end(JSON.stringify(body));
|
|
}
|
|
const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null);
|
|
|
|
async function readBody(req) {
|
|
const type = one(req, 'content-type') ?? '';
|
|
if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(type)) throw Object.assign(new Error('JSON body required'), { status: 415 });
|
|
const chunks = []; let size = 0;
|
|
for await (const chunk of req) {
|
|
size += chunk.length;
|
|
if (size > MAX_BODY) throw Object.assign(new Error('body too large'), { status: 413 });
|
|
chunks.push(chunk);
|
|
}
|
|
let value;
|
|
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw Object.assign(new Error('invalid JSON'), { status: 400 }); }
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) throw Object.assign(new Error('JSON object required'), { status: 400 });
|
|
return value;
|
|
}
|
|
function strictKeys(value, allowed) {
|
|
const extra = Object.keys(value).filter(k => !allowed.includes(k));
|
|
if (extra.length) throw Object.assign(new Error(`unknown field ${extra[0]}`), { status: 400, errors: [{ path: `$.${extra[0]}`, field: extra[0], message: 'unknown field' }] });
|
|
}
|
|
|
|
const isPathText = s => /^(?:\/|~|\.\.?(?:\/|\\|$))/.test(s) || s.includes('\\') || s.includes('\0') || /^file:/i.test(s);
|
|
const isShellText = s => /[`;|&<>\n\r]|\$[({]/.test(s);
|
|
const label = path => path.replace(/^\$\.?/, '') || 'document';
|
|
|
|
// Refusals for anything the browser may not send: filesystem paths, shell
|
|
// text, server-owned project fields and token-file references. Returns
|
|
// [{ path, field, message }]; empty means the document may go to the service.
|
|
export function browserProblems(doc) {
|
|
const out = [];
|
|
const add = (path, message) => out.push({ path, field: label(path), message });
|
|
const walk = (value, path, depth) => {
|
|
if (depth > 12) return add(path, 'nested too deeply');
|
|
if (typeof value === 'string') {
|
|
if (value.length > 2048) add(path, 'is too long');
|
|
else if (isPathText(value)) add(path, 'a filesystem path is not accepted from the browser');
|
|
else if (isShellText(value)) add(path, 'shell text is not accepted');
|
|
return;
|
|
}
|
|
if (value === null || typeof value !== 'object') return;
|
|
const entries = Array.isArray(value) ? value.map((v, i) => [String(i), v]) : Object.entries(value);
|
|
for (const [key, child] of entries) {
|
|
const at = Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`;
|
|
if (!Array.isArray(value) && !KEY.test(key)) { add(at, 'field names use letters, digits, dot, dash and underscore'); continue; }
|
|
walk(child, at, depth + 1);
|
|
}
|
|
};
|
|
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return [{ path: '$', field: 'document', message: 'must be a JSON object' }];
|
|
walk(doc, '$', 0);
|
|
for (const [project, entry] of Object.entries(doc.projects && typeof doc.projects === 'object' ? doc.projects : {})) {
|
|
if (!entry || typeof entry !== 'object') continue;
|
|
for (const key of SERVER_PROJECT_KEYS) if (Object.hasOwn(entry, key)) add(`$.projects.${project}.${key}`, 'is set by the server; remove it');
|
|
}
|
|
const credentials = (refs, at) => {
|
|
if (!refs || typeof refs !== 'object' || Array.isArray(refs)) return;
|
|
for (const [service, ref] of Object.entries(refs)) {
|
|
if (!ref || typeof ref !== 'object') continue;
|
|
if (Object.hasOwn(ref, 'file')) add(`${at}.${service}.file`, 'only secret references are accepted ("env" or "store"), not a token file');
|
|
if (Object.hasOwn(ref, 'env') && !(typeof ref.env === 'string' && ENV_NAME.test(ref.env))) add(`${at}.${service}.env`, 'must name an environment variable (A-Z, 0-9, _)');
|
|
}
|
|
};
|
|
for (const [name, role] of Object.entries(doc.roles && typeof doc.roles === 'object' ? doc.roles : {})) credentials(role?.credentials, `$.roles.${name}.credentials`);
|
|
credentials(doc.tracker?.sync?.credentials, '$.tracker.sync.credentials');
|
|
return out;
|
|
}
|
|
|
|
// Field checks that name a path before the business loader runs. The loader
|
|
// reports one message; these give the form one error per field.
|
|
export function formProblems(id, doc) {
|
|
const out = [];
|
|
const add = (path, message) => out.push({ path, field: label(path), message });
|
|
if (typeof id !== 'string' || !ID.test(id)) add('$.id', 'must be 1-64 characters: lowercase letters, digits, dot, dash or underscore, starting with a letter or digit');
|
|
else if (doc.id !== id) add('$.id', `must be ${id}`);
|
|
if (doc.businessVersion !== 1) add('$.businessVersion', 'must be 1');
|
|
if (typeof doc.human !== 'string' || !ID.test(doc.human)) add('$.human', 'must be an id such as local-dev-owner');
|
|
const roles = doc.roles && typeof doc.roles === 'object' && !Array.isArray(doc.roles) ? doc.roles : null;
|
|
if (!roles || !Object.keys(roles).length) add('$.roles', 'must declare at least one role');
|
|
else for (const [name, role] of Object.entries(roles)) {
|
|
if (!ID.test(name)) add(`$.roles.${name}`, 'role names use lowercase letters, digits, dot, dash or underscore');
|
|
if (!role || typeof role !== 'object' || typeof role.definition !== 'string' || !ID.test(role.definition)) add(`$.roles.${name}.definition`, 'must name a role definition');
|
|
}
|
|
for (const kind of ['delivery', 'technical']) {
|
|
const name = doc.arbiters?.[kind];
|
|
if (typeof name !== 'string' || !name) add(`$.arbiters.${kind}`, 'must name a declared role');
|
|
else if (roles && !Object.hasOwn(roles, name)) add(`$.arbiters.${kind}`, `names ${name}, which roles does not declare`);
|
|
}
|
|
const projects = doc.projects && typeof doc.projects === 'object' && !Array.isArray(doc.projects) ? doc.projects : null;
|
|
if (!projects || !Object.keys(projects).length) add('$.projects', 'must name at least one project');
|
|
else for (const [name, entry] of Object.entries(projects)) {
|
|
if (!ID.test(name)) add(`$.projects.${name}`, 'project ids use lowercase letters, digits, dot, dash or underscore');
|
|
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) add(`$.projects.${name}`, 'must be an object');
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// The business loader's messages name the field after the file
|
|
// ("/businesses/a.json projects.work.root must be ..."). Recover a JSON path.
|
|
export function pathFromMessage(message) {
|
|
const text = String(message ?? '');
|
|
let m = text.match(/requires "([A-Za-z]+)"/); if (m) return `$.${m[1]}`;
|
|
if (/^business id\b|business "id"/.test(text)) return '$.id';
|
|
if (/^business human\b/.test(text)) return '$.human';
|
|
if (/"businessVersion"/.test(text)) return '$.businessVersion';
|
|
m = text.match(/\b((?:arbiters|projects|roles|vars|launch|tracker|plugins|usage|retired)(?:\.[A-Za-z0-9_-]+)*)/);
|
|
return m ? `$.${m[1]}` : '$';
|
|
}
|
|
const withField = errors => errors.map(e => {
|
|
const path = e.path && e.path !== '$' ? e.path : pathFromMessage(e.message);
|
|
return { path, field: label(path), message: plainMessage(null, e.message ?? 'invalid') };
|
|
});
|
|
|
|
// What the browser sees: the document without server-held fields. `held`
|
|
// lists their JSON paths so the page can say they are kept on the server.
|
|
export function forBrowser(doc) {
|
|
const copy = structuredClone(doc ?? {}); const held = [];
|
|
for (const [project, entry] of Object.entries(copy.projects ?? {})) {
|
|
if (!entry || typeof entry !== 'object') continue;
|
|
for (const key of SERVER_PROJECT_KEYS) if (Object.hasOwn(entry, key)) { delete entry[key]; held.push(`$.projects.${project}.${key}`); }
|
|
}
|
|
const strip = (refs, at) => {
|
|
for (const [service, ref] of Object.entries(refs ?? {})) if (ref && typeof ref === 'object' && Object.hasOwn(ref, 'file')) { delete refs[service]; held.push(`${at}.${service}`); }
|
|
};
|
|
for (const [name, role] of Object.entries(copy.roles ?? {})) if (role?.credentials) strip(role.credentials, `$.roles.${name}.credentials`);
|
|
if (copy.tracker?.sync?.credentials) strip(copy.tracker.sync.credentials, '$.tracker.sync.credentials');
|
|
return { doc: copy, held };
|
|
}
|
|
|
|
// The document handed to the service: the browser's, plus server-held fields.
|
|
// A new project gets the template placeholder root, as `mosaic org create
|
|
// --from` does with a rendered template; a kept project keeps its stored
|
|
// fields; a token-file reference absent from the browser copy is restored.
|
|
export function toCanonical(id, doc, stored = null) {
|
|
const out = structuredClone(doc);
|
|
for (const [project, entry] of Object.entries(out.projects ?? {})) {
|
|
if (!entry || typeof entry !== 'object' || entry.kind === 'library') continue;
|
|
const before = stored?.projects?.[project];
|
|
const kept = before && typeof before === 'object' ? Object.fromEntries(SERVER_PROJECT_KEYS.filter(k => Object.hasOwn(before, k)).map(k => [k, structuredClone(before[k])])) : {};
|
|
out.projects[project] = { ...entry, ...(Object.hasOwn(kept, 'root') ? kept : { root: placeholderRoot(id, project), ...kept }) };
|
|
}
|
|
const restore = (refs, before) => {
|
|
for (const [service, ref] of Object.entries(before ?? {})) if (ref && typeof ref === 'object' && Object.hasOwn(ref, 'file') && refs && !Object.hasOwn(refs, service)) refs[service] = structuredClone(ref);
|
|
};
|
|
for (const [name, role] of Object.entries(stored?.roles ?? {})) if (out.roles?.[name] && role?.credentials) { out.roles[name].credentials ??= {}; restore(out.roles[name].credentials, role.credentials); }
|
|
if (stored?.tracker?.sync?.credentials && out.tracker?.sync) { out.tracker.sync.credentials ??= {}; restore(out.tracker.sync.credentials, stored.tracker.sync.credentials); }
|
|
return out;
|
|
}
|
|
|
|
// One refusal shape for org errors. A definite refusal (an OrgError code)
|
|
// keeps its code; anything else is an unknown outcome that needs a read-back.
|
|
function refusal(res, error, { step, id, unknownOk = false }) {
|
|
const code = error?.code;
|
|
if (code === 'revision-conflict') return json(res, 409, { error: 'revision-conflict', step, message: 'someone saved this organization after you opened it. Reload to see their version; your edits are still in the form.' });
|
|
// A refusal that names a document field goes back to that field.
|
|
if (typeof code === 'string' && typeof error.path === 'string' && error.path.startsWith('$')) return json(res, 422, { error: code, step, message: String(error.message ?? code), errors: withField([{ path: error.path, message: error.message }]) });
|
|
if (code === 'org-unknown' || code === 'org-mismatch') return json(res, 404, { error: 'org-unavailable' });
|
|
// C2 answers org-unavailable for an organization whose creation did not finish (reserved, not active).
|
|
if (code === 'org-unavailable') return json(res, 409, { error: 'org-inactive', step, message: 'this organization was reserved but its creation did not finish, so it cannot be opened or set up here' });
|
|
if (code === 'not-configured') return json(res, 503, { error: 'not-configured', step, message: 'this part of the organization service is not available on this Console' });
|
|
if (code === 'org-forbidden') return json(res, 403, { error: 'org-forbidden', step, message: String(error.message ?? code) });
|
|
if (code === 'org-exists' || code === 'org-overlap' || code === 'exists') return json(res, 409, { error: code, step, message: 'it already exists; read it back instead of creating it again', readBack: id ? `/api/orgs/${id}/setup` : null });
|
|
if (code === 'org-invalid' && (step === 'queue' || step === 'project')) return json(res, 422, { error: code, step, message: String(error.message), errors: [{ path: '$.remote', field: 'remote', message: String(error.message) }] });
|
|
if (code === 'org-risk') return json(res, 422, { error: code, step, message: String(error.message), errors: [{ path: '$.acceptLocalLossRisk', field: 'acceptLocalLossRisk', message: String(error.message) }] });
|
|
if (typeof code === 'string' && /^org-|invalid|refused|required/.test(code)) return json(res, 422, { error: code, step, message: String(error.message ?? code), errors: error.errors ? withField(error.errors) : [] });
|
|
if (unknownOk) return json(res, 502, { error: 'outcome-unknown', step, message: 'the outcome is unknown. Read the step back before retrying.', readBack: id ? `/api/orgs/${id}/setup` : null });
|
|
return json(res, 500, { error: 'internal', step });
|
|
}
|
|
|
|
// Default service wiring: the real C1/C2/C3 modules, loaded on first use.
|
|
// A missing module (a branch without S1 yet) answers not-configured.
|
|
async function load(spec) { try { return await import(spec); } catch (e) { if (e?.code === 'ERR_MODULE_NOT_FOUND') return null; throw e; } }
|
|
export function defaultOrgAdmin(env = process.env) {
|
|
let system = null;
|
|
return createOrgAdmin({
|
|
service: () => load('../../organization/src/org-service.mjs'),
|
|
registry: () => load('../../organization/src/org-registry.mjs'),
|
|
bus: () => load('../../cli/src/org-bus.mjs'),
|
|
// The same context `mosaic org` builds (packages/cli/src/org.mjs): the named
|
|
// instance from MOSAIC_CONFIG, its data root and its config directory.
|
|
context: async () => {
|
|
if (!system) {
|
|
const { loadSystem } = await import('../../cli/src/config.mjs');
|
|
const { configDir } = await import('../../organization/src/organization-config.mjs');
|
|
const { devOwnerInstance } = await import('../../cli/src/dev-local-owner.mjs');
|
|
let instance; try { instance = devOwnerInstance(env); } catch { return null; }
|
|
system = { configDir: configDir(env), dataRoot: loadSystem({ env, instance }).dataRoot, instance };
|
|
}
|
|
return system;
|
|
},
|
|
});
|
|
}
|
|
|
|
// `service`, `registry` and `bus` are module objects or functions returning
|
|
// them (or null when absent). `context()` gives { configDir, dataRoot, instance }.
|
|
export function createOrgAdmin({ service, registry = null, bus = null, context }) {
|
|
const get = async x => (typeof x === 'function' ? x() : x);
|
|
return { service: () => get(service), registry: () => get(registry), bus: () => get(bus), context: () => get(context) };
|
|
}
|
|
|
|
// The handler. Returns true when it answered. `owner` is the signed-in owner
|
|
// session (provider, iss, sub) or null; `send` says --send is on; `origin` is
|
|
// the page's own origin for the write fence.
|
|
// `trail` (F3) records each bus restart: who, when, which organization and the outcome.
|
|
export async function orgAdminHTTP(req, res, { path, search = '', admin, session = null, owner = false, send = false, origin = null, log = () => {}, trail = null }) {
|
|
const org = path.match(ROUTE);
|
|
const top = ['/api/org-template', '/api/org-presets', '/api/org-validate', '/api/org-admin'].includes(path) || (path === '/api/orgs' && req.method === 'POST');
|
|
if (!org && !top) return false;
|
|
if (!owner || !session) { json(res, 403, { error: 'owner-only', message: 'organization setup is the owner\'s' }); return true; }
|
|
if (!admin) { json(res, 503, { error: 'not-configured' }); return true; }
|
|
const write = req.method === 'POST';
|
|
if (!write && req.method !== 'GET') { json(res, 405, { error: 'method not allowed' }); return true; }
|
|
if (write) {
|
|
if (!send) { json(res, 403, { error: 'read-only', message: 'start the Console with --send to make changes' }); return true; }
|
|
if (!origin || one(req, 'origin') !== origin) { json(res, 403, { error: 'cross-origin request refused' }); return true; }
|
|
if (one(req, 'sec-fetch-site') !== 'same-origin') { json(res, 403, { error: 'cross-site request refused' }); return true; }
|
|
}
|
|
const principal = { provider: session.provider, iss: session.iss, sub: session.sub };
|
|
if (![principal.provider, principal.iss, principal.sub].every(v => typeof v === 'string' && v)) { json(res, 403, { error: 'owner-only' }); return true; }
|
|
try {
|
|
await route(req, res, { path, search, org, admin, principal, write, log, trail, by: actor(session) });
|
|
} catch (error) {
|
|
if (error?.status) json(res, error.status, { error: error.message, ...(error.detail ? { message: error.detail } : {}), ...(error.errors ? { errors: error.errors } : {}) });
|
|
else { log(`org-admin: ${path}: ${error?.code ?? error?.name ?? 'error'}`); json(res, 500, { error: 'internal' }); }
|
|
}
|
|
return true;
|
|
}
|
|
|
|
async function ctxOf(admin, principal) {
|
|
const base = await admin.context();
|
|
if (!base) throw Object.assign(new Error('not-configured'), { status: 503, detail: 'organization setup needs a named instance (MOSAIC_CONFIG=~/.config/mosaic-NAME/config.json)' });
|
|
return { configDir: base.configDir, dataRoot: base.dataRoot, instance: base.instance, principal };
|
|
}
|
|
async function need(admin, which, res, step) {
|
|
const mod = await admin[which]();
|
|
if (!mod) { json(res, 503, { error: 'not-configured', step, message: `the ${which === 'bus' ? 'bus control' : 'organization service'} is not available on this Console yet` }); return null; }
|
|
return mod;
|
|
}
|
|
|
|
// A setup step's receipt, read back. C2 queueShow/projectRepoShow answer
|
|
// org-unavailable when no receipt exists ("setup receipt unavailable"); the
|
|
// caller has already shown the organization, so that means "not done yet".
|
|
async function receiptOf(fn) {
|
|
try { return (await fn()) ?? null; } catch (e) { if (e?.code === 'org-unavailable') return null; throw e; }
|
|
}
|
|
|
|
// Read every setup step back. Each step is { state: 'done' | 'missing' |
|
|
// 'unavailable' | 'unknown', receipt? }. The page resumes from the first
|
|
// step that isn't done.
|
|
async function readSetup(admin, ctx, id) {
|
|
const service = await admin.service(); const bus = await admin.bus();
|
|
const shown = await service.showOrg(ctx, id);
|
|
const step = async (fn) => {
|
|
try { const value = await receiptOf(fn); return value ? { state: 'done', receipt: forReceipt(ctx, value), raw: value } : { state: 'missing' }; }
|
|
catch (e) { if (e?.code === 'not-configured') return { state: 'unavailable', message: 'not available on this Console' }; if (isCliError(e)) return { state: 'unknown', message: `could not be read back: ${plainMessage(ctx, e.message)}` }; return { state: 'unknown', message: `could not be read back${e?.code ? ` (${e.code})` : ''}` }; }
|
|
};
|
|
const projects = Object.entries(shown.doc?.projects ?? {}).filter(([, p]) => p?.kind !== 'library').map(([name]) => name);
|
|
const view = ({ raw, ...rest }, verb) => ({ ...rest, verb });
|
|
const queue = await step(() => service.queueShow(ctx, id));
|
|
const notifications = await step(() => service.notificationShow ? service.notificationShow(ctx, id) : Promise.reject(Object.assign(new Error('not-configured'), { code: 'not-configured' })));
|
|
const out = { id, revision: shown.revision, notifications: view(notifications, verbFor('create', id)), queue: view(queue, doneVerb('queue', id, queue.raw)), projects: [], bus: null };
|
|
for (const project of projects) { const r = await step(() => service.projectRepoShow(ctx, id, project)); out.projects.push({ project, ...view(r, doneVerb('project', id, r.raw, { project })) }); }
|
|
if (!bus) out.bus = { state: 'unavailable', message: 'bus control is not available on this Console yet', verb: verbFor('bus', id) };
|
|
else {
|
|
const status = await step(() => bus.busStatus(ctx, id));
|
|
const { raw, ...rest } = status;
|
|
out.bus = { ...(rest.state === 'done' ? { state: raw.healthy ? 'done' : 'missing', receipt: rest.receipt } : rest), verb: verbFor('bus', id) };
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// A step whose receipt can't be read back is never retried: the page shows it
|
|
// as incomplete with the reason, and the owner inspects it with the show verb.
|
|
function unreadable(res, error, step, id, log) {
|
|
log(`org-admin: ${id} ${step} read-back: ${error?.code ?? error?.name ?? 'error'}`);
|
|
return json(res, 409, { error: 'readback-failed', step, message: `the ${step === 'queue' ? 'checkout' : 'repository'} could not be read back${error?.code ? ` (${error.code})` : ''}, so it was not retried. Inspect it with the show verb.`, readBack: `/api/orgs/${id}/setup` });
|
|
}
|
|
|
|
const gitOptions = (body, res, step) => {
|
|
strictKeys(body, ['mode', 'remote', 'acceptLocalLossRisk']);
|
|
if (body.mode === 'local-only') {
|
|
if (body.acceptLocalLossRisk !== true) { json(res, 422, { error: 'risk-not-accepted', step, errors: [{ path: '$.acceptLocalLossRisk', field: 'acceptLocalLossRisk', message: 'tick the box to accept that a local-only checkout has no copy anywhere else' }] }); return null; }
|
|
if (body.remote !== undefined) { json(res, 422, { error: 'invalid', step, errors: [{ path: '$.remote', field: 'remote', message: 'local only takes no remote' }] }); return null; }
|
|
return { mode: 'local-only', acceptLocalLossRisk: true };
|
|
}
|
|
if (body.mode === 'remote') {
|
|
if (typeof body.remote !== 'string' || body.remote.length > 2048 || !/^https:\/\/[^\s/]+\/\S+$/.test(body.remote) || isShellText(body.remote)) { json(res, 422, { error: 'invalid', step, errors: [{ path: '$.remote', field: 'remote', message: 'must be an https repository URL, such as https://git.example/owner/repo' }] }); return null; }
|
|
if (body.acceptLocalLossRisk !== undefined) { json(res, 422, { error: 'invalid', step, errors: [{ path: '$.acceptLocalLossRisk', field: 'acceptLocalLossRisk', message: 'applies to local only' }] }); return null; }
|
|
return { mode: 'remote', remote: body.remote };
|
|
}
|
|
json(res, 422, { error: 'invalid', step, errors: [{ path: '$.mode', field: 'mode', message: 'choose local only or remote' }] });
|
|
return null;
|
|
};
|
|
|
|
async function route(req, res, { path, search, org, admin, principal, write, log, trail = null, by = null }) {
|
|
if (path === '/api/org-presets' && !write) {
|
|
if (new URLSearchParams(search).size) return json(res, 422, { error: 'invalid', message: 'unexpected query parameter' });
|
|
const service = await need(admin, 'service', res, 'presets'); if (!service) return;
|
|
try { return json(res, 200, { presets: await service.orgPresets() }); }
|
|
catch (e) { return refusal(res, e, { step: 'presets' }); }
|
|
}
|
|
if (path === '/api/org-template' && !write) {
|
|
const params = new URLSearchParams(search);
|
|
for (const [key] of params) if (!['id', 'preset', 'thinking'].includes(key) || params.getAll(key).length !== 1) return json(res, 422, { error: 'invalid', message: 'invalid template query' });
|
|
const id = params.has('id') ? params.get('id') : 'new-org';
|
|
if (!ID.test(id)) return json(res, 422, { error: 'invalid', errors: [{ path: '$.id', field: 'id', message: 'invalid organization id' }] });
|
|
const service = await need(admin, 'service', res, 'template'); if (!service) return;
|
|
let doc;
|
|
try { doc = await service.templateRender(id, params.has('preset') || params.has('thinking') ? { ...(params.has('preset') ? { preset: params.get('preset') } : {}), ...(params.has('thinking') ? { thinking: params.get('thinking') } : {}) } : { fixture: 'local' }); } catch (e) { return refusal(res, e, { step: 'template' }); }
|
|
const shown = forBrowser(doc);
|
|
return json(res, 200, { id, doc: shown.doc, held: shown.held, verb: verbFor('create', id) });
|
|
}
|
|
if (path === '/api/org-validate' && write) {
|
|
const body = await readBody(req); strictKeys(body, ['id', 'doc']);
|
|
const service = await need(admin, 'service', res, 'validate'); if (!service) return;
|
|
const problems = [...browserProblems(body.doc), ...(body.doc && typeof body.doc === 'object' ? formProblems(body.id, body.doc) : [])];
|
|
if (problems.length) return json(res, 200, { ok: false, errors: problems });
|
|
const result = await service.validateOrg(toCanonical(body.id, body.doc));
|
|
return json(res, 200, { ok: result.ok, errors: withField(result.errors ?? []) });
|
|
}
|
|
if (path === '/api/org-admin' && !write) {
|
|
const registry = await need(admin, 'registry', res, 'list'); if (!registry) return;
|
|
const ctx = await ctxOf(admin, principal);
|
|
try { const orgs = await registry.listOrgs(ctx); return json(res, 200, { orgs: orgs.map(o => ({ id: o.id, state: o.state })) }); }
|
|
catch (e) { return refusal(res, e, { step: 'list' }); }
|
|
}
|
|
if (path === '/api/orgs' && write) {
|
|
const body = await readBody(req); strictKeys(body, ['id', 'doc']);
|
|
const service = await need(admin, 'service', res, 'create'); if (!service) return;
|
|
const problems = [...browserProblems(body.doc), ...(body.doc && typeof body.doc === 'object' ? formProblems(body.id, body.doc) : [])];
|
|
if (problems.length) return json(res, 422, { error: 'invalid', step: 'create', errors: problems });
|
|
const doc = toCanonical(body.id, body.doc);
|
|
const checked = await service.validateOrg(doc);
|
|
if (!checked.ok) return json(res, 422, { error: 'invalid', step: 'create', errors: withField(checked.errors ?? []) });
|
|
const ctx = await ctxOf(admin, principal);
|
|
let receipt;
|
|
try { receipt = await service.createOrg(ctx, body.id, doc); } catch (e) { return refusal(res, e, { step: 'create', id: body.id, unknownOk: true }); }
|
|
log(`org-admin: created ${body.id}`);
|
|
return json(res, 201, { outcome: 'done', step: 'create', receipt: forReceipt(ctx, receipt), verb: verbFor('create', body.id) });
|
|
}
|
|
if (!org) return json(res, 404, { error: 'not found' });
|
|
const [, id, kind, sub, repoProject, recordsProject] = org;
|
|
const project = repoProject ?? recordsProject;
|
|
if (!ID.test(id)) return json(res, 404, { error: 'org-unavailable' });
|
|
const service = await need(admin, 'service', res, kind); if (!service) return;
|
|
const ctx = await ctxOf(admin, principal);
|
|
if ((kind === 'archive' || kind === 'restore') && !sub && write) {
|
|
const body = await readBody(req); strictKeys(body, ['revision']);
|
|
if (!Number.isSafeInteger(body.revision) || body.revision < 1) return json(res, 422, { error: 'invalid', step: kind, message: 'A valid revision is required.' });
|
|
let busStop;
|
|
if (kind === 'archive') {
|
|
const bus = await need(admin, 'bus', res, kind); if (!bus) return;
|
|
if (typeof bus.busStopForDelete !== 'function') return json(res, 503, { error: 'not-configured', step: kind, message: 'bus control cannot stop a bus for archive on this Console yet' });
|
|
busStop = bus.busStopForDelete;
|
|
}
|
|
try {
|
|
const fn = kind === 'archive' ? service.archiveOrg : service.restoreOrg;
|
|
if (typeof fn !== 'function') return json(res, 503, { error: 'not-configured', step: kind });
|
|
const receipt = await fn(ctx, id, { ifRevision: body.revision, ...(busStop ? { busStop } : {}) });
|
|
return json(res, 200, { outcome: 'done', step: kind, receipt: forReceipt(ctx, receipt), verb: verbFor(kind, id, { revision: body.revision }) });
|
|
} catch (e) { return refusal(res, e, { step: kind, id, unknownOk: true }); }
|
|
}
|
|
if (kind === 'delete' && !sub && write) {
|
|
const body = await readBody(req); strictKeys(body, ['confirm', 'revision']);
|
|
if (body.confirm !== id || !Number.isSafeInteger(body.revision) || body.revision < 1) return json(res, 422, { error: 'invalid', step: 'delete', message: 'Confirmation and a valid revision are required.' });
|
|
const bus = await need(admin, 'bus', res, 'delete'); if (!bus) return;
|
|
if (typeof bus.busStopForDelete !== 'function') return json(res, 503, { error: 'not-configured', step: 'delete', message: 'bus control cannot stop a bus for deletion on this Console yet' });
|
|
try {
|
|
const receipt = await service.deleteOrg(ctx, id, { busStop: bus.busStopForDelete, confirm: body.confirm, ifRevision: body.revision });
|
|
return json(res, 200, { outcome: 'done', step: 'delete', receipt: forReceipt(ctx, receipt), verb: verbFor('delete', id, { revision: body.revision }) });
|
|
} catch (e) { if (e.code === 'revision-conflict') return refusal(res, e, { step: 'delete', id }); return json(res, 409, { error: e.code || 'delete-refused', step: e.deleteStep || 'delete', message: plainMessage(ctx, e.message || 'Deletion stopped; inspect the receipt and resume with the CLI.'), receipt: forReceipt(ctx, e.deleteReceipt), verb: verbFor('delete', id, { revision: body.revision }) }); }
|
|
}
|
|
if (kind === 'admin' && !sub) {
|
|
if (!write) {
|
|
try {
|
|
const shown = await service.showOrg(ctx, id, { includeArchived: true }); const view = forBrowser(shown.doc);
|
|
return json(res, 200, { id, state: shown.state ?? 'active', revision: shown.revision, doc: view.doc, held: view.held, verb: verbFor('update', id, { revision: shown.revision }) });
|
|
} catch (e) { return refusal(res, e, { step: 'show', id }); }
|
|
}
|
|
const body = await readBody(req); strictKeys(body, ['doc', 'ifRevision']);
|
|
if (!Number.isSafeInteger(body.ifRevision) || body.ifRevision < 1) return json(res, 422, { error: 'invalid', step: 'update', errors: [{ path: '$.ifRevision', field: 'ifRevision', message: 'reload the organization; the revision you opened is missing' }] });
|
|
const problems = [...browserProblems(body.doc), ...(body.doc && typeof body.doc === 'object' ? formProblems(id, body.doc) : [])];
|
|
if (problems.length) return json(res, 422, { error: 'invalid', step: 'update', errors: problems });
|
|
let shown;
|
|
try { shown = await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step: 'update', id }); }
|
|
if (shown.revision !== body.ifRevision) return refusal(res, { code: 'revision-conflict' }, { step: 'update', id });
|
|
const doc = toCanonical(id, body.doc, shown.doc);
|
|
const checked = await service.validateOrg(doc);
|
|
if (!checked.ok) return json(res, 422, { error: 'invalid', step: 'update', errors: withField(checked.errors ?? []) });
|
|
let receipt;
|
|
try { receipt = await service.updateOrg(ctx, id, doc, { ifRevision: body.ifRevision }); } catch (e) { return refusal(res, e, { step: 'update', id, unknownOk: true }); }
|
|
return json(res, 200, { outcome: 'done', step: 'update', receipt: forReceipt(ctx, receipt), verb: verbFor('update', id, { revision: body.ifRevision }) });
|
|
}
|
|
if (kind === 'setup' && sub?.startsWith('records/')) {
|
|
let name;
|
|
try { name = decodeURIComponent(project); } catch { return json(res, 404, { error: 'not found' }); }
|
|
if (!ID.test(name)) return json(res, 404, { error: 'not found' });
|
|
if (write) { const body = await readBody(req); strictKeys(body, []); }
|
|
try {
|
|
const shown = await service.showOrg(ctx, id);
|
|
if (!Object.hasOwn(shown.doc?.projects ?? {}, name)) return json(res, 404, { error: 'project-unknown', step: 'records' });
|
|
const context = recordContext({ business: shown.doc, project: name, dataRoot: ctx.dataRoot, orgRoot: shown.root });
|
|
const repo = projectRepo(context);
|
|
let exists = true;
|
|
try { lstatSync(repo); } catch (e) { if (e.code === 'ENOENT') exists = false; else throw e; }
|
|
if (!exists && write) { refuseInsideAgent(); await initProject(context); }
|
|
if (!exists && !write) return json(res, 200, { state: 'missing', step: 'records', verb: verbFor('records', id, { project: name }) });
|
|
const checked = await checkProject(context);
|
|
if (!checked.ok) return json(res, 409, { error: 'readback-failed', step: 'records', message: 'Project records could not be verified; inspect them before retrying.' });
|
|
return json(res, 200, { state: 'done', outcome: 'done', step: 'records', verb: verbFor('records', id, { project: name }) });
|
|
} catch (e) {
|
|
return json(res, 409, { error: e.code ?? 'readback-failed', step: 'records', message: plainMessage(ctx, e.message ?? 'Project records could not be verified.') });
|
|
}
|
|
}
|
|
if (kind === 'setup' && !sub && !write) {
|
|
try { return json(res, 200, await readSetup(admin, ctx, id)); } catch (e) { return refusal(res, e, { step: 'setup', id }); }
|
|
}
|
|
if (kind === 'restart') return restartBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by });
|
|
if (kind !== 'setup' || !sub || !write) return json(res, 404, { error: 'not found' });
|
|
|
|
// Every setup write reads the step back first and never overwrites.
|
|
if (sub === 'queue') {
|
|
const body = await readBody(req); const opts = gitOptions(body, res, 'queue'); if (!opts) return;
|
|
try { await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step: 'queue', id }); }
|
|
let existing;
|
|
try { existing = await receiptOf(() => service.queueShow(ctx, id)); } catch (e) { return unreadable(res, e, 'queue', id, log); }
|
|
if (existing) return json(res, 200, { outcome: 'done', existing: true, step: 'queue', receipt: forReceipt(ctx, existing), verb: doneVerb('queue', id, existing) });
|
|
try { const receipt = await service.queueInit(ctx, id, opts); return json(res, 201, { outcome: 'done', step: 'queue', receipt: forReceipt(ctx, receipt), verb: verbFor('queue', id, opts) }); }
|
|
catch (e) { return refusal(res, e, { step: 'queue', id, unknownOk: true }); }
|
|
}
|
|
if (sub.startsWith('project/')) {
|
|
let name;
|
|
try { name = decodeURIComponent(project); } catch { return json(res, 404, { error: 'not found' }); }
|
|
if (!ID.test(name)) return json(res, 404, { error: 'not found' });
|
|
const body = await readBody(req); const opts = gitOptions(body, res, 'project'); if (!opts) return;
|
|
let shown;
|
|
try { shown = await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step: 'project', id }); }
|
|
if (!Object.hasOwn(shown.doc?.projects ?? {}, name) || shown.doc.projects[name]?.kind === 'library') return json(res, 404, { error: 'project-unknown', step: 'project', message: `${id} declares no project ${name}` });
|
|
let existing;
|
|
try { existing = await receiptOf(() => service.projectRepoShow(ctx, id, name)); } catch (e) { return unreadable(res, e, 'project', id, log); }
|
|
if (existing) return json(res, 200, { outcome: 'done', existing: true, step: 'project', project: name, receipt: forReceipt(ctx, existing), verb: doneVerb('project', id, existing, { project: name }) });
|
|
try { const receipt = await service.projectRepoInit(ctx, id, name, opts); return json(res, 201, { outcome: 'done', step: 'project', project: name, receipt: forReceipt(ctx, receipt), verb: verbFor('project', id, { ...opts, project: name }) }); }
|
|
catch (e) { return refusal(res, e, { step: 'project', id, unknownOk: true }); }
|
|
}
|
|
if (sub === 'bus') {
|
|
const body = await readBody(req); strictKeys(body, []);
|
|
try { await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step: 'bus', id }); }
|
|
const bus = await need(admin, 'bus', res, 'bus'); if (!bus) return;
|
|
let status = null;
|
|
try { status = await bus.busStatus(ctx, id); if (status?.healthy) return json(res, 200, { outcome: 'done', existing: true, step: 'bus', receipt: forReceipt(ctx, status), verb: verbFor('bus', id) }); }
|
|
catch (e) { if (e?.code === 'org-unknown' || e?.code === 'org-mismatch' || e?.code === 'org-unavailable') return refusal(res, e, { step: 'bus', id }); if (isCliError(e)) return json(res, 409, { error: 'bus-refused', step: 'bus', message: plainMessage(ctx, e.message) }); }
|
|
try { const receipt = await bus.busStart(ctx, id, { detach: true, devLocalOwner: principal.provider === 'local-dev', pm: false }); return json(res, 201, { outcome: 'done', step: 'bus', receipt: forReceipt(ctx, receipt), verb: verbFor('bus', id) }); }
|
|
// C3 throws CliError for a refusal and for a host it started and stopped
|
|
// (packages/cli/src/org-bus.mjs:13,103, both exit 3): a known failure either way.
|
|
catch (e) {
|
|
if (!isCliError(e)) return refusal(res, e, { step: 'bus', id, unknownOk: true });
|
|
const failed = /^bus failed to start\b/.test(e.message);
|
|
const said = failed ? await hostRefusal(status?.root) : null;
|
|
return json(res, 409, { error: failed ? 'bus-failed' : 'bus-refused', step: 'bus', message: plainMessage(ctx, said ? `${e.message}. The bus host said: ${said}` : e.message) });
|
|
}
|
|
}
|
|
return json(res, 404, { error: 'not found' });
|
|
}
|
|
|
|
// F3 (REQ-WEB-3): one control restarts an organization's bus and answers with a done receipt. A
|
|
// running host restarts on the options it was started with (C3 busRestart keeps --dev-local-owner);
|
|
// a stopped one starts as setup starts it. The trail line is written before anything changes, and
|
|
// a trail that cannot be written refuses the restart. Stale host state is never cleared here.
|
|
async function restartBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by }) {
|
|
const step = 'bus-restart';
|
|
if (sub !== 'bus' || !write) return json(res, 404, { error: 'not found' });
|
|
const body = await readBody(req); strictKeys(body, []);
|
|
try { await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step, id }); }
|
|
const bus = await need(admin, 'bus', res, step); if (!bus) return;
|
|
if (!trail) return json(res, 503, { error: 'trail-unavailable', step, message: 'this Console has no action trail, so it does not restart buses' });
|
|
let status;
|
|
try { status = await bus.busStatus(ctx, id); }
|
|
catch (e) {
|
|
if (['org-unknown', 'org-mismatch', 'org-unavailable', 'org-archived'].includes(e?.code)) return refusal(res, e, { step, id });
|
|
if (isCliError(e)) {
|
|
// Refused before anything changed, but the owner asked: the trail records the attempt.
|
|
try { trail({ by, action: 'bus.restart', org: id, outcome: 'refused', running: null }); } catch { log(`org-admin: ${id} bus restart: trail write failed after refused`); }
|
|
return json(res, 409, { error: 'bus-refused', step, message: `${plainMessage(ctx, e.message)}. Inspect it with mosaic bus status ${id}; mosaic bus recover ${id} clears a host that died.` });
|
|
}
|
|
return refusal(res, e, { step, id });
|
|
}
|
|
const running = Number.isSafeInteger(status?.pid);
|
|
try { trail({ by, action: 'bus.restart', org: id, outcome: 'requested', running }); }
|
|
catch { return json(res, 500, { error: 'trail-unavailable', step, message: 'the action trail could not be written, so nothing was restarted' }); }
|
|
const note = outcome => { try { trail({ by, action: 'bus.restart', org: id, outcome }); } catch { log(`org-admin: ${id} bus restart: trail write failed after ${outcome}`); } };
|
|
let receipt;
|
|
try {
|
|
receipt = running ? await bus.busRestart(ctx, id) : await bus.busStart(ctx, id, { detach: true, devLocalOwner: by?.provider === 'local-dev', pm: false });
|
|
} catch (e) {
|
|
note('refused');
|
|
if (!isCliError(e)) return refusal(res, e, { step, id, unknownOk: true });
|
|
return json(res, 409, { error: /^bus failed to start\b/.test(e.message) ? 'bus-failed' : 'bus-refused', step, message: plainMessage(ctx, e.message) });
|
|
}
|
|
note('done');
|
|
log(`org-admin: ${id} bus ${running ? 'restarted' : 'started'}`);
|
|
let healthy = null;
|
|
try { healthy = (await bus.busStatus(ctx, id)).healthy; } catch { /* the receipt still stands */ }
|
|
return json(res, 200, { outcome: 'done', step, restarted: running, healthy, receipt: forReceipt(ctx, receipt), verb: running ? verbFor('bus-restart', id) : verbFor('bus', id) });
|
|
}
|