veilmark
v0.2.0
Published
Blind image watermarking for the browser and Node (WebAssembly). Embed up to 256 bytes into RGBA pixels; extract with the same keys.
Maintainers
Readme
veilmark (web)
Blind image watermarking for the browser and Node, as a WebAssembly package with a
framework-free JavaScript/TypeScript wrapper. Embed 1–256 bytes (an opaque id) into
PNG/JPEG pixels; extract them later with the same two seeds —
no original image needed. The heavy lifting is Rust (veilmark-core);
this package is a zero-runtime-dependency JS layer around the wasm-bindgen build in pkg/.
- Works with Vite / webpack / Rollup (ESM), Node ≥ 18 (CommonJS), or a plain
<script>tag (single file, wasm inlined). - Canvas,
Blob, URL,ImageBitmapandOffscreenCanvashelpers, plus an off-main-thread worker API. - Same deterministic behaviour as the CLI:
standardsurvives JPEG ≥ 32 on the test page,light≈ 41.9 dB PSNR. - Screen watermark: one 256×256 tile to repeat over the viewport; every screenshot of the page then carries a four-byte id that can still be read after cropping, downscaling and JPEG compression (
screenTileBlob,packScreenId).
Install
npm i veilmark # after `cd web && npm install && npm run build` in this repoRequirements: WebAssembly + ES2020 (see Browser compatibility); Node ≥ 18.
Quick start (ESM / bundler)
import { init, createVeilMark, embedBlob, extractBlob, maxPayloadLen } from 'veilmark';
await init(); // fetches veilmark_wasm_bg.wasm next to the JS module
const wm = createVeilMark({ blockSeed: 1234, payloadSeed: 5678 }); // 'standard' by default
const file /* Blob */ = inputElement.files[0];
const marked /* Blob (PNG) */ = await embedBlob(file, wm, 'id-0000001');
objectUrl = URL.createObjectURL(marked); // show / download it
const { text, confidence } = await extractBlob(marked, wm); // 'id-0000001'Raw pixels work too, and are synchronous:
import { imageDataToRgba, rgbaToImageData } from 'veilmark';
const wm = createVeilMark({ blockSeed: 1234, payloadSeed: 5678, strength: 'strong' });
const out = wm.embedText(imageDataToRgba(imageData), imageData.width, imageData.height, 'id-0000001');
ctx.putImageData(rgbaToImageData(out, imageData.width, imageData.height), 0, 0);CommonJS (Node)
const { init, createVeilMark, embedRgba, extractRgba, capacity } = require('veilmark');
await init(); // reads dist/veilmark_wasm_bg.wasm from disk — no setup
const wm = createVeilMark({ blockSeed: 1234, payloadSeed: 5678 });
const marked = embedRgba(wm, rgba, 320, 240, 'id-0000001');
extractRgba(wm, marked, 320, 240).text; // 'id-0000001'Node has no canvas: decode/encode images with sharp / pngjs / canvas and pass RGBA bytes.
Classic <script> tag (IIFE, wasm inlined)
<script src="node_modules/veilmark/dist/veilmark.iife.js"></script>
<script>
// Auto-initialised on load (the wasm is embedded as base64). Works from file://.
const wm = VeilMark.createVeilMark({ blockSeed: 1234, payloadSeed: 5678 });
VeilMark.embedCanvas(canvas, wm, 'id-0000001'); // in place
const { text } = VeilMark.extractCanvas(canvas, wm); // 'id-0000001'
const blob = await VeilMark.embedBlob(file, wm, 'id-0000001'); // Promise<Blob>
</script>Screen watermark (the whole page)
The image watermark marks a file; the screen watermark marks the page. Repeat one tile
over the viewport — one to two grey levels deep, multiplied into the pixels — and every
screenshot of it carries a four-byte id, also after the screenshot is cropped, downscaled
and JPEG-compressed. Reading a screenshot is a CLI step (veilmark screen-extract).
import { init, packScreenId, screenTileBlob } from 'veilmark';
await init();
const id = packScreenId('123456'); // 1..=8 decimal digits → 4 bytes: 00 12 34 56
const blob = await screenTileBlob(id, { blockSeed: 1234, payloadSeed: 5678 }); // 256×256 PNG
const url = URL.createObjectURL(blob); // render once per id; revoke when it changes
const overlay = document.createElement('div');
Object.assign(overlay.style, {
position: 'fixed', inset: '0', zIndex: String(Number.MAX_SAFE_INTEGER),
pointerEvents: 'none', mixBlendMode: 'multiply', // composes INTO the captured pixels
backgroundImage: `url("${url}")`, backgroundRepeat: 'repeat',
backgroundSize: '256px 256px', imageRendering: 'pixelated',
});
document.body.append(overlay);Keep every rule of that style: multiply is what puts the tile into a screenshot (a
translucent overlay would only cover the page), background-size: 256px anchors it to CSS
pixels, pixelated keeps browser zoom and high-density displays from inventing grey levels.
The tile must stay a PNG. It is hard to make out on flat, light backgrounds and carries no
signal anywhere else. What survives is tabulated in
docs/robustness.md.
Workers
Embedding 1080p takes ~150 ms on the main thread; move it to a worker to keep the UI responsive.
import { init, createWorker, embedInWorker, extractInWorker, imageDataToRgba } from 'veilmark';
await init();
const worker = createWorker(); // new Worker(new URL('./worker.mjs', import.meta.url), { type: 'module' })
const pixels = imageDataToRgba(imageData).slice(); // the buffer is *transferred*; copy to keep `imageData`
const marked = await embedInWorker(worker, pixels, 1920, 1080, 'id-0000001', [1234, 5678], 'standard');
const { text, confidence } = await extractInWorker(worker, marked.slice(), 1920, 1080, [1234, 5678]);
worker.terminate();createWorker({ inline: true })uses a Blob worker built from the worker source inlined in the bundle — for bundlers that cannot handlenew URL(..., import.meta.url)worker paths.transfer: falsein the last argument copies instead of transferring.- Roll your own worker with
import 'veilmark/worker'(ornew URL('veilmark/dist/worker.mjs', import.meta.url)): messages are{ id, op: 'embed'|'extract', seeds, strength?, width, height, rgba, payload? }→{ id, ok: true, rgba? | extracted? }or{ id, ok: false, error }(seesrc/worker.ts). - Vite: add
optimizeDeps: { exclude: ['veilmark'] }andworker: { format: 'es' }(seeexamples/worker-demo).
API
| Export | Signature | Notes |
|---|---|---|
| init | (opts?: { wasmUrl?: InitInput }) => Promise<void> | Idempotent; concurrent calls share one load; retries after failure. wasmUrl: URL / Request / Response / bytes / WebAssembly.Module. |
| initSync | (module: SyncInitInput) => void | Bytes or compiled module. |
| isReady | () => boolean | True once init() resolved / initSync() returned. |
| createVeilMark | ({ blockSeed, payloadSeed, strength? }) => VeilMark | Seeds are u32 integers. strength: 'light' \| 'standard' \| 'strong' \| { d1, d2 }. |
| embedRgba | (wm, rgba, w, h, payload) => Uint8Array | New buffer; alpha preserved. payload: Uint8Array \| string. |
| embedRgbaInPlace | (wm, rgba, w, h, payload) => void | No allocation. |
| extractRgba | (wm, rgba, w, h) => Extracted | Throws E_NOT_DETECTED if absent. |
| packBitmap / unpackBitmap | (w, h, bits) => Uint8Array / (payload, w, h) => Uint8Array | 1-bit logo payload: row-major, MSB-first, 1 = ink. |
| bitmapCapacity / bitmapFromImage / bitmapToImageData | (w, h) => number / (img, opts?) => Promise<{width,height,bits}> / (bits, w, h) => ImageData | Pixel budget and image ↔ bitmap conversion. |
| embedImage | (img: HTMLImageElement \| ImageBitmap, wm, payload) => Promise<ImageData> | Decodes via createImageBitmap; image untouched. |
| embedCanvas | (canvas: HTMLCanvasElement \| OffscreenCanvas, wm, payload) => ImageData | In place (putImageData). |
| embedBlob | (blob, wm, payload, { type?: 'image/png' \| 'image/jpeg', quality? }) => Promise<Blob> | Default PNG. |
| embedUrl | (url, wm, payload, opts?) => Promise<Blob> | fetch(url, { mode: 'cors' }) → embedBlob. |
| extractImage / extractCanvas | (source, wm) => Extracted | Synchronous. |
| extractBlob / extractUrl | (source, wm) => Promise<Extracted> | |
| rgbaToImageData / imageDataToRgba | Uint8Array ↔ ImageData | Zero-copy views. |
| createWorker | (opts?: { inline?, wasmUrl? }) => Worker | Browser only. |
| embedInWorker | (worker, rgba, w, h, payload, seeds, strength?, { transfer?, wasmUrl? }?) => Promise<Uint8Array> | Input transferred by default. |
| extractInWorker | (worker, rgba, w, h, seeds, strength?, opts?) => Promise<WorkerExtracted> | text: string \| null. |
| packScreenId | (id: string) => Uint8Array | 1–8 decimal digits packed two per byte, zero-padded on the left; throws RangeError otherwise. |
| screenTileRgba | (payload, { blockSeed, payloadSeed }) => Uint8Array | The screen tile as 256×256 RGBA8. payload: 1–4 bytes. |
| screenTileImageData / screenTileBlob | (payload, seeds) => ImageData / Promise<Blob> | Same tile for a canvas / as a PNG Blob. |
| SCREEN_TILE_PX / SCREEN_MAX_PAYLOAD | 256 / 4 | Tile side in CSS px; largest tile payload in bytes. |
| capacity | (w, h) => number | Coded bits (= 4×4 LL blocks). |
| maxPayloadLen | (w, h) => number | Largest payload class that fits (8…256 bytes); 0 if none. |
| minImageSize | (len) => Uint32Array | [w, h] or empty. |
| presetSteps | (name) => Float64Array | [d1, d2] or empty. |
| version | () => string | Core crate version. |
| getErrorCode | (err) => ErrorCode \| undefined | Parses the E_* prefix. |
VeilMark (wasm class) exposes embedRgba, embedRgbaInPlace, embedText, extractRgba, extractRgb, extractRgbaBestEffort, extractRgbBestEffort, blockSoft, free() and static withStrength. Extracted has payload, payloadHex, text (string | undefined when not UTF-8), classBytes, ber, confidence, crcOk (false only for a best-effort read — a hint, not evidence), free().
Error codes
Thrown as Error whose message starts with the code: E_NOT_DETECTED: no valid watermark detected (best coded-bit error rate 12.3%); ….
| Code | Meaning |
|---|---|
| E_NOT_DETECTED | Nothing validates (CRC): unwatermarked image, wrong seeds, or destroyed watermark. Strength is not a key — a different preset may still decode, with lower confidence. |
| E_IMAGE_TOO_SMALL | Fewer LL blocks than the payload class needs (≈ 128×128 minimum). |
| E_IMAGE_TOO_LARGE | Above the pixel limit (67,108,864). |
| E_PAYLOAD | Empty, > 256 bytes, above this image's capacity (maxPayloadLen) — or > 4 bytes for the screen tile. |
| E_BUFFER_LENGTH | Buffer is not w*h*4 bytes. |
| E_EMPTY_IMAGE | Zero or negative width/height. |
| E_STRENGTH | Unknown preset or invalid { d1, d2 } (0 < d2 <= d1; embedding additionally needs d1 >= 8, d2 >= 4). |
CORS
getImageData() throws SecurityError on a canvas that has drawn a cross-origin image without CORS. Helpers rewrite that into a hint, but the fix is on your side:
<img src="https://cdn.example/photo.jpg" crossorigin="anonymous">
<!-- server must answer with Access-Control-Allow-Origin (or the image must be same-origin) -->embedUrl / extractUrl already fetch with mode: 'cors', so the server must send CORS headers too.
CSP
WebAssembly compilation needs script-src 'wasm-unsafe-eval' (or 'wasm-eval', Firefox ≥ 102):
Content-Security-Policy: script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:blob: in worker-src is only needed for createWorker({ inline: true }). The IIFE build compiles inline base64 bytes — same directive, no unsafe-eval.
Browser compatibility
WebAssembly + ES2020. Canvas helpers: Chrome/Edge 80+, Firefox 74+, Safari 13.1+
(embedBlob / embedImage / extractBlob need createImageBitmap: Safari 15+).
OffscreenCanvas is used when available, otherwise HTMLCanvasElement. The worker
helpers need module workers: Firefox 114+, Safari 15+. Node ≥ 18 for the CommonJS
build; Node has no canvas, so use the raw-buffer API there.
The generated veilmark_wasm.d.ts references [Symbol.dispose](). Under an
ES2020 lib that type does not exist, so tsc reports TS2550; either add
"lib": ["ES2020", "ESNext.Disposable", "DOM"] or set skipLibCheck: true.
The runtime itself does not use Symbol.dispose.
Bundler notes
- ESM default wasm URL:
new URL('./veilmark_wasm_bg.wasm', import.meta.url)— Vite, webpack 5 and Rollup emit the file as an asset automatically. If your setup rewritesimport.meta.url(e.g. Vite dependency pre-bundling), either exclude the package or pass the URL yourself:init({ wasmUrl: new URL('veilmark/dist/veilmark_wasm_bg.wasm', import.meta.url) }). file://: browsers refuse to fetch the wasm from disk — use the IIFE build orinitSync(bytes).- CJS in a browser bundler: without
fsthe default loader throws; passinit({ wasmUrl })orinitSync(bytes).
中文速览
veilmark 是 Rust 盲水印核心的 WebAssembly 封装(零运行时依赖),支持三种接入方式:ESM 打包器(import { init, createVeilMark, embedBlob } from 'veilmark',init() 默认用 new URL('./veilmark_wasm_bg.wasm', import.meta.url) 加载 wasm)、CommonJS(Node ≥ 18,init() 直接从磁盘读取 wasm,无需任何配置)和 传统 <script> 标签(dist/veilmark.iife.js 单文件,wasm 以 base64 内联,加载即初始化,file:// 可直接打开,全局变量 window.VeilMark)。
整页水印:screenTileBlob(packScreenId('123456'), seeds) 生成一张 256×256 的 PNG 瓦片,按上面的样式平铺在整个视口上(mix-blend-mode: multiply 把瓦片乘进像素、background-size: 256px 锚定 CSS 像素、image-rendering: pixelated、pointer-events: none、最高 z-index)。瓦片只有 1–2 个灰阶深,在平坦浅色底上很难看出来;整张截图被裁切、缩小、JPEG 压缩后,都能用 veilmark screen-extract 读回 4 字节 ID。载荷最多 4 字节:packScreenId 接受 1–8 位十进制数字、每字节两位;文本请用图片水印。
常用 API:createVeilMark({ blockSeed, payloadSeed, strength }) 创建引擎(strength 可选 light / standard / strong 或自定义 { d1, d2 });embedCanvas / extractCanvas 就地处理 canvas,embedBlob / extractBlob 处理图片文件(默认输出 PNG,可指定 JPEG 与质量),embedUrl / extractUrl 通过 fetch(..., { mode: 'cors' }) 取图;大图建议用 createWorker() + embedInWorker / extractInWorker 在 Worker 中处理(默认 transfer 像素缓冲区,零拷贝但会 detach 输入)。错误以 Error 抛出,message 以稳定错误码开头(E_NOT_DETECTED 未检测到水印 / 密钥不符,E_IMAGE_TOO_SMALL 图片过小,E_PAYLOAD 载荷超长,E_BUFFER_LENGTH 缓冲区长度不符,E_STRENGTH 强度参数非法等),可用 getErrorCode(err) 取码。
注意事项:跨域图片必须加 crossorigin="anonymous" 且服务端返回 CORS 头,否则 canvas 被污染无法读取像素;CSP 需放行 script-src 'wasm-unsafe-eval'(内联 Worker 还需 worker-src blob:``);载荷 1–256 字节,320×240 图片最多 64 字节,最小约 128×128;standard` 强度在测试页上可抗 JPEG ≥ 32。
Development
cd web
npm install # esbuild, typescript, @types/node (dev only)
npm run build # → dist/ (index.mjs, index.cjs, worker.mjs, veilmark.iife.js, *.d.ts, wasm)
npm test # Node smoke test across all formats + worker protocol + type-level consumer testtest/iife.html— open from disk; canvas → embed → extract with the IIFE build.test/browser.html— serveweb/over http and open it for a full in-browser check (helpers, both worker forms); results inwindow.__check.../examples/—vanilla-script-tag,vite-vue,vite-react,worker-demo.
pkg/ is generated by wasm-pack (scripts/build-wasm.sh) and is never modified by this package.
