feat(api): capability enforcement on writes

Add lib/api/cap.js: requireWrite(entity_type) maps HTTP method to
action, runs canAct, and tags req.capTier as allow|suggest|deny→403.
Mutating routes (pages, projects, tasks, refs, resources, source_docs)
now check req.capTier and either run the repo (allow) or divert to
pending_changes returning 202 (suggest). Owner and worker actors stay
on the allow path. requireOwner helper added for Task 11.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
root
2026-05-31 21:03:52 +10:00
parent 7862d22a03
commit 56805053f0
8 changed files with 225 additions and 5 deletions

View File

@@ -4,6 +4,7 @@ import * as repo from '../../db/repos/refs.js';
import { validate } from '../validate.js';
import { parsePagination } from '../pagination.js';
import { NotFoundError, ValidationError, asyncWrap } from '../errors.js';
import { requireWrite, divertToPending } from '../cap.js';
const KINDS = ['url', 'video', 'pdf', 'image', 'file'];
@@ -56,8 +57,12 @@ router.get('/',
);
router.post('/',
requireWrite('ref'),
validate({ body: createSchema }),
asyncWrap(async (req, res) => {
if (req.capTier === 'suggest') {
return divertToPending(req, res, { entity_type: 'ref', action: 'create', payload: req.body });
}
try {
const row = await repo.create(req.body, req.actor);
res.status(201).json(row);
@@ -69,8 +74,12 @@ router.post('/',
);
router.post('/upsert',
requireWrite('ref'),
validate({ body: upsertSchema }),
asyncWrap(async (req, res) => {
if (req.capTier === 'suggest') {
return divertToPending(req, res, { entity_type: 'ref', action: 'upsert', payload: req.body });
}
try {
const row = await repo.upsertByExternal(req.body, req.actor);
res.json(row);
@@ -91,20 +100,32 @@ router.get('/:id',
);
router.patch('/:id',
requireWrite('ref'),
validate({ params: idParams, body: patchSchema }),
asyncWrap(async (req, res) => {
const existing = await repo.getById(req.params.id);
if (!existing) throw new NotFoundError('ref not found');
if (req.capTier === 'suggest') {
return divertToPending(req, res, {
entity_type: 'ref', entity_id: req.params.id, action: 'update', payload: req.body
});
}
const row = await repo.update(req.params.id, req.body, req.actor);
res.json(row);
})
);
router.delete('/:id',
requireWrite('ref'),
validate({ params: idParams }),
asyncWrap(async (req, res) => {
const existing = await repo.getById(req.params.id);
if (!existing) throw new NotFoundError('ref not found');
if (req.capTier === 'suggest') {
return divertToPending(req, res, {
entity_type: 'ref', entity_id: req.params.id, action: 'delete', payload: {}
});
}
await repo.del(req.params.id, req.actor);
res.status(204).end();
})