mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-06 03:32:25 +03:00
Update `native-playground.yml` for `desktop-leaf-only` and macOS checks: - Skip `playground` Wasm build and `web-smoke.mjs` when `desktop-leaf-only` is true. Keep `affine_desktop` Wasm, `check-snapshot-prefixes.mjs`, and `verify-desktop-persistence.mjs`. - Narrow macOS desktop tests to `affine-desktop --lib --features harness` while keeping `--all-targets` check coverage. - Build `bs-harness` and `desktop-harness` together in `macos-headless`, and verify deterministic `desktop-harness gallery` output across two runs (`14` PNG files). Add seven live desktop snapshot prefixes to `check-snapshot-prefixes.mjs` (`250` to `257`) and update `check-snapshot-prefixes.test.mjs` with a single-bundle CLI test.
854 lines
25 KiB
JavaScript
854 lines
25 KiB
JavaScript
#!/usr/bin/env node
|
|
// @ts-check
|
|
|
|
/**
|
|
* Verifies that production Wasm bundles (`playground_bg.wasm`,
|
|
* `affine_desktop_bg.wasm`) contain zero harness snapshot ID prefixes in
|
|
* WebAssembly Section 11 (Data).
|
|
*
|
|
* Modes:
|
|
* node scripts/check-snapshot-prefixes.mjs --source-only
|
|
* node scripts/check-snapshot-prefixes.mjs <path/to/bundle_bg.wasm>...
|
|
*/
|
|
|
|
import { createHash } from 'node:crypto';
|
|
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const SCRIPT_DIR = fileURLToPath(new URL('.', import.meta.url));
|
|
export const DEFAULT_REPO_ROOT = resolve(SCRIPT_DIR, '../../..');
|
|
|
|
export const ZERO_IN_PRODUCTION = Object.freeze([
|
|
'edgeless.surface.',
|
|
'edgeless.note.',
|
|
'edgeless.frame.',
|
|
'edgeless.text.',
|
|
'edgeless.block.',
|
|
'page.presence.',
|
|
'page.block.',
|
|
'overlay.slash_menu.item.',
|
|
'overlay.slash_menu.group.',
|
|
'overlay.linked_doc_menu.item.',
|
|
'overlay.linked_doc_menu.group.',
|
|
'overlay.linked_doc_menu.journal.',
|
|
'overlay.pdf_viewer.page.',
|
|
'overlay.pdf_viewer.thumb.',
|
|
'overlay.attachment_toolbar.',
|
|
'overlay.code_more_menu.',
|
|
'overlay.code_lang_picker.item.',
|
|
'overlay.bookmark_toolbar',
|
|
'overlay.embed_toolbar',
|
|
'overlay.format_toolbar.',
|
|
'overlay.image_toolbar.',
|
|
'overlay.link_popup',
|
|
'overlay.callout_toolbar',
|
|
'overlay.callout_icon_picker.',
|
|
'overlay.table_toolbar.axis_menu',
|
|
'overlay.table_col_resize.',
|
|
'overlay.table_hover.',
|
|
'overlay.page_scrollbar',
|
|
'page.table_cell_focus',
|
|
'chrome.edgeless_element_toolbar.',
|
|
'chrome.edgeless_toolbar.',
|
|
'chrome.edgeless_zoom.',
|
|
'edgeless.label_format.',
|
|
'edgeless.mindmap.toggle.',
|
|
'edgeless.handle.rotate_',
|
|
'edgeless.selection_box',
|
|
'edgeless.remote_cursor.',
|
|
'edgeless.remote_selection.',
|
|
'chrome.presence.',
|
|
'overlay.context_menu.',
|
|
'overlay.context_menu',
|
|
'overlay.image_lightbox.',
|
|
'overlay.image_lightbox',
|
|
'overlay.doc_panel.',
|
|
'overlay.doc_panel',
|
|
'overlay.database_record_sheet.',
|
|
'overlay.database_record_sheet',
|
|
'desktop.list.doc.',
|
|
'desktop.trash.row.',
|
|
'desktop.outline.rail.heading.',
|
|
'desktop.inspector.heading.',
|
|
'desktop.qs.doc.',
|
|
'desktop.qs.cmd.',
|
|
'desktop.qs.collection.',
|
|
'desktop.qs.tag.',
|
|
'desktop.sidebar.workspace.',
|
|
'desktop.explorer.doc_menu.',
|
|
'desktop.outline.rail.tick.',
|
|
'desktop.outline.rail.open.',
|
|
'desktop.inspector.backlink.',
|
|
'desktop.trash.restore.',
|
|
'desktop.trash.delete.',
|
|
'desktop.inspector.journal.day.',
|
|
'desktop.app_tabs.tab.',
|
|
'desktop.split.resize.',
|
|
'desktop.explorer.group.',
|
|
'desktop.outline.rail.',
|
|
'desktop.sidebar.sec.',
|
|
'desktop.sidebar.fav.',
|
|
'desktop.sidebar.fdoc.',
|
|
'desktop.sidebar.col_doc.',
|
|
'desktop.sidebar.tag_doc.',
|
|
'desktop.sidebar.folder.',
|
|
'desktop.sidebar.col.',
|
|
'desktop.sidebar.tag.',
|
|
'desktop.trash.open.',
|
|
'desktop.sidebar.resize',
|
|
'desktop.split.resize',
|
|
'desktop.inspector.journal.previous',
|
|
'desktop.inspector.journal.today',
|
|
'desktop.inspector.journal.next',
|
|
'chrome.doc_panel_toggle',
|
|
'chrome.mode_switcher.edgeless',
|
|
'chrome.mode_switcher.indicator',
|
|
'chrome.mode_switcher.page',
|
|
'chrome.nav_back',
|
|
'chrome.theme_toggle',
|
|
'chrome.topbar',
|
|
'desktop.explorer.favorite.',
|
|
'desktop.explorer.heading',
|
|
'desktop.explorer.menu.',
|
|
'desktop.explorer.selected',
|
|
'desktop.explorer.tag_switch.',
|
|
'desktop.header.trash.body',
|
|
'desktop.inspector.frame.item.',
|
|
'desktop.inspector.journal.activity.empty',
|
|
'desktop.inspector.journal.conflict.more',
|
|
'desktop.inspector.journal.conflict.trash.',
|
|
'desktop.inspector.journal.dot.',
|
|
'desktop.inspector.journal.tab.',
|
|
'desktop.pane.0.tab.',
|
|
'desktop.peek.control.tooltip',
|
|
'desktop.settings.font.size.thumb',
|
|
'desktop.sidebar.node.add',
|
|
'desktop.sidebar.node.more',
|
|
'desktop.trash.confirm.body',
|
|
'desktop.trash.confirm.description',
|
|
'desktop.trash_prompt.body',
|
|
'desktop.trash_prompt.description',
|
|
'edgeless.auto_complete.ghost_preview',
|
|
'edgeless.caption_caret',
|
|
'edgeless.caption_focus',
|
|
'edgeless.frame_drop_highlight',
|
|
'edgeless.inline_edit',
|
|
'edgeless.marquee',
|
|
'edgeless.note_slicer',
|
|
'edgeless.snap_guideline',
|
|
'edgeless.transform_hud',
|
|
'overlay.add_block_button',
|
|
'overlay.block_drag_ghost',
|
|
'overlay.calendar_day_hover',
|
|
'overlay.calendar_day_new_row',
|
|
'overlay.calendar_drag_ghost',
|
|
'overlay.calendar_drop_settle',
|
|
'overlay.calendar_event_hover',
|
|
'overlay.calendar_event_resize_',
|
|
'overlay.code_lang_picker.empty',
|
|
'overlay.code_lang_picker.scrollbar',
|
|
'overlay.code_lang_picker.search',
|
|
'overlay.database_popover',
|
|
'overlay.drag_handle',
|
|
'overlay.drop_indicator',
|
|
'overlay.equation_editor.done',
|
|
'overlay.equation_editor.input',
|
|
'overlay.kanban_card_hover',
|
|
'overlay.kanban_drag_ghost',
|
|
'overlay.kanban_drag_placeholder',
|
|
'overlay.kanban_drop_settle',
|
|
'overlay.kanban_lane_footer_add',
|
|
'overlay.keyboard_toolbar.group.',
|
|
'overlay.keyboard_toolbar.panel.',
|
|
'overlay.linked_doc_menu.create',
|
|
'overlay.linked_doc_menu.input_mask',
|
|
'overlay.linked_doc_menu.more',
|
|
'overlay.page_marquee',
|
|
'overlay.pdf_viewer.close',
|
|
'overlay.pdf_viewer.filename',
|
|
'overlay.pdf_viewer.header_title',
|
|
'overlay.pdf_viewer.indicator',
|
|
'overlay.pdf_viewer.status',
|
|
'overlay.pdf_viewer.thumbnails_toggle',
|
|
'overlay.pdf_viewer.zoom_in',
|
|
'overlay.pdf_viewer.zoom_out',
|
|
'overlay.pdf_viewer.zoom_reset',
|
|
'overlay.slash_menu.preview',
|
|
'overlay.slash_menu.query',
|
|
'overlay.table_column_drag_ghost',
|
|
'overlay.table_header_hover',
|
|
'overlay.table_resize_guide',
|
|
'overlay.table_row_drag_ghost',
|
|
'overlay.table_row_drag_handle',
|
|
'overlay.table_toolbar.axis_selection',
|
|
'overlay.table_toolbar.more',
|
|
'overlay.toolbar_tooltip',
|
|
'overlay.touch_selection_menu',
|
|
'page.block_placeholder',
|
|
'page.block_selection',
|
|
'page.caption_caret',
|
|
'page.caption_focus',
|
|
'page.database_cell_focus',
|
|
'page.local_caret',
|
|
'page.selection',
|
|
'page.status',
|
|
'page.table_area_selection',
|
|
'page.table_cell_caret',
|
|
'.attachment_card',
|
|
'.bookmark_card',
|
|
'.builtin.',
|
|
'.custom.menu.',
|
|
'.embed_activate',
|
|
'.embed_card',
|
|
'.embed_shield',
|
|
'.highlight_menu.background.',
|
|
'.hscrollbar',
|
|
'.image_card',
|
|
'.journal_next',
|
|
'.journal_previous',
|
|
'.journal_week',
|
|
'.links.',
|
|
'.tag.attached.',
|
|
'.tag.create',
|
|
'.tag.option.',
|
|
'.toolbar.copy',
|
|
'.toolbar.language',
|
|
'desktop.collection_editor.count',
|
|
'desktop.collection_editor.doc.',
|
|
'desktop.collection_editor.filter.remove.',
|
|
'desktop.collection_editor.include.remove.',
|
|
'desktop.collection_editor.menu.item.',
|
|
'desktop.collection_editor.rules.tips',
|
|
'desktop.collection_editor.selected',
|
|
'desktop.header.dialog.close.icon',
|
|
'desktop.header.info.backlink.',
|
|
'desktop.header.info.outgoing.',
|
|
'desktop.header.trash.description',
|
|
'desktop.header.trash.title',
|
|
'desktop.inspector.outgoing.',
|
|
'desktop.settings.appearance.language',
|
|
'desktop.settings.storage.panel',
|
|
'overlay.pdf_viewer.titlebar',
|
|
'overlay.slash_menu.submenu',
|
|
'page.database_cell_caret',
|
|
'root.canvas',
|
|
'desktop.explorer.display.group.',
|
|
'desktop.explorer.group_header.',
|
|
'desktop.explorer.group_select.',
|
|
'desktop.explorer.group_toggle.',
|
|
'desktop.explorer.pinned.add_option.',
|
|
'desktop.explorer.pinned.item.',
|
|
'desktop.explorer.pinned.remove.',
|
|
'desktop.explorer.quick_select.',
|
|
'desktop.explorer.quick_split.',
|
|
'desktop.explorer.quick_tab.',
|
|
'desktop.explorer.quick_trash.',
|
|
'chrome.edgeless_element_toolbar',
|
|
'chrome.edgeless_toolbar',
|
|
'chrome.edgeless_zoom',
|
|
'chrome.mode_switcher',
|
|
'desktop.explorer.display.body',
|
|
'desktop.explorer.display.icon',
|
|
'desktop.inspector.journal.conflict',
|
|
'desktop.trash.confirm.close.icon',
|
|
'desktop.trash.confirm.title',
|
|
'desktop.trash_prompt.close.icon',
|
|
'desktop.trash_prompt.title',
|
|
'overlay.attachment_toolbar',
|
|
'overlay.code_lang_picker',
|
|
'overlay.code_more_menu',
|
|
'overlay.equation_editor',
|
|
'overlay.format_toolbar',
|
|
'overlay.image_toolbar',
|
|
'overlay.keyboard_toolbar',
|
|
'overlay.linked_doc_menu',
|
|
'overlay.pdf_viewer',
|
|
'overlay.slash_menu',
|
|
'overlay.table_toolbar',
|
|
'desktop.explorer.display.prop.',
|
|
'desktop.inspector.frame.title.',
|
|
'desktop.sidebar.linked_doc.',
|
|
'edgeless.link_picker',
|
|
'desktop.settings.about.version.',
|
|
'desktop.settings.delete_workspace_confirm.body',
|
|
'desktop.settings.delete_workspace_confirm.close.icon',
|
|
'desktop.settings.delete_workspace_confirm.description',
|
|
'desktop.settings.delete_workspace_confirm.title',
|
|
'desktop.settings.storage.export',
|
|
'desktop.trash.select.',
|
|
]);
|
|
|
|
const WASM_MAGIC = new Uint8Array([0x00, 0x61, 0x73, 0x6d]);
|
|
const WASM_VERSION_1 = new Uint8Array([0x01, 0x00, 0x00, 0x00]);
|
|
const DATA_SECTION_ID = 11;
|
|
|
|
/**
|
|
* Returns whether `dir` exists and is a directory.
|
|
*
|
|
* @param {string} dir
|
|
* @returns {boolean}
|
|
*/
|
|
function isDirectory(dir) {
|
|
try {
|
|
return statSync(dir).isDirectory();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Collects all `.rs` files under `blocksuite/crates/<crate>/src/**` and
|
|
* `packages/frontend/desktop/src/**`.
|
|
*
|
|
* @param {string} repoRoot
|
|
* @returns {string[]}
|
|
*/
|
|
function collectRustSourceFiles(repoRoot) {
|
|
/** @type {string[]} */
|
|
const files = [];
|
|
const cratesRoot = join(repoRoot, 'blocksuite', 'crates');
|
|
const desktopSrc = join(repoRoot, 'packages', 'frontend', 'desktop', 'src');
|
|
const hasCrates = isDirectory(cratesRoot);
|
|
const hasDesktop = isDirectory(desktopSrc);
|
|
|
|
if (!hasCrates && !hasDesktop) {
|
|
throw new Error(`Cannot read Rust source directories under ${repoRoot}`);
|
|
}
|
|
|
|
/** @param {string} dir */
|
|
function walkRs(dir) {
|
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
const full = join(dir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
walkRs(full);
|
|
} else if (entry.isFile() && entry.name.endsWith('.rs')) {
|
|
files.push(full);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (hasCrates) {
|
|
for (const entry of readdirSync(cratesRoot, { withFileTypes: true })) {
|
|
if (!entry.isDirectory()) continue;
|
|
const srcDir = join(cratesRoot, entry.name, 'src');
|
|
if (isDirectory(srcDir)) {
|
|
walkRs(srcDir);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (hasDesktop) {
|
|
walkRs(desktopSrc);
|
|
}
|
|
|
|
return files;
|
|
}
|
|
|
|
const TEST_CFG_LINE = /^\s*#\[cfg\((?:test|all\(\s*test\b.*)\)\]\s*$/;
|
|
const MOD_DECL_LINE =
|
|
/^(\s*)(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*([;{])\s*$/;
|
|
|
|
/**
|
|
* Lists the module declarations of one Rust file. A declaration is test-only
|
|
* when a `#[cfg(test)]` or `#[cfg(all(test, ...))]` attribute precedes it.
|
|
* Inline test-only modules also report the line of the `}` that closes them,
|
|
* which rustfmt places at the indentation of the `mod` line.
|
|
*
|
|
* @param {string} file
|
|
* @param {string[]} lines
|
|
* @returns {Array<{ name: string, test: boolean, start: number, end: number }>}
|
|
*/
|
|
function moduleDeclarations(file, lines) {
|
|
const decls = [];
|
|
for (let i = 0; i < lines.length; i += 1) {
|
|
const match = MOD_DECL_LINE.exec(lines[i]);
|
|
if (!match) continue;
|
|
let start = i;
|
|
let test = false;
|
|
while (start > 0 && lines[start - 1].trim().startsWith('#[')) {
|
|
start -= 1;
|
|
test ||= TEST_CFG_LINE.test(lines[start]);
|
|
}
|
|
let end = i;
|
|
if (test && match[3] === '{') {
|
|
const close = match[1] + '}';
|
|
end = lines.indexOf(close, i + 1);
|
|
if (end === -1) {
|
|
throw new Error(
|
|
`${file}:${i + 1}: inline module ${match[2]} has no closing "${close}" line`
|
|
);
|
|
}
|
|
}
|
|
decls.push({ name: match[2], test, start, end });
|
|
}
|
|
return decls;
|
|
}
|
|
|
|
/**
|
|
* Returns the directory that holds the child module files of `file`.
|
|
*
|
|
* @param {string} file
|
|
*/
|
|
function childModuleDir(file) {
|
|
const name = basename(file);
|
|
return ['lib.rs', 'main.rs', 'mod.rs'].includes(name)
|
|
? dirname(file)
|
|
: join(dirname(file), name.slice(0, -'.rs'.length));
|
|
}
|
|
|
|
/**
|
|
* Reads the production text of every Rust source file. Files of test-only
|
|
* modules are left out: a module declared under `#[cfg(test)]` and every
|
|
* module below it. Inline `#[cfg(test)]` modules are cut out of the text that
|
|
* remains, so assertions in unit tests never keep a prefix alive.
|
|
*
|
|
* @param {string[]} files
|
|
* @returns {Map<string, string>}
|
|
*/
|
|
function readProductionSources(files) {
|
|
/** @type {Map<string, string[]>} */
|
|
const lines = new Map(
|
|
files.map(file => [file, readFileSync(file, 'utf8').split('\n')])
|
|
);
|
|
const decls = new Map(
|
|
files.map(file => [
|
|
file,
|
|
moduleDeclarations(file, /** @type {string[]} */ (lines.get(file))),
|
|
])
|
|
);
|
|
|
|
/** @type {string[]} */
|
|
const testRoots = [];
|
|
const isTestOnly = (/** @type {string} */ file) =>
|
|
testRoots.some(
|
|
root => file === root + '.rs' || file.startsWith(root + '/')
|
|
);
|
|
let grew = true;
|
|
while (grew) {
|
|
grew = false;
|
|
for (const file of files) {
|
|
const testFile = isTestOnly(file);
|
|
for (const decl of decls.get(file) ?? []) {
|
|
if (!decl.test && !testFile) continue;
|
|
const root = join(childModuleDir(file), decl.name);
|
|
if (!testRoots.includes(root)) {
|
|
testRoots.push(root);
|
|
grew = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @type {Map<string, string>} */
|
|
const sources = new Map();
|
|
for (const file of files) {
|
|
if (isTestOnly(file)) continue;
|
|
const kept = [...(lines.get(file) ?? [])];
|
|
let cutEnd = -1;
|
|
const cuts = [];
|
|
for (const decl of decls.get(file) ?? []) {
|
|
if (decl.test && decl.start > cutEnd) {
|
|
cuts.push(decl);
|
|
cutEnd = decl.end;
|
|
}
|
|
}
|
|
for (const cut of cuts.reverse()) {
|
|
kept.splice(cut.start, cut.end - cut.start + 1);
|
|
}
|
|
sources.set(file, kept.join('\n'));
|
|
}
|
|
return sources;
|
|
}
|
|
|
|
/**
|
|
* Checks that every prefix in `prefixes` appears at least once in Rust sources
|
|
* under `<repoRoot>/blocksuite/crates/<crate>/src/**` and
|
|
* `<repoRoot>/packages/frontend/desktop/src/**`.
|
|
*
|
|
* @param {{ repoRoot?: string, prefixes?: readonly string[] }} [options]
|
|
* @returns {{ ok: boolean, missing: string[], counts: Record<string, number>, scannedFiles: number }}
|
|
*/
|
|
export function verifySourcePrefixes(options = {}) {
|
|
const repoRoot = options.repoRoot ?? DEFAULT_REPO_ROOT;
|
|
const prefixes = options.prefixes ?? ZERO_IN_PRODUCTION;
|
|
const sources = readProductionSources(collectRustSourceFiles(repoRoot));
|
|
|
|
/** @type {Record<string, number>} */
|
|
const counts = Object.fromEntries(prefixes.map(prefix => [prefix, 0]));
|
|
for (const content of sources.values()) {
|
|
for (const prefix of prefixes) {
|
|
let from = 0;
|
|
while (true) {
|
|
const idx = content.indexOf(prefix, from);
|
|
if (idx === -1) break;
|
|
counts[prefix] += 1;
|
|
from = idx + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
const missing = prefixes.filter(prefix => counts[prefix] === 0);
|
|
return {
|
|
ok: missing.length === 0,
|
|
missing,
|
|
counts,
|
|
scannedFiles: sources.size,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Reads an unsigned LEB128 u32 from `bytes` within `[offset, end)`.
|
|
*
|
|
* @param {Uint8Array} bytes
|
|
* @param {number} offset
|
|
* @param {number} end
|
|
* @returns {{ value: number, next: number }}
|
|
*/
|
|
function readU32Leb(bytes, offset, end) {
|
|
let result = 0;
|
|
let shift = 0;
|
|
let pos = offset;
|
|
for (let count = 0; count < 5; count += 1) {
|
|
if (pos >= end) {
|
|
throw new Error(`Truncated unsigned LEB128 at byte offset ${offset}`);
|
|
}
|
|
const byte = bytes[pos++];
|
|
if (count === 4 && (byte & 0xf0) !== 0) {
|
|
throw new Error(`Unsigned LEB128 u32 overflow at byte offset ${offset}`);
|
|
}
|
|
result += (byte & 0x7f) * 2 ** shift;
|
|
if ((byte & 0x80) === 0) {
|
|
return { value: result, next: pos };
|
|
}
|
|
shift += 7;
|
|
}
|
|
throw new Error(`Overlong unsigned LEB128 at byte offset ${offset}`);
|
|
}
|
|
|
|
/**
|
|
* Skips a signed LEB128 integer of at most `maxBytes` within `[offset, end)`.
|
|
*
|
|
* @param {Uint8Array} bytes
|
|
* @param {number} offset
|
|
* @param {number} end
|
|
* @param {number} maxBytes
|
|
* @returns {number}
|
|
*/
|
|
function skipSignedLeb(bytes, offset, end, maxBytes) {
|
|
let pos = offset;
|
|
for (let count = 0; count < maxBytes; count += 1) {
|
|
if (pos >= end) {
|
|
throw new Error(`Truncated signed LEB128 at byte offset ${offset}`);
|
|
}
|
|
const byte = bytes[pos++];
|
|
if ((byte & 0x80) === 0) {
|
|
return pos;
|
|
}
|
|
}
|
|
throw new Error(`Overlong signed LEB128 at byte offset ${offset}`);
|
|
}
|
|
|
|
/**
|
|
* Skips a WebAssembly constant expression through its terminating `0x0b` opcode.
|
|
*
|
|
* @param {Uint8Array} bytes
|
|
* @param {number} offset
|
|
* @param {number} end
|
|
* @returns {number}
|
|
*/
|
|
function skipConstExpr(bytes, offset, end) {
|
|
let pos = offset;
|
|
while (pos < end) {
|
|
const opcode = bytes[pos++];
|
|
if (opcode === 0x0b) {
|
|
return pos;
|
|
}
|
|
if (opcode === 0x41) {
|
|
// i32.const
|
|
pos = skipSignedLeb(bytes, pos, end, 5);
|
|
} else if (opcode === 0x42) {
|
|
// i64.const
|
|
pos = skipSignedLeb(bytes, pos, end, 10);
|
|
} else if (opcode === 0x43) {
|
|
// f32.const
|
|
if (pos + 4 > end) {
|
|
throw new Error(`Truncated f32.const at byte offset ${pos - 1}`);
|
|
}
|
|
pos += 4;
|
|
} else if (opcode === 0x44) {
|
|
// f64.const
|
|
if (pos + 8 > end) {
|
|
throw new Error(`Truncated f64.const at byte offset ${pos - 1}`);
|
|
}
|
|
pos += 8;
|
|
} else if (opcode === 0x23 || opcode === 0xd2) {
|
|
// global.get / ref.func
|
|
pos = readU32Leb(bytes, pos, end).next;
|
|
} else if (opcode === 0xd0) {
|
|
// ref.null heaptype
|
|
pos = skipSignedLeb(bytes, pos, end, 5);
|
|
} else if (
|
|
opcode === 0x6a ||
|
|
opcode === 0x6b ||
|
|
opcode === 0x6c ||
|
|
opcode === 0x7c ||
|
|
opcode === 0x7d ||
|
|
opcode === 0x7e
|
|
) {
|
|
// Extended constant expression arithmetic (i32/i64 add/sub/mul)
|
|
} else if (opcode === 0xfd) {
|
|
// SIMD v128.const
|
|
const sub = readU32Leb(bytes, pos, end);
|
|
if (sub.value !== 0x0c) {
|
|
throw new Error(
|
|
`Unsupported SIMD opcode 0xfd 0x${sub.value.toString(16)} in constant expression`
|
|
);
|
|
}
|
|
if (sub.next + 16 > end) {
|
|
throw new Error(`Truncated v128.const at byte offset ${pos - 1}`);
|
|
}
|
|
pos = sub.next + 16;
|
|
} else {
|
|
throw new Error(
|
|
`Unsupported opcode 0x${opcode.toString(16)} in Data segment constant expression at byte offset ${pos - 1}`
|
|
);
|
|
}
|
|
}
|
|
throw new Error(
|
|
`Unterminated Data segment constant expression starting at byte offset ${offset}`
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Parses Section 11 (Data) from a WebAssembly binary and returns each data
|
|
* segment's independent payload slice.
|
|
*
|
|
* @param {Uint8Array} bytes
|
|
* @returns {{ segments: Array<{ index: number, mode: number, payload: Uint8Array }>, totalDataBytes: number }}
|
|
*/
|
|
export function extractWasmDataSegments(bytes) {
|
|
if (!(bytes instanceof Uint8Array) || bytes.length < 8) {
|
|
throw new Error('Wasm binary is shorter than the 8-byte header');
|
|
}
|
|
for (let i = 0; i < 4; i += 1) {
|
|
if (bytes[i] !== WASM_MAGIC[i]) {
|
|
throw new Error('Invalid Wasm magic header (expected \\0asm)');
|
|
}
|
|
}
|
|
for (let i = 0; i < 4; i += 1) {
|
|
if (bytes[4 + i] !== WASM_VERSION_1[i]) {
|
|
throw new Error('Unsupported Wasm binary version (expected version 1)');
|
|
}
|
|
}
|
|
|
|
let pos = 8;
|
|
/** @type {{ start: number, end: number } | null} */
|
|
let dataSection = null;
|
|
|
|
while (pos < bytes.length) {
|
|
const sectionId = bytes[pos++];
|
|
const sizeInfo = readU32Leb(bytes, pos, bytes.length);
|
|
const payloadStart = sizeInfo.next;
|
|
const payloadEnd = payloadStart + sizeInfo.value;
|
|
if (payloadEnd > bytes.length) {
|
|
throw new Error(
|
|
`Section ${sectionId} length ${sizeInfo.value} exceeds binary size ${bytes.length} at byte offset ${payloadStart}`
|
|
);
|
|
}
|
|
if (sectionId === DATA_SECTION_ID) {
|
|
if (dataSection !== null) {
|
|
throw new Error('Duplicate Wasm Section 11 (Data)');
|
|
}
|
|
dataSection = { start: payloadStart, end: payloadEnd };
|
|
}
|
|
pos = payloadEnd;
|
|
}
|
|
|
|
if (dataSection === null) {
|
|
throw new Error('Missing Wasm Section 11 (Data)');
|
|
}
|
|
if (dataSection.start === dataSection.end) {
|
|
throw new Error('Wasm Section 11 (Data) is empty');
|
|
}
|
|
|
|
const countInfo = readU32Leb(bytes, dataSection.start, dataSection.end);
|
|
const segmentCount = countInfo.value;
|
|
if (segmentCount === 0) {
|
|
throw new Error('Wasm Section 11 (Data) declares 0 data segments');
|
|
}
|
|
|
|
let segPos = countInfo.next;
|
|
/** @type {Array<{ index: number, mode: number, payload: Uint8Array }>} */
|
|
const segments = [];
|
|
let totalDataBytes = 0;
|
|
|
|
for (let index = 0; index < segmentCount; index += 1) {
|
|
const modeInfo = readU32Leb(bytes, segPos, dataSection.end);
|
|
const mode = modeInfo.value;
|
|
segPos = modeInfo.next;
|
|
|
|
if (mode === 0) {
|
|
// Active segment targeting memory 0.
|
|
segPos = skipConstExpr(bytes, segPos, dataSection.end);
|
|
} else if (mode === 1) {
|
|
// Passive segment: no memory index or offset expression.
|
|
} else if (mode === 2) {
|
|
// Active segment with explicit memory index.
|
|
const memIdxInfo = readU32Leb(bytes, segPos, dataSection.end);
|
|
segPos = skipConstExpr(bytes, memIdxInfo.next, dataSection.end);
|
|
} else {
|
|
throw new Error(
|
|
`Unsupported Wasm Data segment mode ${mode} at segment ${index}`
|
|
);
|
|
}
|
|
|
|
const lenInfo = readU32Leb(bytes, segPos, dataSection.end);
|
|
const dataStart = lenInfo.next;
|
|
const dataEnd = dataStart + lenInfo.value;
|
|
if (dataEnd > dataSection.end) {
|
|
throw new Error(
|
|
`Data segment ${index} length ${lenInfo.value} exceeds Section 11 bounds`
|
|
);
|
|
}
|
|
segments.push({
|
|
index,
|
|
mode,
|
|
payload: bytes.subarray(dataStart, dataEnd),
|
|
});
|
|
totalDataBytes += lenInfo.value;
|
|
segPos = dataEnd;
|
|
}
|
|
|
|
if (segPos !== dataSection.end) {
|
|
throw new Error(
|
|
`Trailing bytes in Wasm Section 11 (Data): parsed to ${segPos}, section ends at ${dataSection.end}`
|
|
);
|
|
}
|
|
if (totalDataBytes === 0) {
|
|
throw new Error('Wasm Section 11 (Data) contains 0 payload bytes');
|
|
}
|
|
|
|
return { segments, totalDataBytes };
|
|
}
|
|
|
|
/**
|
|
* Searches each Wasm Data segment payload independently for forbidden ASCII
|
|
* snapshot prefixes.
|
|
*
|
|
* @param {Uint8Array} bytes
|
|
* @param {readonly string[]} [prefixes]
|
|
*/
|
|
export function scanWasmDataPrefixes(bytes, prefixes = ZERO_IN_PRODUCTION) {
|
|
const sha256 = createHash('sha256').update(bytes).digest('hex');
|
|
const { segments, totalDataBytes } = extractWasmDataSegments(bytes);
|
|
|
|
/** @type {Array<{ prefix: string, count: number, firstSegment: number, firstOffset: number }>} */
|
|
const hits = [];
|
|
|
|
for (const prefix of prefixes) {
|
|
const needle = Buffer.from(prefix, 'ascii');
|
|
let count = 0;
|
|
let firstSegment = -1;
|
|
let firstOffset = -1;
|
|
|
|
for (const seg of segments) {
|
|
const hay = Buffer.from(
|
|
seg.payload.buffer,
|
|
seg.payload.byteOffset,
|
|
seg.payload.byteLength
|
|
);
|
|
let from = 0;
|
|
while (from <= hay.length - needle.length) {
|
|
const idx = hay.indexOf(needle, from);
|
|
if (idx === -1) break;
|
|
if (firstSegment === -1) {
|
|
firstSegment = seg.index;
|
|
firstOffset = idx;
|
|
}
|
|
count += 1;
|
|
from = idx + 1;
|
|
}
|
|
}
|
|
|
|
if (count > 0) {
|
|
hits.push({ prefix, count, firstSegment, firstOffset });
|
|
}
|
|
}
|
|
|
|
return {
|
|
ok: hits.length === 0,
|
|
sha256,
|
|
segmentCount: segments.length,
|
|
totalDataBytes,
|
|
hits,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* CLI entrypoint.
|
|
*
|
|
* @param {string[]} argv
|
|
*/
|
|
function main(argv) {
|
|
if (
|
|
argv.length === 0 ||
|
|
(argv.includes('--source-only') && argv.length !== 1)
|
|
) {
|
|
throw new Error(
|
|
'Usage: node scripts/check-snapshot-prefixes.mjs --source-only | <path/to/bundle_bg.wasm>...'
|
|
);
|
|
}
|
|
|
|
const sourceResult = verifySourcePrefixes();
|
|
if (!sourceResult.ok) {
|
|
throw new Error(
|
|
`Snapshot prefix liveness check failed across ${sourceResult.scannedFiles} Rust files. Missing prefixes: ${sourceResult.missing.join(', ')}`
|
|
);
|
|
}
|
|
|
|
if (argv[0] === '--source-only') {
|
|
console.log(
|
|
`Snapshot prefix source liveness check passed (${ZERO_IN_PRODUCTION.length}/${ZERO_IN_PRODUCTION.length} prefixes found across ${sourceResult.scannedFiles} Rust files).`
|
|
);
|
|
return;
|
|
}
|
|
|
|
/** @type {string[]} */
|
|
const failures = [];
|
|
for (const arg of argv) {
|
|
const wasmPath = resolve(arg);
|
|
const scan = scanWasmDataPrefixes(readFileSync(wasmPath));
|
|
if (!scan.ok) {
|
|
failures.push(
|
|
`Forbidden snapshot prefixes found in Wasm Section 11 (Data): ${wasmPath}`,
|
|
`SHA-256: ${scan.sha256}`,
|
|
...scan.hits.map(
|
|
hit =>
|
|
` - ${hit.prefix}: count=${hit.count}, first_segment=${hit.firstSegment}, first_offset=${hit.firstOffset}`
|
|
)
|
|
);
|
|
continue;
|
|
}
|
|
console.log(
|
|
`Wasm Section 11 snapshot prefix gate passed for ${wasmPath} (${ZERO_IN_PRODUCTION.length}/${ZERO_IN_PRODUCTION.length} prefixes at 0, ${scan.segmentCount} segments, ${scan.totalDataBytes} data bytes, sha256=${scan.sha256}).`
|
|
);
|
|
}
|
|
if (failures.length > 0) {
|
|
throw new Error(failures.join('\n'));
|
|
}
|
|
}
|
|
|
|
const isMain =
|
|
process.argv[1] &&
|
|
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
|
|
if (isMain) {
|
|
try {
|
|
main(process.argv.slice(2));
|
|
} catch (err) {
|
|
console.error(err instanceof Error ? err.message : String(err));
|
|
process.exitCode = 1;
|
|
}
|
|
}
|