f6c added template-exists for a save under a taken name. The template route had no entry for it, so a duplicate save answered 503 outcome-unknown. Map it to 409 and move the SP8 pin.
103 lines
6.2 KiB
JavaScript
103 lines
6.2 KiB
JavaScript
// Starter packs SP8 (#1873, design section 5): the owner saves the selected organization's shape as a
|
|
// template under their own account, and lists the templates they saved. Owner Console transports only;
|
|
// no caller-supplied business, account, subject or origin reaches the bus.
|
|
//
|
|
// serve.mjs strips /api/orgs/<id> before the route is matched, so the paths below reach this module as
|
|
// /api/templates and /api/templates/preview.
|
|
//
|
|
// GET /api/orgs/<id>/templates {templates, writable}: template.list.console, the owner's saved templates
|
|
// POST /api/orgs/<id>/templates/preview {name, project?}: template.save.console with preview true. Writes nothing;
|
|
// answers the template JSON, every free-text field and the digest
|
|
// POST /api/orgs/<id>/templates {name, digest, project?}: template.save.console with the preview's digest
|
|
//
|
|
// `read` is the owner's Console call (consoleCall), used for the list and the preview, which write nothing.
|
|
// `write` is the owner's Console call fenced to template.save.console (templatesCaller), present only for
|
|
// the owner's own session under --send. The broker answers both .console verbs to the business human's
|
|
// console cap alone and runs the capture, the held-credential scan and the digest check itself.
|
|
export const TEMPLATES_ROUTE = /^\/api\/templates(?:\/(preview))?$/;
|
|
export const TEMPLATE_WRITE_VERBS = Object.freeze(['template.save.console']);
|
|
export const templatesCaller = call => async (verb, args, options) => {
|
|
if (!TEMPLATE_WRITE_VERBS.includes(verb)) throw new Error(`the template writer does not call ${verb}`);
|
|
if (args?.preview !== undefined) throw new Error('the template writer does not preview');
|
|
return call(verb, args, options);
|
|
};
|
|
// A template or project name: the bus's own rule (template-save.mjs checkTemplateName, vocabulary KIND_NAME).
|
|
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
const DIGEST = /^[a-f0-9]{64}$/;
|
|
const LIMIT = 4096;
|
|
const codes = {
|
|
'invalid-request': 400, 'template-secret-suspected': 400, 'starter-pack-invalid': 400,
|
|
'project-not-found': 404,
|
|
'pack-plan-stale': 409, 'starter-pack-template-changed': 409, 'organization-busy': 409, 'template-exists': 409,
|
|
'human-required': 403, 'read-only': 403,
|
|
'not-configured': 503, 'no-bus-host': 503,
|
|
};
|
|
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
|
|
function json(res, status, value) {
|
|
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
res.end(JSON.stringify(value));
|
|
}
|
|
const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
|
|
// The body names exactly the required keys and any of the optional ones; nothing else reaches the bus.
|
|
async function body(req, required, optional) {
|
|
if (one(req, 'content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') return null;
|
|
const chunks = []; let size = 0;
|
|
for await (const chunk of req) { size += chunk.length; if (size > LIMIT) return 'too-large'; chunks.push(chunk); }
|
|
let value;
|
|
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; }
|
|
if (!plain(value) || !required.every(k => Object.hasOwn(value, k)) || Object.keys(value).some(k => !required.includes(k) && !optional.includes(k))) return null;
|
|
return value;
|
|
}
|
|
|
|
export async function templatesHTTP(req, res, { path, owner, read, write, session, live, origin }) {
|
|
const refuse = (status, error) => json(res, status, { error });
|
|
const fail = error => { const code = codes[error?.code] ? error.code : 'outcome-unknown'; return refuse(codes[code] ?? 503, code); };
|
|
const match = TEMPLATES_ROUTE.exec(path);
|
|
if (!match) return refuse(404, 'not-found');
|
|
const preview = match[1] === 'preview';
|
|
const list = !preview && req.method === 'GET';
|
|
const allowed = preview ? ['POST'] : ['GET', 'POST'];
|
|
if (!allowed.includes(req.method)) return refuse(405, 'method-not-allowed');
|
|
// A method the route never serves answers 405 first; every served method is the root owner's.
|
|
if (!owner) return refuse(403, 'owner-only');
|
|
if (!session) return refuse(401, 'sign-in-required');
|
|
if (!read) return refuse(503, 'not-configured');
|
|
const writes = !list && !preview;
|
|
if (writes && !write) return refuse(403, 'read-only');
|
|
const site = one(req, 'sec-fetch-site'), from = one(req, 'origin');
|
|
if (req.method !== 'GET' ? from !== origin || site !== 'same-origin'
|
|
: (req.headersDistinct.origin && from !== origin) || (req.headersDistinct['sec-fetch-site'] && !['same-origin', 'none'].includes(site)))
|
|
return refuse(403, 'cross-origin');
|
|
|
|
let verb, args = {};
|
|
if (list) verb = 'template.list.console';
|
|
else {
|
|
const value = await body(req, preview ? ['name'] : ['name', 'digest'], ['project']);
|
|
if (value === 'too-large') return refuse(413, 'invalid-request');
|
|
if (!value || typeof value.name !== 'string' || !NAME.test(value.name)
|
|
|| (!preview && (typeof value.digest !== 'string' || !DIGEST.test(value.digest)))
|
|
|| (value.project !== undefined && (typeof value.project !== 'string' || !NAME.test(value.project))))
|
|
return refuse(400, 'invalid-request');
|
|
verb = 'template.save.console';
|
|
args = preview ? { ...value, preview: true } : value;
|
|
}
|
|
|
|
// The session is checked again after the body is read: a sign-out meanwhile dispatches nothing.
|
|
if (live() !== session) return refuse(401, 'sign-in-required');
|
|
const subject = { provider: session.provider, iss: session.iss, sub: session.sub };
|
|
let result;
|
|
try { result = writes ? await write(verb, args, { subject }) : await read(verb, args, { subject }); }
|
|
catch (error) { return fail(error); }
|
|
if (!plain(result)) return refuse(503, 'outcome-unknown');
|
|
if (list) {
|
|
if (!Array.isArray(result.templates)) return refuse(503, 'outcome-unknown');
|
|
return json(res, 200, { templates: result.templates, writable: Boolean(write) });
|
|
}
|
|
if (!DIGEST.test(result.digest ?? '')) return refuse(503, 'outcome-unknown');
|
|
if (preview) return json(res, 200, result);
|
|
// A save admitted may already have written its file: the receipt is returned even if the session
|
|
// ended meanwhile, never reported as not done.
|
|
return json(res, 200, { name: result.name, scope: result.scope, digest: result.digest });
|
|
}
|