Files
vibemake-pcb-studio/scripts/pcb-object-relay.mjs
T

220 lines
7.6 KiB
JavaScript

import { randomBytes } from 'node:crypto';
import https from 'node:https';
import { pipeline, Transform } from 'node:stream';
const MIB = 1024 * 1024;
const ARCHIVE_LIMIT = 256 * MIB;
const METADATA_LIMIT = 65536;
const TTL = 5 * 60 * 1000;
const DEFAULT_ORIGIN = 'https://linkerbot.oss-cn-beijing.aliyuncs.com';
const PRIVATE = {
'Cache-Control': 'no-store',
'Referrer-Policy': 'no-referrer',
'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': "default-src 'none'; sandbox",
};
function endWithStatus(res, status) {
if (res.headersSent) {
res.destroy();
return;
}
res.writeHead(status, PRIVATE);
res.end();
}
function byteLimit(maximum) {
let size = 0;
return new Transform({
transform(chunk, _, cb) {
size += chunk.length;
cb(size > maximum ? Error('Storage transfer is too large') : null, chunk);
},
});
}
function routeKind(req, pathname) {
if (!/^Bearer [^\s]+$/i.test(req.headers.authorization || '')) return null;
if (req.method === 'GET' && /^\/api\/pcb\/workspace\/projects\/[^/]+\/document$/.test(pathname))
return 'download';
if (req.method !== 'POST') return null;
if (/^\/api\/pcb\/workspace\/projects\/[^/]+\/uploads\/signature$/.test(pathname))
return 'upload';
return pathname === '/api/uploads/project-covers/signature' ? 'cover' : null;
}
export function createObjectRelay(
siteBase,
origins = DEFAULT_ORIGIN,
request = https.request,
now = Date.now,
) {
const prefix = siteBase + 'storage-transfer/';
const allowed = new Set(
origins.split(',').map((item) => {
const url = new URL(item.trim());
if (
url.protocol !== 'https:' ||
url.username ||
url.password ||
url.pathname !== '/' ||
url.hash ||
url.search
)
throw Error('PCB_OBJECT_ORIGINS must contain only trusted HTTPS origins');
return url.origin;
}),
);
const tickets = new Map();
function issue(rawUrl, method, size, ttl, ownOrigin) {
const url = new URL(rawUrl);
if (url.username || url.password || url.hash || !allowed.has(url.origin))
throw Error('Unexpected object storage endpoint');
const stamp = now();
for (const [key, item] of tickets) if (item.expires <= stamp) tickets.delete(key);
if (tickets.size >= 16384) throw Error('Too many pending transfers');
const token = randomBytes(24).toString('base64url');
tickets.set(token, { url, method, size, expires: stamp + ttl });
return new URL(prefix + token, ownOrigin).href;
}
function prepare(req, pathname, ownOrigin) {
const kind = routeKind(req, pathname);
if (!kind) return null;
// Observe just the small authenticated signature request, while the normal
// platform proxy sends exactly the original bytes.
const chunks = [];
let total = 0;
if (kind !== 'download')
req.on('data', (chunk) => {
total += chunk.length;
if (total <= METADATA_LIMIT) chunks.push(chunk);
});
return async function rewrite(reply, res) {
if (reply.headers['content-encoding'] && reply.headers['content-encoding'] !== 'identity') {
reply.resume();
return endWithStatus(res, 502);
}
try {
const parts = [];
let length = 0;
for await (const chunk of reply) {
length += chunk.length;
if (length > MIB) throw Error('Invalid storage metadata');
parts.push(chunk);
}
const body = JSON.parse(Buffer.concat(parts));
const data = body?.data;
if ((!body.code || body.code === 'OK') && data) {
if (kind === 'download') {
if (
!Number.isSafeInteger(data.sizeBytes) ||
data.sizeBytes < 1 ||
data.sizeBytes > ARCHIVE_LIMIT
)
throw Error('Invalid project archive size');
data.downloadUrl = issue(data.downloadUrl, 'GET', data.sizeBytes, TTL, ownOrigin);
} else {
if (total > METADATA_LIMIT || !data.formFields || typeof data.formFields !== 'object')
throw Error('Invalid signature');
const input = JSON.parse(Buffer.concat(chunks));
const size = kind === 'cover' ? input.fileSize : input.sizeBytes;
if (
!Number.isSafeInteger(size) ||
size < 1 ||
size > (kind === 'cover' ? 5 * MIB : ARCHIVE_LIMIT)
)
throw Error('Invalid object upload size');
// OSS enforces its own per-key signed policy, expiry, and file size.
// This server additionally bounds the original file plus multipart overhead.
data.uploadUrl = issue(data.uploadUrl, 'POST', size + METADATA_LIMIT, TTL, ownOrigin);
}
}
res.writeHead(reply.statusCode, {
...PRIVATE,
'Content-Type': 'application/json; charset=utf-8',
});
res.end(JSON.stringify(body));
} catch {
endWithStatus(res, 502);
}
};
}
function transfer(req, res, url, ownOrigin) {
if (!url.pathname.startsWith(prefix)) return false;
const token = url.pathname.slice(prefix.length);
const ticket = tickets.get(token);
if (!/^[A-Za-z0-9_-]{32}$/.test(token) || url.search) {
endWithStatus(res, 404);
return true;
}
if (!ticket || ticket.expires <= now()) {
endWithStatus(res, 410);
return true;
}
if (req.method !== ticket.method) {
endWithStatus(res, 405);
return true;
}
if (
(req.headers.origin && req.headers.origin !== ownOrigin) ||
req.headers['sec-fetch-site'] === 'cross-site' ||
(ticket.method === 'POST' && req.headers.origin !== ownOrigin)
) {
endWithStatus(res, 403);
return true;
}
const headers = {};
if (ticket.method === 'POST') {
const contentType = req.headers['content-type'] || '';
if (!/^multipart\/form-data;\s*boundary=/i.test(contentType)) {
endWithStatus(res, 415);
return true;
}
headers['content-type'] = contentType;
const length = req.headers['content-length'];
if (length !== undefined) {
if (!/^\d+$/.test(length) || Number(length) > ticket.size) {
endWithStatus(res, 413);
return true;
}
headers['content-length'] = length;
}
}
// Never forward a user bearer, Cookie, Host, Origin or arbitrary request
// headers. The destination is fixed when the platform issues the ticket.
const upstream = request(ticket.url, { method: ticket.method, headers }, (reply) => {
const status = reply.statusCode || 502;
if (status < 200 || status >= 300 || ticket.method === 'POST') {
reply.resume();
endWithStatus(res, status >= 300 && status < 400 ? 502 : status);
return;
}
const length = reply.headers['content-length'];
if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > ticket.size)) {
reply.destroy();
endWithStatus(res, 502);
return;
}
res.writeHead(status, {
...PRIVATE,
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename="project.zip"',
...(length === undefined ? {} : { 'Content-Length': length }),
});
pipeline(reply, byteLimit(ticket.size), res, () => {});
});
upstream.setTimeout(120000, () => upstream.destroy(Error('Storage timed out')));
upstream.on('error', () => {
if (!res.destroyed) endWithStatus(res, 502);
});
res.on('close', () => upstream.destroy());
if (ticket.method === 'POST') pipeline(req, byteLimit(ticket.size), upstream, () => {});
else upstream.end();
return true;
}
return { prepare, transfer };
}