wishforge-ide/apps/ide/provisioner/resource-grants.mjs
eust-w b47a07e8d2 chore: baseline snapshot of the Codex-delivered code before review
Imports the previously untracked working tree as-is so that the review
changes that follow (requirements -> design -> implementation) can be
reviewed as diffs and reverted if needed. No content changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:18:04 +08:00

16 lines
2.2 KiB
JavaScript

import { createHmac, timingSafeEqual } from 'node:crypto';
const fields = ['schemaVersion','tenantId','runId','generation','planId','planVersion','image','cpuMilli','memoryMiB','storageMiB','issuedAt','expiresAt'];
export function resourceGrantPayload(grant) { return JSON.stringify(Object.fromEntries(fields.map(name => [name, grant[name]]))); }
export function verifyResourceGrant(config, request, { allowExpired = false, allowRetiredImage = false, cleanup = false } = {}) {
const grant = request.resourceGrant;
if (!config.resourceGrantSecret || config.resourceGrantSecret.length < 32 || !grant || Object.keys(grant).some(key => ![...fields,'signature'].includes(key))) throw new Error('RESOURCE_GRANT_INVALID');
const expected = createHmac('sha256', config.resourceGrantSecret).update(resourceGrantPayload(grant)).digest('base64url');
const supplied = typeof grant.signature === 'string' ? Buffer.from(grant.signature) : Buffer.alloc(0), signature = Buffer.from(expected);
if (supplied.length !== signature.length || !timingSafeEqual(supplied,signature) || grant.schemaVersion !== 1 || grant.tenantId !== request.tenantId || request.tenantId !== config.tenantId || grant.runId !== request.runId || grant.generation !== request.generation) throw new Error('RESOURCE_GRANT_INVALID');
const now = Math.floor(Date.now()/1000);
if (!Number.isSafeInteger(grant.issuedAt) || !Number.isSafeInteger(grant.expiresAt) || grant.issuedAt > now + 30 || grant.expiresAt <= grant.issuedAt || grant.expiresAt - grant.issuedAt > 300 || (!allowExpired && grant.expiresAt <= now)) throw new Error('RESOURCE_GRANT_EXPIRED');
if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]*@sha256:[a-f0-9]{64}$/.test(grant.image) || (!allowRetiredImage && ![config.image, ...(config.previousImages ?? [])].includes(grant.image))) throw new Error('RUNTIME_IMAGE_MIGRATION_REQUIRED');
for (const [field, maximum, minimum] of [['cpuMilli',config.cpuMilliCap??2000,100],['memoryMiB',config.memoryMiBCap??4096,512],['storageMiB',Number.parseInt(config.storageSize,10)*1024,128]]) if (!Number.isSafeInteger(grant[field]) || grant[field] < minimum || (!cleanup && grant[field] > maximum)) throw new Error('RESOURCE_LIMIT');
return grant;
}