Files
stack/packages/webui/src/project-archive-http.mjs
T
jason.woltje 3e21d239b3 feat(bus): owner project archive and unarchive (#797)
Jason's owner report 2026-11-06: no way to archive or delete projects.
Archive is the reversible half; delete stays out of scope because project
and run records are write-once evidence.

- project.archive / project.unarchive: human-only (project.create's gate
  minus the tester carve-out; tester, user and agent refused). State is the
  latest row of a new append-only project_archives journal (3s->3t, additive;
  the rows are the audit trail), so projects itself never changes and nothing
  is deleted. Repeats refuse project-already-archived / project-not-archived.
- project.list hides archived projects until {includeArchived:true}, which
  flags each with archived:true; a user still lists granted projects only.
- While archived, thread.create, thread.send, room.open and room.send refuse
  project-archived; every existing record stays readable and unarchive
  restores everything.
- Console: new public/project-archive.js (+css) and project-archive-http.mjs
  routes (chatHTTP's write fence); chat.js gains two one-line hooks,
  index.html one script and one link tag; styling only through the shell's
  .project-archive-control / .project-archived-filter hooks.
- CLI: mosaic project archive|unarchive <name-or-id> and list --archived.
- stack-release COUNTED/LISTED gain project_archives (schema order); schema
  step-count pins and migration fixtures updated for 3t.

bus 1601/1601 (Node 24; Node 26 has the pre-existing project-file socket
stall), webui 582/582, plugins 132/132, cli 1191/1194 (two pre-existing
load flakes of the row253 C4 and land_work families; both pass isolated and
the base commit's full suite fails four of the same family).
2026-11-05 23:50:51 -06:00

100 lines
5.7 KiB
JavaScript

// #797 MVP3 (owner report 2026-11-06): the Console's project archive routes, kept out of
// chat-http.mjs and request-http.mjs on purpose. Three shapes only: the archived-projects read
// the "Show archived" toggle needs, and the owner's archive and unarchive writes. The write
// fence is chat-http's: same-origin, signed-in send mode, and the tester listener never has
// them (serve.mjs's TESTER_CHAT_WRITE fence stops a tester POST before this module runs).
import { BusReadError } from './bus.mjs';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const ROUTE = /^\/api\/chat\/projects\/([0-9a-f-]{36})\/(archive|unarchive)$/;
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
const json = (res, status, value) => {
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
res.end(JSON.stringify(value));
};
const STATUS = {
'invalid-request': 400, 'project-not-found': 404,
'project-archived': 409, 'project-already-archived': 409, 'project-not-archived': 409,
'project-exists': 409, 'human-required': 403, unauthenticated: 403, 'read-only': 403,
'unknown-business': 403, 'tester-refused': 403, 'access-refused': 403, 'access-revoked': 401,
'not-configured': 503, 'no-bus-host': 503, 'channel-disabled': 503,
'channel-operation': 503, 'outcome-unknown': 503, 'unknown-verb': 503,
'invalid-response': 502,
};
const safeMessage = (code) =>
code === 'project-not-found' ? 'Project not found.' :
code === 'project-archived' ? 'This project is archived. Unarchive it to use it again.' :
code === 'project-already-archived' ? 'This project is already archived.' :
code === 'project-not-archived' ? 'This project is not archived.' :
code === 'channel-disabled'
? 'Run mosaic plugins to read the revision, then mosaic plugins set --file PATCH with plugins.channel set to ["cli","webui"].'
: `Project operation refused (${code}).`;
async function payload(req) {
if ((req.headers['content-type'] || '').split(';')[0].trim().toLowerCase() !== 'application/json') throw Error();
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 16384) throw Error();
chunks.push(chunk);
}
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length) throw Error();
return value;
}
export async function projectArchiveHTTP(req, res, { path, search, chat, named, send, preview, log }) {
const write = req.method === 'POST';
const refuse = (status, code, sent = false) =>
json(res, status, { error: code, message: safeMessage(code), ...(write ? { sent } : {}) });
if (!['GET', 'POST'].includes(req.method)) return refuse(405, 'method-not-allowed');
const match = ROUTE.exec(path);
const list = path === '/api/chat/projects/archived';
if (!match && !list) return refuse(404, 'not-found');
if (write !== !!match) return refuse(405, 'method-not-allowed');
if (search) return refuse(400, 'invalid-request');
try {
if (write) {
// Same fence as chat-http.mjs: the tester listener answers read-only, and every other
// listener needs send mode on its public name with a signed-in single-user preview.
if (preview?.tester) {
if (!chat) return refuse(403, 'read-only');
if (one(req, 'origin') !== preview.origin) return refuse(403, 'cross-origin');
} else {
if (!send || !named || !preview) return refuse(403, 'read-only');
if (preview.sso !== true && one(req, preview.header) !== preview.user) return refuse(401, 'unauthenticated');
if (one(req, 'origin') !== (preview.origin ?? `https://${preview.host}`)) return refuse(403, 'cross-origin');
}
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse(403, 'cross-site');
await payload(req);
}
} catch { return refuse(400, 'invalid-request'); }
if (!chat) return refuse(503, 'not-configured');
const action = match ? (match[2] === 'archive' ? 'archiveProject' : 'unarchiveProject') : 'projects';
const line = outcome => log(`${new Date().toISOString()} project-archive action=${action} user=${JSON.stringify(preview?.user ?? null)} ${outcome}`);
try {
if (!write) {
const rows = await chat[action]({ includeArchived: true });
if (!Array.isArray(rows) || rows.some(p => !UUID.test(p?.id) || typeof p.name !== 'string'
|| p.name.length > 200 || /[\r\n\0]/.test(p.name) || p.archived !== true && p.archived !== undefined))
return refuse(502, 'invalid-response');
return json(res, 200, { rows, at: new Date().toISOString() });
}
const value = await chat[action]({ project: match[1] });
if (value?.project !== match[1] || value.archived !== (match[2] === 'archive'))
{ line('error=outcome-unknown'); return refuse(503, 'outcome-unknown', 'unknown'); }
line(`project=${match[1]} op=${match[2]}`);
// Only the fields of this operation's receipt are exposed.
return json(res, 200, { project: value.project, archived: value.archived, at: new Date().toISOString() });
} catch (err) {
// Unrecognized transport text is never reflected. Known refusal codes have fixed messages.
// Like chatHTTP: a write whose answer was lost is outcome-unknown; a read is invalid-response.
const known = err instanceof BusReadError && Object.hasOwn(STATUS, err.code);
const code = write ? (known ? err.code : 'outcome-unknown')
: known && err.code !== 'outcome-unknown' ? err.code : 'invalid-response';
if (write) line(`error=${code}`);
return refuse(STATUS[code] ?? 502, code, write && code === 'outcome-unknown' ? 'unknown' : false);
}
}