deployed-website-source.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import { createHash, randomUUID } from 'node:crypto';
  2. import { lstat, mkdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
  3. import { dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from 'node:path';
  4. import JSZip from 'jszip';
  5. import { LocalMatrixClient } from '../matrix/local-matrix-client.js';
  6. import type { LocalRuntimeAuthContext } from '../runtime/model-resolver.js';
  7. import type { LocalRuntimeRoutingContext } from '../runtime/routing-headers.js';
  8. import { LocalWebsiteManagementClient } from './local-website-management-client.js';
  9. /**
  10. * Materializes retained deployed-site source before model execution. Only the owner API may
  11. * supply the signed download URL, which must never enter prompts or logs.
  12. */
  13. export const DEPLOYED_WEBSITE_SOURCE_MAX_ARCHIVE_BYTES = 200 * 1024 * 1024;
  14. export const DEPLOYED_WEBSITE_SOURCE_MAX_UNCOMPRESSED_BYTES = 512 * 1024 * 1024;
  15. export const DEPLOYED_WEBSITE_SOURCE_MAX_FILES = 5_000;
  16. const DEPLOYED_WEBSITE_CONTEXT_RE =
  17. /<deployed-website-context\b[^>]*>([\s\S]*?)<\/deployed-website-context>/gu;
  18. const DEPLOYED_WEBSITE_SOURCE_ROOT = 'deployed-website-sources';
  19. const ARCHIVE_TOO_LARGE_MESSAGE = 'Website source archive is too large.';
  20. const SAFE_ERROR_CODE_RE = /^[A-Z][A-Z0-9_]{0,127}$/u;
  21. export interface DeployedWebsiteSourceOwnerClient {
  22. getProjectSourceDownloadUrl(
  23. nodeId: string,
  24. signal?: AbortSignal,
  25. ): Promise<Record<string, unknown>>;
  26. }
  27. export interface DeployedWebsiteSourceDownloadClient {
  28. getStream(
  29. url: string,
  30. signal?: AbortSignal,
  31. ): Promise<{ body: ReadableStream<Uint8Array>; contentLength?: number; dispose(): void }>;
  32. }
  33. interface DeployedWebsiteContext {
  34. node_id: string;
  35. site_name: string;
  36. site_url?: string;
  37. }
  38. /** Fails closed before the model sees a turn, validating the archive into a local source path. */
  39. export async function prepareDeployedWebsiteEditSources(input: {
  40. content: string;
  41. workspaceDir: string;
  42. ownerClient: DeployedWebsiteSourceOwnerClient;
  43. downloadClient?: DeployedWebsiteSourceDownloadClient;
  44. fetchImpl?: typeof fetch;
  45. signal?: AbortSignal;
  46. }): Promise<string> {
  47. const matches = [...input.content.matchAll(DEPLOYED_WEBSITE_CONTEXT_RE)];
  48. if (matches.length === 0) return input.content;
  49. const extractionRoot = await ensureExtractionRoot(input.workspaceDir);
  50. let cursor = 0;
  51. let prepared = '';
  52. for (const match of matches) {
  53. const index = match.index ?? 0;
  54. const context = parseContext(match[1] ?? '');
  55. const sourcePath = await materializeSource({ ...input, context, extractionRoot });
  56. prepared += input.content.slice(cursor, index);
  57. prepared += `<deployed-website-context>\n${JSON.stringify({
  58. ...context,
  59. source_path: sourcePath,
  60. })}\n</deployed-website-context>`;
  61. cursor = index + match[0].length;
  62. }
  63. return `${prepared}${input.content.slice(cursor)}`;
  64. }
  65. export function prepareDeployedSources(
  66. host: {
  67. readonly authContextGetter: (() => LocalRuntimeAuthContext | undefined) | undefined;
  68. readonly routingContextGetter: (() => LocalRuntimeRoutingContext | undefined) | undefined;
  69. readonly fetchImpl: typeof fetch | undefined;
  70. },
  71. input: { content: string; signal?: AbortSignal },
  72. workspaceDir: string,
  73. ): Promise<string> {
  74. return prepareDeployedWebsiteEditSources({
  75. content: input.content,
  76. workspaceDir,
  77. ownerClient: new LocalWebsiteManagementClient({
  78. ...(host.authContextGetter ? { authContext: host.authContextGetter() } : {}),
  79. routingContextGetter: host.routingContextGetter,
  80. ...(host.fetchImpl ? { fetchImpl: host.fetchImpl } : {}),
  81. }),
  82. downloadClient: new LocalMatrixClient({
  83. ...(host.authContextGetter ? { authContext: host.authContextGetter() } : {}),
  84. routingContextGetter: host.routingContextGetter,
  85. ...(host.fetchImpl ? { fetchImpl: host.fetchImpl } : {}),
  86. }),
  87. signal: input.signal,
  88. });
  89. }
  90. async function materializeSource(input: {
  91. workspaceDir: string;
  92. ownerClient: DeployedWebsiteSourceOwnerClient;
  93. downloadClient?: DeployedWebsiteSourceDownloadClient;
  94. fetchImpl?: typeof fetch;
  95. signal?: AbortSignal;
  96. context: DeployedWebsiteContext;
  97. extractionRoot: string;
  98. }): Promise<string> {
  99. const downloadUrl = await getOwnerDownloadUrl(
  100. input.ownerClient,
  101. input.context.node_id,
  102. input.signal,
  103. );
  104. const archive = await downloadArchive({
  105. url: downloadUrl,
  106. downloadClient: input.downloadClient,
  107. fetchImpl: input.fetchImpl,
  108. signal: input.signal,
  109. });
  110. const sourcePath = join(input.extractionRoot, sourceDirectoryName(input.context.node_id));
  111. const stagingPath = join(input.extractionRoot, `.${randomUUID()}.staging`);
  112. try {
  113. await mkdir(stagingPath);
  114. await extractArchive(archive, stagingPath);
  115. await replaceSourceDirectory(sourcePath, stagingPath);
  116. return sourcePath;
  117. } finally {
  118. await rm(stagingPath, { force: true, recursive: true });
  119. }
  120. }
  121. function parseContext(value: string): DeployedWebsiteContext {
  122. try {
  123. const parsed = JSON.parse(value) as Record<string, unknown>;
  124. const nodeId = typeof parsed.node_id === 'string' ? parsed.node_id.trim() : '';
  125. const siteName = typeof parsed.site_name === 'string' ? parsed.site_name.trim() : '';
  126. const siteUrl = typeof parsed.site_url === 'string' ? parsed.site_url.trim() : '';
  127. if (!nodeId || !siteName) throw new Error('invalid deployed website context');
  128. return {
  129. node_id: nodeId,
  130. site_name: siteName,
  131. ...(siteUrl ? { site_url: siteUrl } : {}),
  132. };
  133. } catch {
  134. throw new Error('Invalid deployed website context.');
  135. }
  136. }
  137. async function getOwnerDownloadUrl(
  138. ownerClient: DeployedWebsiteSourceOwnerClient,
  139. nodeId: string,
  140. signal: AbortSignal | undefined,
  141. ): Promise<string> {
  142. let response: Record<string, unknown>;
  143. try {
  144. response = await ownerClient.getProjectSourceDownloadUrl(nodeId, signal);
  145. } catch {
  146. throw new Error('Website source owner service failed.');
  147. }
  148. const baseResp = readRecord(response.base_resp);
  149. const baseStatus = readNumber(baseResp?.status_code);
  150. if (baseStatus !== undefined && baseStatus !== 0) {
  151. throw new Error('Website source owner service failed.');
  152. }
  153. const statusCode = readNumber(response.code);
  154. if (statusCode !== undefined && statusCode !== 0) {
  155. const errorCode =
  156. (baseStatus === undefined || baseStatus === 0) &&
  157. typeof response.error_code === 'string' &&
  158. SAFE_ERROR_CODE_RE.test(response.error_code)
  159. ? response.error_code
  160. : undefined;
  161. throw new Error(
  162. errorCode
  163. ? `Website source owner service failed (${errorCode}).`
  164. : 'Website source owner service failed.',
  165. );
  166. }
  167. const downloadUrl = typeof response.download_url === 'string' ? response.download_url.trim() : '';
  168. if (!downloadUrl) throw new Error('Website source owner service failed.');
  169. return downloadUrl;
  170. }
  171. async function downloadArchive(input: {
  172. url: string;
  173. downloadClient?: DeployedWebsiteSourceDownloadClient;
  174. fetchImpl?: typeof fetch;
  175. signal?: AbortSignal;
  176. }): Promise<Buffer> {
  177. let stream: { body: ReadableStream<Uint8Array>; contentLength?: number; dispose(): void };
  178. try {
  179. stream = input.downloadClient
  180. ? await input.downloadClient.getStream(input.url, input.signal)
  181. : await getStreamWithFetch(input.fetchImpl, input.url, input.signal);
  182. } catch {
  183. throw new Error('Website source download failed.');
  184. }
  185. try {
  186. if (
  187. stream.contentLength !== undefined &&
  188. (!Number.isSafeInteger(stream.contentLength) ||
  189. stream.contentLength < 0 ||
  190. stream.contentLength > DEPLOYED_WEBSITE_SOURCE_MAX_ARCHIVE_BYTES)
  191. ) {
  192. throw new Error(ARCHIVE_TOO_LARGE_MESSAGE);
  193. }
  194. try {
  195. return await readBoundedStream(stream.body);
  196. } catch (error) {
  197. if (error instanceof Error && error.message === ARCHIVE_TOO_LARGE_MESSAGE) throw error;
  198. throw new Error('Website source download failed.');
  199. }
  200. } finally {
  201. stream.dispose();
  202. }
  203. }
  204. async function getStreamWithFetch(
  205. fetchImpl: typeof fetch | undefined,
  206. url: string,
  207. signal: AbortSignal | undefined,
  208. ): Promise<{ body: ReadableStream<Uint8Array>; contentLength?: number; dispose(): void }> {
  209. if (!fetchImpl) throw new Error('fetch is unavailable');
  210. const response = await fetchImpl(url, { method: 'GET', signal });
  211. if (!response.ok || !response.body) throw new Error('download failed');
  212. const header = response.headers.get('content-length');
  213. const contentLength = header && /^\d+$/u.test(header) ? Number(header) : undefined;
  214. return {
  215. body: response.body,
  216. ...(contentLength !== undefined ? { contentLength } : {}),
  217. dispose() {},
  218. };
  219. }
  220. async function readBoundedStream(body: ReadableStream<Uint8Array>): Promise<Buffer> {
  221. const reader = body.getReader();
  222. const chunks: Uint8Array[] = [];
  223. let size = 0;
  224. try {
  225. while (true) {
  226. const { done, value } = await reader.read();
  227. if (done) break;
  228. if (!value) continue;
  229. size += value.byteLength;
  230. if (size > DEPLOYED_WEBSITE_SOURCE_MAX_ARCHIVE_BYTES) {
  231. await reader.cancel();
  232. throw new Error(ARCHIVE_TOO_LARGE_MESSAGE);
  233. }
  234. chunks.push(value);
  235. }
  236. return Buffer.concat(chunks);
  237. } finally {
  238. reader.releaseLock();
  239. }
  240. }
  241. async function extractArchive(archive: Buffer, stagingPath: string): Promise<void> {
  242. const zip = await JSZip.loadAsync(archive).catch(() => {
  243. throw new Error('Website source archive is not a valid ZIP archive.');
  244. });
  245. const entries = Object.values(zip.files).filter((entry) => !entry.dir);
  246. if (entries.length === 0) throw new Error('Website source archive contains no files.');
  247. if (entries.length > DEPLOYED_WEBSITE_SOURCE_MAX_FILES) {
  248. throw new Error('Website source archive contains too many files.');
  249. }
  250. let declaredSize = 0;
  251. for (const entry of entries) {
  252. assertSafeZipEntry(entry);
  253. declaredSize += readUncompressedSize(entry);
  254. if (declaredSize > DEPLOYED_WEBSITE_SOURCE_MAX_UNCOMPRESSED_BYTES) {
  255. throw new Error('Website source expanded content is too large.');
  256. }
  257. }
  258. let extractedSize = 0;
  259. for (const entry of entries) {
  260. const destination = resolveEntryPath(stagingPath, entry.name);
  261. const content = await entry.async('nodebuffer').catch(() => {
  262. throw new Error('Website source archive is not a valid ZIP archive.');
  263. });
  264. extractedSize += content.byteLength;
  265. if (extractedSize > DEPLOYED_WEBSITE_SOURCE_MAX_UNCOMPRESSED_BYTES) {
  266. throw new Error('Website source expanded content is too large.');
  267. }
  268. await mkdir(dirname(destination), { recursive: true });
  269. await writeFile(destination, content, { flag: 'wx' });
  270. }
  271. }
  272. function assertSafeZipEntry(entry: JSZip.JSZipObject): void {
  273. const originalName = entry.unsafeOriginalName ?? entry.name;
  274. if (isSymbolicLink(entry)) throw new Error('Website source archive contains a symbolic link.');
  275. if (
  276. !originalName ||
  277. originalName.includes('\0') ||
  278. isAbsolute(originalName) ||
  279. posix.isAbsolute(originalName) ||
  280. win32.isAbsolute(originalName) ||
  281. originalName.split(/[\\/]+/u).some((part) => part === '.' || part === '..')
  282. ) {
  283. throw new Error('Website source archive contains an unsafe path.');
  284. }
  285. }
  286. function isSymbolicLink(entry: JSZip.JSZipObject): boolean {
  287. const permissions = entry.unixPermissions;
  288. const mode =
  289. typeof permissions === 'number'
  290. ? permissions
  291. : typeof permissions === 'string' && /^[0-7]+$/u.test(permissions)
  292. ? Number.parseInt(permissions, 8)
  293. : undefined;
  294. return mode !== undefined && (mode & 0o170000) === 0o120000;
  295. }
  296. function resolveEntryPath(root: string, name: string): string {
  297. const destination = resolve(root, name);
  298. const pathRelative = relative(root, destination);
  299. if (
  300. !pathRelative ||
  301. pathRelative === '..' ||
  302. pathRelative.startsWith(`..${sep}`) ||
  303. isAbsolute(pathRelative)
  304. ) {
  305. throw new Error('Website source archive contains an unsafe path.');
  306. }
  307. return destination;
  308. }
  309. function readUncompressedSize(entry: JSZip.JSZipObject): number {
  310. const size = (entry as { _data?: { uncompressedSize?: unknown } })._data?.uncompressedSize;
  311. if (typeof size !== 'number' || !Number.isSafeInteger(size) || size < 0) {
  312. throw new Error('Website source archive contains invalid size metadata.');
  313. }
  314. return size;
  315. }
  316. async function ensureExtractionRoot(workspaceDir: string): Promise<string> {
  317. const workspace = await realpath(resolve(workspaceDir));
  318. const mavisRoot = join(workspace, '.mavis');
  319. await ensureDirectory(mavisRoot);
  320. const extractionRoot = join(mavisRoot, DEPLOYED_WEBSITE_SOURCE_ROOT);
  321. await ensureDirectory(extractionRoot);
  322. return extractionRoot;
  323. }
  324. async function ensureDirectory(path: string): Promise<void> {
  325. const existing = await lstat(path).catch((error: unknown) => {
  326. if (isMissingPath(error)) return undefined;
  327. throw error;
  328. });
  329. if (!existing) {
  330. await mkdir(path, { recursive: true });
  331. return ensureDirectory(path);
  332. }
  333. if (existing.isSymbolicLink())
  334. throw new Error('Website source extraction root must not be a symbolic link.');
  335. if (!existing.isDirectory())
  336. throw new Error('Website source extraction root is not a directory.');
  337. }
  338. async function replaceSourceDirectory(target: string, staging: string): Promise<void> {
  339. const current = await lstat(target).catch((error: unknown) => {
  340. if (isMissingPath(error)) return undefined;
  341. throw error;
  342. });
  343. if (current?.isSymbolicLink())
  344. throw new Error('Website source extraction root must not be a symbolic link.');
  345. if (current && !current.isDirectory())
  346. throw new Error('Website source extraction target is not a directory.');
  347. if (!current) {
  348. await rename(staging, target);
  349. return;
  350. }
  351. const backup = join(dirname(target), `.${randomUUID()}.previous`);
  352. await rename(target, backup);
  353. try {
  354. await rename(staging, target);
  355. } catch (error) {
  356. await rename(backup, target).catch(() => undefined);
  357. throw error;
  358. }
  359. await rm(backup, { force: true, recursive: true });
  360. }
  361. function sourceDirectoryName(nodeId: string): string {
  362. return createHash('sha256').update(nodeId).digest('hex');
  363. }
  364. function readRecord(value: unknown): Record<string, unknown> | undefined {
  365. return value && typeof value === 'object' && !Array.isArray(value)
  366. ? (value as Record<string, unknown>)
  367. : undefined;
  368. }
  369. function readNumber(value: unknown): number | undefined {
  370. return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
  371. }
  372. function isMissingPath(error: unknown): boolean {
  373. return (
  374. typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT'
  375. );
  376. }