Build review (changes 8) and security review (changes 4): - P1-1: an owner-approved fire no longer writes the revoke before the apply (decision-stale). The fire stops the copy's runs, the fire is written, then the retire revoke starts for the fired instance. - P2 (both): archive and delete from the CLI and the Console pass the organization's managed Gitea remote step (copyRemoteFor). A remote step that was not attempted or failed keeps the record revoking with failed remote, so the bus finishes it after restore; no done tombstone over a live token. - Security P2-1: a bound server that cannot be read is a failed remote step, not not-managed. updateOrg refuses project-repo-bound when a project a copy binding grants loses or changes its remote or git. - P3-1 (security): a delete whose organization file cannot be read says copiesUnreadable, never an empty copy list. - P3-2 (security): the remote step requires the record's incarnation to equal the registry's live one. - P3-5 (build): the archive's slot discard checks each parent directory (no symlink, own uid, private mode). - P3-6 (build): resume keeps credential-revoke-failed as the gate code while a failed op runs again. - P3-4 (build): a test pins the refused-begin reopen guard.
789 lines
59 KiB
JavaScript
789 lines
59 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
|
|
// GET /api/orgs/ID/repo/project/P C2 projectRepoShow mosaic org project repo show (#1873 P1-7)
|
|
// POST /api/orgs/ID/repo/project/P C2 projectRepoSet mosaic org project repo set --if-revision
|
|
// POST /api/orgs/ID/setup/bus C3 busStart mosaic bus start --detach
|
|
// POST /api/orgs/ID/restore C2 restoreOrg, then C3 busStart (E1: the answer's `bus`)
|
|
// POST /api/orgs/ID/restart/bus C3 busRestart mosaic bus restart (F3; busStart when stopped;
|
|
// busRevive for a host that died, dev-local owner only, D2)
|
|
// POST /api/orgs/ID/stop/bus C3 busStop mosaic bus stop (a stopped bus answers state 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';
|
|
import { DEV_OWNER } from '../../cli/src/dev-local-owner.mjs';
|
|
import { revivePending } from './bus-revive.mjs';
|
|
import { parseRepoRemote } from '../../organization/src/vocabulary.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|repo|delete|archive|restore|restart|stop)(?:\/(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 ?? '<repository-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 === 'repo') return `mosaic org project repo set ${id} ${opts.project} ${tail} --if-revision ${opts.revision ?? '<revision>'}`;
|
|
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}`;
|
|
if (step === 'bus-stop') return `mosaic bus stop ${id}`;
|
|
if (step === 'bus-revive') return `mosaic bus recover ${id}; mosaic bus start ${id} --dev-local-owner --detach`;
|
|
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); }
|
|
// #1873 CB1: copy bindings are server-held on an update. Only an owner-approved binding decision
|
|
// changes them, so the stored ones go back whatever the browser sent. A create passes the
|
|
// browser's value through and the service refuses any binding there.
|
|
if (stored) { if (Object.hasOwn(stored, 'copyBindings')) out.copyBindings = structuredClone(stored.copyBindings); else delete out.copyBindings; }
|
|
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) }] });
|
|
// #1873 F7: a copy binding still grants this project; the message names the copies and the next step.
|
|
if (code === 'project-repo-bound') return json(res, 409, { error: code, step, message: String(error.message ?? code) });
|
|
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, extra = []) => {
|
|
strictKeys(body, ['mode', 'remote', 'acceptLocalLossRisk', ...extra]);
|
|
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') {
|
|
// #1873 P1-6: the service's own URL rules (https or ssh; no option, helper, path or credential).
|
|
const parsed = parseRepoRemote(body.remote);
|
|
if (!parsed.ok) { json(res, 422, { error: 'invalid', step, errors: [{ path: '$.remote', field: 'remote', message: parsed.message }] }); 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, copyRemote = null;
|
|
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;
|
|
// #1873 CB4: archive revokes each copy's grant through the organization's managed adapter.
|
|
if (typeof bus.copyRemoteFor === 'function') copyRemote = await bus.copyRemoteFor(ctx);
|
|
}
|
|
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 } : {}), ...(copyRemote ? { copyRemote } : {}) });
|
|
const done = { outcome: 'done', step: kind, receipt: forReceipt(ctx, receipt), verb: verbFor(kind, id, { revision: body.revision }) };
|
|
if (kind === 'archive') return json(res, 200, done);
|
|
return json(res, 200, { ...done, bus: await restoreBus({ id, ctx, admin, log, trail, by }) });
|
|
} 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 copyRemote = typeof bus.copyRemoteFor === 'function' ? await bus.copyRemoteFor(ctx) : null;
|
|
const receipt = await service.deleteOrg(ctx, id, { busStop: bus.busStopForDelete, confirm: body.confirm, ifRevision: body.revision, ...(copyRemote ? { copyRemote } : {}) });
|
|
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 === 'repo' && sub?.startsWith('project/')) return repoSet(req, res, { project, write, id, ctx, service, log });
|
|
if (kind === 'restart') return restartBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by });
|
|
if (kind === 'stop') return stopBus(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' });
|
|
}
|
|
|
|
// E1 (P1-4): Restore brings the organization back running. After a good restore the bus starts as
|
|
// Restart bus starts a stopped one: the owner, origin and --send checks were made for the restore,
|
|
// the trail line is written first, and a trail that cannot be written starts nothing. The restore
|
|
// stands whatever happens here; the answer's `bus` says what did, and the page offers Restart bus
|
|
// when the bus did not start. Never throws.
|
|
async function restoreBus({ id, ctx, admin, log, trail, by }) {
|
|
const verb = verbFor('bus', id);
|
|
const notStarted = (error, message) => ({ outcome: 'not-started', error, message, verb });
|
|
let bus = null;
|
|
try { bus = await admin.bus(); } catch { /* reported as not configured */ }
|
|
if (!bus || typeof bus.busStart !== 'function' || typeof bus.busStatus !== 'function') return notStarted('not-configured', 'bus control is not available on this Console, so the bus was not started');
|
|
if (!trail) return notStarted('trail-unavailable', 'this Console has no action trail, so it does not start buses');
|
|
let root = null;
|
|
try {
|
|
const status = await bus.busStatus(ctx, id);
|
|
if (status?.healthy) return { outcome: 'done', existing: true, healthy: true, receipt: forReceipt(ctx, status), verb };
|
|
root = status?.root ?? null;
|
|
} catch (e) {
|
|
if (!isCliError(e)) { log(`org-admin: ${id} restore: bus status: ${e?.code ?? e?.name ?? 'error'}`); return notStarted('bus-refused', 'the bus state could not be read, so the bus was not started'); }
|
|
return notStarted('bus-refused', `${plainMessage(ctx, e.message)}. Inspect it with mosaic bus status ${id}; mosaic bus recover ${id} clears a host that died.`);
|
|
}
|
|
try { trail({ by, action: 'bus.start', org: id, outcome: 'requested', after: 'restore' }); }
|
|
catch { return notStarted('trail-unavailable', 'the action trail could not be written, so the bus was not started'); }
|
|
const note = outcome => { try { trail({ by, action: 'bus.start', org: id, outcome, after: 'restore' }); } catch { log(`org-admin: ${id} restore bus start: trail write failed after ${outcome}`); } };
|
|
let receipt;
|
|
try { receipt = await bus.busStart(ctx, id, { detach: true, devLocalOwner: by?.provider === 'local-dev', pm: false }); }
|
|
catch (e) {
|
|
const failed = isCliError(e) && /^bus failed to start\b/.test(e.message);
|
|
note(failed ? 'failed' : 'refused');
|
|
if (!isCliError(e)) { log(`org-admin: ${id} restore bus start: ${e?.code ?? e?.name ?? 'error'}`); return { outcome: 'failed', error: 'bus-failed', message: 'the bus did not start', verb }; }
|
|
const said = failed ? await hostRefusal(root) : null;
|
|
return { outcome: 'failed', error: failed ? 'bus-failed' : 'bus-refused', message: plainMessage(ctx, said ? `${e.message}. The bus host said: ${said}` : e.message), verb };
|
|
}
|
|
note('done');
|
|
log(`org-admin: ${id} bus started after restore`);
|
|
let healthy = null;
|
|
try { healthy = (await bus.busStatus(ctx, id)).healthy; } catch { /* the receipt still stands */ }
|
|
return { outcome: 'done', healthy, receipt: forReceipt(ctx, receipt), verb };
|
|
}
|
|
|
|
// #1873 P1-7: the project Settings tab reads and changes the project's repository. GET answers the
|
|
// binding as it is now; POST is `mosaic org project repo set`: the same URL rules and check as setup,
|
|
// origin follows, nothing is pushed, a receipt records it. A project not set up yet answers missing.
|
|
async function repoSet(req, res, { project, write, id, ctx, service, log }) {
|
|
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' });
|
|
let body = null, opts = null;
|
|
if (write) { body = await readBody(req); opts = gitOptions(body, res, 'repo', ['ifRevision']); if (!opts) return; }
|
|
if (write && (!Number.isSafeInteger(body.ifRevision) || body.ifRevision < 1)) return json(res, 422, { error: 'invalid', step: 'repo', errors: [{ path: '$.ifRevision', field: 'ifRevision', message: 'reload the project; the revision you opened is missing' }] });
|
|
let shown;
|
|
try { shown = await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step: 'repo', id }); }
|
|
if (!Object.hasOwn(shown.doc?.projects ?? {}, name) || shown.doc.projects[name]?.kind === 'library') return json(res, 404, { error: 'project-unknown', step: 'repo', 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); }
|
|
// No new refusal code: a write to a project not set up yet is the existing 'invalid'.
|
|
if (!existing) return json(res, write ? 422 : 200, { state: 'missing', step: 'repo', project: name, revision: shown.revision, ...(write ? { error: 'invalid' } : {}), message: 'this project has no repository yet; set it up first', verb: verbFor('project', id, { project: name }) });
|
|
if (!write) {
|
|
const current = existing.current ?? { mode: existing.mode, ...(existing.remote ? { remote: existing.remote } : {}), revision: shown.revision };
|
|
return json(res, 200, { state: 'done', step: 'repo', project: name, current: forReceipt(ctx, current), receipt: forReceipt(ctx, existing), verb: verbFor('repo', id, { ...current, project: name, revision: current.revision }) });
|
|
}
|
|
if (typeof service.projectRepoSet !== 'function') return json(res, 503, { error: 'not-configured', step: 'repo', message: 'changing a project repository is not available on this Console yet' });
|
|
try {
|
|
const receipt = await service.projectRepoSet(ctx, id, name, { ...opts, ifRevision: body.ifRevision });
|
|
return json(res, 200, { outcome: 'done', step: 'repo', project: name, receipt: forReceipt(ctx, receipt), check: receipt?.check ?? null, verb: verbFor('repo', id, { ...opts, project: name, revision: body.ifRevision }) });
|
|
} catch (e) { return refusal(res, e, { step: 'repo', id, unknownOk: true }); }
|
|
}
|
|
|
|
// 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 cleared only for the
|
|
// dev-local owner, and only through busRevive (D2), whose busRecover refuses a host it cannot prove dead.
|
|
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' });
|
|
// D2: the dev Console's start-up revive may be bringing this bus back; the press acts on the result.
|
|
await revivePending(id);
|
|
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)) {
|
|
if (isDevOwner(by) && typeof bus.busRevive === 'function') return reviveBus(res, { id, ctx, bus, log, trail, by, step });
|
|
// 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) });
|
|
}
|
|
|
|
// Stop bus: the same owner, origin, --send and trail rules as Restart bus. C3 busStop sends SIGTERM
|
|
// to the proven host and waits for it to exit; the host's close() removes host.json and host.lock,
|
|
// and the broker's store removes writer.lock, so a clean stop leaves no lock behind (an offline
|
|
// migrate-schema run can follow). The bus state is read back after the stop: a host or lock still
|
|
// there, or state that does not check out, is a failure, not a done receipt. A host whose state
|
|
// cannot be proven refuses before anything changes; there is no recovery path here, unlike Restart
|
|
// bus on the dev Console. A bus that is already stopped answers done with state stopped.
|
|
async function stopBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by }) {
|
|
const step = 'bus-stop';
|
|
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 (typeof bus.busStop !== 'function') return json(res, 503, { error: 'not-configured', step, message: 'bus control cannot stop a bus on this Console yet' });
|
|
if (!trail) return json(res, 503, { error: 'trail-unavailable', step, message: 'this Console has no action trail, so it does not stop buses' });
|
|
// The dev Console's start-up revive may be bringing this bus back; the press acts on the result.
|
|
await revivePending(id);
|
|
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.stop', org: id, outcome: 'refused', running: null }); } catch { log(`org-admin: ${id} bus stop: 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.stop', 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 stopped' }); }
|
|
const note = outcome => { try { trail({ by, action: 'bus.stop', org: id, outcome }); } catch { log(`org-admin: ${id} bus stop: trail write failed after ${outcome}`); } };
|
|
if (!running) {
|
|
note('done');
|
|
return json(res, 200, { outcome: 'done', step, stopped: false, state: 'stopped', receipt: { org: id, stopped: false }, verb: verbFor('bus-stop', id) });
|
|
}
|
|
let receipt;
|
|
try { receipt = await bus.busStop(ctx, id); }
|
|
catch (e) {
|
|
// Only exit 3 comes before the signal; a timeout or an unexpected error may follow SIGTERM.
|
|
note(isCliError(e) && e.exitCode === 3 ? 'refused' : 'failed');
|
|
if (!isCliError(e)) return refusal(res, e, { step, id, unknownOk: true });
|
|
return json(res, 409, { error: e.exitCode === 3 ? 'bus-refused' : 'bus-failed', step, message: `${plainMessage(ctx, e.message)}. Inspect it with mosaic bus status ${id}.` });
|
|
}
|
|
// Read the state back: the stop is done only when no host and no lock is left.
|
|
let after = null, left = 'a bus host still runs';
|
|
try { after = await bus.busStatus(ctx, id); }
|
|
catch (e) { if (!isCliError(e)) { note('failed'); return refusal(res, e, { step, id, unknownOk: true }); } left = plainMessage(ctx, e.message); }
|
|
if (!after || Number.isSafeInteger(after.pid)) {
|
|
note('failed');
|
|
return json(res, 409, { error: 'bus-failed', step, message: `the bus host was stopped, but ${left}. Inspect it with mosaic bus status ${id}; mosaic bus recover ${id} clears a host that died.` });
|
|
}
|
|
note('done');
|
|
log(`org-admin: ${id} bus stopped`);
|
|
// A host that exited on its own between the read and the stop was not stopped by this press.
|
|
return json(res, 200, { outcome: 'done', step, stopped: receipt?.stopped === true, state: 'stopped', receipt: forReceipt(ctx, { org: id, ...receipt }), verb: verbFor('bus-stop', id) });
|
|
}
|
|
|
|
// The dev-local owner exactly (packages/cli/src/dev-local-owner.mjs). A signed-in session carries
|
|
// its provider's issuer, so no SSO user matches.
|
|
const isDevOwner = by => by?.provider === DEV_OWNER.provider && by.iss === DEV_OWNER.iss && by.sub === DEV_OWNER.sub;
|
|
|
|
// D2 (P0-3): the dev Console's Restart bus on a bus whose state did not check out. A Console unit
|
|
// stop kills the hosts the Console started and leaves their state behind; busRevive clears that
|
|
// state only when busRecover proves the host dead, then starts the bus on its recorded options.
|
|
// A live or unprovable host, or a lock that is not the dead host's, refuses and nothing changes.
|
|
async function reviveBus(res, { id, ctx, bus, log, trail, by, step }) {
|
|
try { trail({ by, action: 'bus.restart', org: id, outcome: 'requested', running: false, recover: true }); }
|
|
catch { return json(res, 500, { error: 'trail-unavailable', step, message: 'the action trail could not be written, so nothing was recovered' }); }
|
|
const note = outcome => { try { trail({ by, action: 'bus.restart', org: id, outcome, recover: true }); } catch { log(`org-admin: ${id} bus recover: trail write failed after ${outcome}`); } };
|
|
let receipt;
|
|
try { receipt = await bus.busRevive(ctx, id); }
|
|
catch (e) {
|
|
// busRevive marks a failure after busRecover cleared the dead host's state (e.recovered).
|
|
const cleared = Boolean(e?.recovered);
|
|
note(cleared ? 'failed' : 'refused');
|
|
if (!cleared && e?.code === 'org-locked') return json(res, 409, { error: 'bus-busy', step, message: `another bus or lifecycle action on ${id} is running, and nothing was changed. Press Restart bus again when it ends.` });
|
|
if (cleared) return json(res, 409, { error: 'bus-failed', step, message: isCliError(e) ? plainMessage(ctx, `The dead host's state was cleared, but ${e.message}`) : `The dead host's state was cleared, but the bus did not start. Check it with mosaic bus status ${id}.` });
|
|
if (!isCliError(e)) return refusal(res, e, { step, id, unknownOk: true });
|
|
return json(res, 409, { error: 'bus-refused', step, message: `${plainMessage(ctx, e.message)}. Inspect it with mosaic bus status ${id}.` });
|
|
}
|
|
note('done');
|
|
log(`org-admin: ${id} bus recovered and 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: false, recovered: true, healthy, receipt: forReceipt(ctx, receipt), verb: verbFor('bus-revive', id) });
|
|
}
|