Files
Void-Homelab/lib/api/cap.js

31 lines
1.3 KiB
JavaScript

import { canAct } from '../auth/capability.js';
import * as pendingChanges from '../db/repos/pending_changes.js';
import { ForbiddenError, UnauthorizedError } from './errors.js';
const METHOD_TO_ACTION = { POST: 'create', PATCH: 'update', PUT: 'update', DELETE: 'delete' };
export function requireWrite(entity_type) {
return (req, _res, next) => {
const action = METHOD_TO_ACTION[req.method] || 'update';
const tier = canAct(req.actor, action, entity_type);
if (tier === 'allow') { req.capTier = 'allow'; return next(); }
if (tier === 'suggest') { req.capTier = 'suggest'; return next(); }
return next(new ForbiddenError(`agent not permitted to ${action} ${entity_type}`));
};
}
export function requireOwner(req, _res, next) {
if (!req.actor) return next(new UnauthorizedError('owner-only endpoint'));
if (req.actor.kind !== 'user') return next(new ForbiddenError('owner-only endpoint'));
next();
}
export async function divertToPending(req, res, { entity_type, entity_id = null, action, payload, reason = null }) {
const change = await pendingChanges.create({
agent_id: req.actor.id,
entity_type, entity_id, action, payload,
reason: reason ?? req.headers['x-reason'] ?? null
});
res.status(202).json({ pending: true, change_id: change.id });
}