feat(intake): refuse submissions past the daily ceiling, and reset it from the admin (#227)
The check is ordered ahead of uploadImages, for the same reason requireUsableLink is: a refused submission must write zero bytes. Ordering it after would accept the upload, store the files and then throw them away, which is the expensive half of the work the ceiling exists to prevent. A test asserts nothing is stored. 503, not 403. The sender has done nothing wrong, their link is fine, and the condition clears by itself as the window rolls — so the link stays usable and works again the moment there is room. The ceiling never touches the admin upload path, which has its own test. Intake being throttled is an inconvenience; the shop being unable to add its own stock is an outage. reset-ceiling is declared above /:id/revoke because Express matches in order and would otherwise read it as an id and try to revoke a link named "reset-ceiling". That has its own test too. The per-link alert is a named function rather than the inline IIFE the plan wrote. routesAreWrapped.test.ts flags any async inside a route registration not directly wrapped in asyncRoute, and it cannot tell an inner IIFE from an unwrapped handler — nor should it have to. The guard caught this, and the extraction reads better than what it rejected. Backend now 373 unit and 337 integration, all passing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -94,6 +94,28 @@ router.post('/', asyncRoute(async (req: Request, res: Response) => {
|
||||
res.status(201).json({ ...link, token, url: `${base}/submit/${token}` });
|
||||
}));
|
||||
|
||||
/**
|
||||
* Forgives the current ceiling window without deleting anything.
|
||||
*
|
||||
* The count is derived from item_drafts rows, which are real submissions with
|
||||
* real items in the review queue — so a reset moves the window's start rather
|
||||
* than removing anything. Recovery is automatic as the window rolls; this is
|
||||
* for the case where the ceiling was hit legitimately and waiting is not
|
||||
* acceptable.
|
||||
*
|
||||
* Declared above `/:id/revoke` deliberately: Express matches in order, and
|
||||
* `reset-ceiling` would otherwise be read as an id.
|
||||
*/
|
||||
router.post('/reset-ceiling', asyncRoute(async (_req: Request, res: Response) => {
|
||||
await pool.query(
|
||||
`INSERT INTO admin_settings (key, value, updated_at)
|
||||
VALUES ('intake_ceiling_reset_at', $1, now())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
|
||||
[new Date().toISOString()]
|
||||
);
|
||||
res.json({ reset: true });
|
||||
}));
|
||||
|
||||
router.post('/:id/revoke', asyncRoute(async (req: Request, res: Response) => {
|
||||
// COALESCE so revoking twice keeps the original timestamp. The useful fact
|
||||
// is when access ended, and a second click should neither rewrite that nor
|
||||
|
||||
@@ -5,6 +5,9 @@ import { hashToken } from '../uploadLinks';
|
||||
import { uploadImages, verifyUploadedImages, insertItemImages } from '../imageUpload';
|
||||
import { intakeViewLimiter, intakeSubmitLimiter } from '../rateLimit';
|
||||
import { draftQueued } from '../intake/draftingWorker';
|
||||
import { checkCapacity, countForLinkSince, windowStart } from '../intake/capacity';
|
||||
import { alertCeilingReached, alertLinkThreshold } from '../intake/abuseAlert';
|
||||
import { getSettings } from '../adminSettings';
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -61,6 +64,53 @@ async function usableLink(token: string): Promise<LinkRow | null> {
|
||||
* and the unlink would skip. Ordering this ahead of `uploadImages` is the
|
||||
* whole mitigation, and a test asserts it.
|
||||
*/
|
||||
/**
|
||||
* Refuses when the intake surface as a whole is over its ceiling.
|
||||
*
|
||||
* Ordered ahead of `uploadImages` for the same reason `requireUsableLink` is: a
|
||||
* refused submission must write zero bytes to disk. Ordering it after would
|
||||
* accept the upload, store the files and then throw them away, which is the
|
||||
* expensive half of the work this exists to prevent.
|
||||
*
|
||||
* 503 rather than 403. The sender has done nothing wrong, their link is fine,
|
||||
* and the condition clears by itself as the window rolls.
|
||||
*/
|
||||
/**
|
||||
* Alerts when one link crosses its threshold.
|
||||
*
|
||||
* A named function rather than an inline IIFE in the handler. The wrapper guard
|
||||
* flags any `async` inside a route registration that is not directly preceded
|
||||
* by `asyncRoute(`, and it cannot tell an inner IIFE from an unwrapped handler —
|
||||
* nor should it have to.
|
||||
*/
|
||||
async function alertIfLinkIsBusy(link: LinkRow): Promise<void> {
|
||||
const { intakeLinkAlertThreshold, intakeCeilingResetAt } = await getSettings();
|
||||
const used = await countForLinkSince(link.id, windowStart(new Date(), intakeCeilingResetAt));
|
||||
if (used >= intakeLinkAlertThreshold) {
|
||||
await alertLinkThreshold(link.id, link.label, used, intakeLinkAlertThreshold);
|
||||
}
|
||||
}
|
||||
|
||||
const requireCapacity = asyncRoute(
|
||||
async (_req: Request, res: Response, next: NextFunction) => {
|
||||
const verdict = await checkCapacity();
|
||||
if (verdict.allowed) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// Not awaited: an alert that fails must not become a failed request for
|
||||
// somebody who has done nothing wrong, and the refusal is already decided.
|
||||
void alertCeilingReached(verdict.used, verdict.ceiling).catch((err) =>
|
||||
console.error('[intake] ceiling alert failed:', err)
|
||||
);
|
||||
|
||||
res.status(503).json({
|
||||
error: 'we are not able to accept submissions right now — please try again later'
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const requireUsableLink = asyncRoute(
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const link = await usableLink(req.params.token as string);
|
||||
@@ -86,6 +136,7 @@ router.post(
|
||||
'/:token',
|
||||
intakeSubmitLimiter,
|
||||
requireUsableLink,
|
||||
requireCapacity,
|
||||
uploadImages,
|
||||
asyncRoute(async (req: Request, res: Response) => {
|
||||
// Set by requireUsableLink above. Re-checked rather than asserted non-null,
|
||||
@@ -157,6 +208,13 @@ router.post(
|
||||
// is a few minutes' delay rather than a lost submission.
|
||||
void draftQueued(1).catch((err) => console.error('[drafting] after submission:', err));
|
||||
|
||||
// The signal that a link has been shared further than intended, which is
|
||||
// the case the revoke mechanism exists for and which otherwise depends on
|
||||
// somebody happening to look. Not awaited, for the same reason as above.
|
||||
void alertIfLinkIsBusy(link).catch((err) =>
|
||||
console.error('[intake] link threshold alert failed:', err)
|
||||
);
|
||||
|
||||
// No item id in the response: the sender has no business knowing about
|
||||
// the catalogue, and nothing they could do with it.
|
||||
res.status(201).json({ ok: true });
|
||||
|
||||
Reference in New Issue
Block a user