49 lines
2.5 KiB
JavaScript
49 lines
2.5 KiB
JavaScript
// 本地 / 局域网调试时通过同源服务读取 OSS 模型,避免依赖每台电脑 IP 的 CORS 白名单。
|
|
// 线上静态站点继续直连 OSS;代理只接受此 bucket 的模型目录与资源类型。
|
|
export const MODEL_ASSET_ROUTE = '/__model_assets';
|
|
const OSS_ORIGIN = 'https://linkerbot.oss-cn-beijing.aliyuncs.com';
|
|
const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|.+\.local)$/i;
|
|
const MODEL_FILE = /\.(urdf|xml|stl|obj|mtl|dae|glb|gltf|bin|f32|png|jpe?g|webp|gif|bmp|tga|ktx2|json|onnx|wav|mp4)$/i;
|
|
|
|
function allowedAsset(value) {
|
|
try {
|
|
const url = new URL(value);
|
|
const path = decodeURIComponent(url.pathname);
|
|
if (url.origin !== OSS_ORIGIN || url.username || url.password) return null;
|
|
if (!/^\/vibemake(?:_dev)?\/(?:urdf|experiences|project-resources)\/.+\//.test(path) || !MODEL_FILE.test(path)) return null;
|
|
if (/[\\\x00-\x1f%]/.test(path) || path.split('/').some((part) => part === '.' || part === '..')) return null;
|
|
return url;
|
|
} catch { return null; }
|
|
}
|
|
|
|
export function modelAssetUrl(value, hostname = globalThis.location?.hostname || '') {
|
|
// OSS interprets a literal '+' in an object URL as a space. The API can
|
|
// return unescaped names such as '1+4 PCB.glb'; encode only the pathname,
|
|
// leaving signed query strings and already encoded '%2B' unchanged.
|
|
try {
|
|
const url = new URL(value);
|
|
if (url.origin === OSS_ORIGIN && url.pathname.includes('+')) {
|
|
url.pathname = url.pathname.replace(/\+/g, '%2B');
|
|
value = url.href;
|
|
}
|
|
} catch { /* Relative, blob and non-URL values keep their existing handling. */ }
|
|
if (!LOCAL_HOST.test(hostname)) return value;
|
|
const url = allowedAsset(value);
|
|
return url ? `${MODEL_ASSET_ROUTE}${url.pathname}${url.search}` : value;
|
|
}
|
|
|
|
// 服务端也使用同一份白名单;请求不能指定上游主机,也不能跳出模型目录。
|
|
export function modelAssetTarget(requestPath) {
|
|
if (!requestPath.startsWith(`${MODEL_ASSET_ROUTE}/`)) return null;
|
|
return allowedAsset(`${OSS_ORIGIN}${requestPath.slice(MODEL_ASSET_ROUTE.length)}`);
|
|
}
|
|
|
|
export function modelUrlResolver(base, hostname = globalThis.location?.hostname || '') {
|
|
return (value) => {
|
|
// URDFLoader 可能已在 file:/// 前面拼上 workingPath,仍按资源包根目录解析。
|
|
const file = String(value).match(/\/file:\/+(.*)$/i) || String(value).match(/^file:\/+(.*)$/i);
|
|
const resolved = file ? `${base.replace(/\/+$/, '')}/${file[1]}` : value;
|
|
return modelAssetUrl(resolved, hostname);
|
|
};
|
|
}
|