Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(transfer): pack a guide into a portable .mimik bundle

davbiof0db166d01f5
diff --git a/src/core/transfer/__tests__/bundle.test.ts b/src/core/transfer/__tests__/bundle.test.ts
new file mode 100644
index 0000000..160e7cf
--- /dev/null
+++ b/src/core/transfer/__tests__/bundle.test.ts
@@ -0,0 +1,262 @@
+import { strFromU8, unzipSync } from 'fflate';
+import { describe, expect, it, vi } from 'vitest';
+import type { Guide, Screenshot, Step } from '@/core/guides/types';
+
+vi.mock('@/core/screenshot/render', () => ({
+ renderScreenshot: async () => new Blob(['pixels'], { type: 'image/webp' }),
+}));
+vi.mock('@/core/export/markdown-export', () => ({
+ // Echo the step text, not just the title: a title-only stub makes every
+ // assertion about README scrubbing vacuous.
+ exportGuideAsMarkdown: async (guide: Guide, steps: Step[]) =>
+ [`# ${guide.title}`, ...steps.map((s) => s.description)].join('\n'),
+}));
+
+import { DEFAULT_BUNDLE_OPTIONS, exportGuideAsBundle, trimUrl } from '../bundle';
+import { MANIFEST_PATH, parseManifest, README_PATH } from '../schema';
+import { SCRUB_PLACEHOLDER } from '../scrub';
+
+function makeGuide(): Guide {
+ return {
+ id: 'guide-1',
+ title: 'Reset a password',
+ createdAt: 1_700_000_000_000,
+ updatedAt: 1_700_000_000_000,
+ stepIds: ['step-1'],
+ starred: true,
+ deletedAt: null,
+ };
+}
+
+function makeStep(overrides: Partial<Step> = {}): Step {
+ return {
+ id: 'step-1',
+ guideId: 'guide-1',
+ index: 0,
+ description: 'Type "hunter2" in the password box',
+ action: 'input',
+ url: 'https://app.example.com/settings/security?token=secret#anchor',
+ timestamp: 1_700_000_000_000,
+ screenshotId: 'ss-1',
+ aiPending: true,
+ inputValue: 'hunter2',
+ ...overrides,
+ };
+}
+
+function makeScreenshot(): Screenshot {
+ return {
+ id: 'ss-1',
+ stepId: 'step-1',
+ blob: new Blob(['raw'], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 800,
+ height: 600,
+ };
+}
+
+async function unpack(blob: Blob) {
+ const entries = unzipSync(new Uint8Array(await blob.arrayBuffer()));
+ return { entries, manifest: parseManifest(JSON.parse(strFromU8(entries[MANIFEST_PATH]))) };
+}
+
+describe('trimUrl', () => {
+ const url = 'https://app.example.com/settings/security?token=secret#anchor';
+
+ it('keeps everything in full mode', () => {
+ expect(trimUrl(url, 'full')).toBe(url);
+ });
+
+ it('drops the query and fragment in path mode', () => {
+ expect(trimUrl(url, 'path')).toBe('https://app.example.com/settings/security');
+ });
+
+ it('keeps only the origin in origin mode', () => {
+ expect(trimUrl(url, 'origin')).toBe('https://app.example.com');
+ });
+
+ it('discards a URL it cannot parse rather than passing it through', () => {
+ expect(trimUrl('not a url', 'path')).toBe('');
+ });
+});
+
+describe('exportGuideAsBundle', () => {
+ it('writes a manifest, the screenshots and a readable markdown copy', async () => {
+ const { entries, manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ expect(Object.keys(entries).sort()).toEqual([README_PATH, MANIFEST_PATH, 'screenshots/ss-1.webp']);
+ expect(strFromU8(entries[README_PATH])).toContain('# Reset a password');
+ expect(manifest.guide.title).toBe('Reset a password');
+ expect(manifest.screenshots[0].file).toBe('screenshots/ss-1.webp');
+ });
+
+ it('scrubs the typed value out of the description, not just the inputValue field', async () => {
+ const { entries, manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ // The capture pipeline writes the value into the description as well, so
+ // dropping inputValue alone would still ship the secret.
+ expect(JSON.stringify(manifest)).not.toContain('hunter2');
+ expect(manifest.steps[0].description).toBe(`Type "${SCRUB_PLACEHOLDER}" in the password box`);
+ expect(strFromU8(entries[README_PATH])).not.toContain('hunter2');
+ });
+
+ it('scrubs a title that quotes the typed value', async () => {
+ const guide = { ...makeGuide(), title: 'Set hunter2 as the password', description: 'Uses hunter2 throughout' };
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(guide, [makeStep()], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ expect(manifest.guide.title).toBe(`Set ${SCRUB_PLACEHOLDER} as the password`);
+ expect(manifest.guide.description).toBe(`Uses ${SCRUB_PLACEHOLDER} throughout`);
+ });
+
+ it('scrubs a typed value echoed by a different step', async () => {
+ const later = makeStep({ id: 'step-2', index: 1, description: 'Confirm hunter2 was saved', inputValue: undefined });
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep(), later], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ expect(manifest.steps[1].description).toBe(`Confirm ${SCRUB_PLACEHOLDER} was saved`);
+ });
+
+ it('leaves descriptions intact when the author keeps typed text', async () => {
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', makeScreenshot()]]), {
+ ...DEFAULT_BUNDLE_OPTIONS,
+ stripInputValues: false,
+ }),
+ );
+
+ expect(manifest.steps[0].description).toBe('Type "hunter2" in the password box');
+ });
+
+ it('strips typed text and trims URLs by default', async () => {
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ expect(manifest.steps[0].inputValue).toBeUndefined();
+ expect(manifest.steps[0].url).toBe('https://app.example.com/settings/security');
+ expect(manifest.redacted).toEqual({ screenshots: false, inputValues: true, urls: 'path' });
+ });
+
+ it('keeps typed text when the author opts in', async () => {
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', makeScreenshot()]]), {
+ ...DEFAULT_BUNDLE_OPTIONS,
+ stripInputValues: false,
+ urls: 'full',
+ }),
+ );
+
+ expect(manifest.steps[0].inputValue).toBe('hunter2');
+ expect(manifest.steps[0].url).toContain('token=secret');
+ });
+
+ it('leaves capture-local state behind', async () => {
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ const step = manifest.steps[0] as Record<string, unknown>;
+ expect(step.guideId).toBeUndefined();
+ expect(step.aiPending).toBeUndefined();
+ expect(step.screenshotId).toBeUndefined();
+ });
+
+ it('trims the href inside elementMeta too', async () => {
+ const step = makeStep({
+ elementMeta: {
+ tag: 'a',
+ cssSelector: 'a.link',
+ textContent: 'Security',
+ ariaLabel: null,
+ placeholder: null,
+ altText: null,
+ name: null,
+ role: null,
+ href: 'https://app.example.com/go?session=abc',
+ inputType: null,
+ dataTestId: null,
+ rect: { x: 0, y: 0, width: 10, height: 10 },
+ devicePixelRatio: 1,
+ },
+ });
+
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [step], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ expect(manifest.steps[0].elementMeta?.href).toBe('https://app.example.com/go');
+ });
+
+ it('reports a redaction in the manifest so the import screen can disclose it', async () => {
+ const shot = makeScreenshot();
+ shot.edits = { annotations: [{ id: 'r1', type: 'redact', x: 1, y: 2, w: 3, h: 4, style: 'blur' }] };
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', shot]])),
+ );
+
+ expect(manifest.redacted.screenshots).toBe(true);
+ });
+
+ it('does not claim a redaction when the author only cropped', async () => {
+ const shot = makeScreenshot();
+ shot.edits = { viewport: { x: 10, y: 10, width: 100, height: 100 } };
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [makeStep()], new Map([['step-1', shot]])),
+ );
+
+ expect(manifest.redacted.screenshots).toBe(false);
+ });
+
+ it('leaves an opaque-origin URL whole instead of turning it into "null/..."', async () => {
+ expect(trimUrl('file:///Users/x/doc.html', 'path')).toBe('file:///Users/x/doc.html');
+ expect(trimUrl('about:blank', 'origin')).toBe('about:blank');
+ expect(trimUrl('chrome://extensions/', 'path')).toBe('chrome://extensions/');
+ });
+
+ it('drops the captured text of the field that was typed into', async () => {
+ // getCleanText stores a truncated copy, so scrubbing the full value misses it.
+ const long = 'x'.repeat(200);
+ const step = makeStep({
+ inputValue: long,
+ description: 'Type into the box',
+ elementMeta: {
+ tag: 'div',
+ cssSelector: 'div.editor',
+ textContent: long.slice(0, 80),
+ ariaLabel: 'Message',
+ placeholder: null,
+ altText: null,
+ name: null,
+ role: 'textbox',
+ href: null,
+ inputType: null,
+ dataTestId: null,
+ rect: { x: 0, y: 0, width: 10, height: 10 },
+ devicePixelRatio: 1,
+ },
+ });
+
+ const { manifest } = await unpack(
+ await exportGuideAsBundle(makeGuide(), [step], new Map([['step-1', makeScreenshot()]])),
+ );
+
+ expect(manifest.steps[0].elementMeta?.textContent).toBeNull();
+ expect(JSON.stringify(manifest)).not.toContain('xxxxxxxxxx');
+ // The signals Guide Me actually matches on survive.
+ expect(manifest.steps[0].elementMeta?.ariaLabel).toBe('Message');
+ expect(manifest.steps[0].elementMeta?.cssSelector).toBe('div.editor');
+ });
+
+ it('handles a step with no screenshot', async () => {
+ const { manifest } = await unpack(await exportGuideAsBundle(makeGuide(), [makeStep()], new Map()));
+ expect(manifest.screenshots).toEqual([]);
+ expect(manifest.steps).toHaveLength(1);
+ });
+});
diff --git a/src/core/transfer/__tests__/flatten.test.ts b/src/core/transfer/__tests__/flatten.test.ts
new file mode 100644
index 0000000..70d1c76
--- /dev/null
+++ b/src/core/transfer/__tests__/flatten.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Screenshot } from '@/core/guides/types';
+import type { Annotation } from '@/core/screenshot/types';
+
+const renderScreenshot = vi.hoisted(() => vi.fn(async () => new Blob(['rendered'], { type: 'image/webp' })));
+vi.mock('@/core/screenshot/render', () => ({ renderScreenshot }));
+
+import { flattenScreenshot } from '../flatten';
+
+function makeScreenshot(overrides: Partial<Screenshot> = {}): Screenshot {
+ return {
+ id: 'ss-1',
+ stepId: 'step-1',
+ blob: new Blob(['raw'], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 1000,
+ height: 800,
+ ...overrides,
+ };
+}
+
+const redaction: Annotation = { id: 'r1', type: 'redact', x: 100, y: 120, w: 60, h: 20, style: 'blur' };
+const box: Annotation = { id: 'b1', type: 'box', x: 200, y: 240, w: 80, h: 40, color: '#000' };
+
+describe('flattenScreenshot', () => {
+ it('bakes redactions into the pixels and drops them from the edits', async () => {
+ const { meta, redacted } = await flattenScreenshot(makeScreenshot({ edits: { annotations: [redaction, box] } }));
+
+ expect(renderScreenshot).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ annotations: 'redactions' }),
+ );
+ expect(meta.edits?.annotations).toEqual([box]);
+ expect(redacted).toBe(true);
+ });
+
+ it('returns the rendered blob, never the raw capture', async () => {
+ const screenshot = makeScreenshot({ edits: { annotations: [redaction] } });
+ const { blob } = await flattenScreenshot(screenshot);
+
+ expect(await blob.text()).toBe('rendered');
+ expect(blob).not.toBe(screenshot.blob);
+ expect(await blob.text()).not.toContain('raw');
+ });
+
+ it('reports a crop alone as non-redacted, so the recipient is not told otherwise', async () => {
+ const { redacted } = await flattenScreenshot(
+ makeScreenshot({ edits: { viewport: { x: 10, y: 10, width: 100, height: 100 }, annotations: [box] } }),
+ );
+ expect(redacted).toBe(false);
+ });
+
+ it('renders the full frame when there is no explicit crop, so the auto-zoom still travels as data', async () => {
+ const screenshot = makeScreenshot({ bounds: { x: 10, y: 20, width: 30, height: 40 }, pixelRatio: 2 });
+ const { meta } = await flattenScreenshot(screenshot);
+
+ expect(renderScreenshot).toHaveBeenCalledWith(
+ screenshot,
+ expect.objectContaining({ viewport: { x: 0, y: 0, width: 1000, height: 800 } }),
+ );
+ expect(meta.bounds).toEqual({ x: 10, y: 20, width: 30, height: 40 });
+ expect(meta.width).toBe(1000);
+ });
+
+ it('reports a clean screenshot as non-redacted', async () => {
+ const { redacted } = await flattenScreenshot(makeScreenshot({ edits: { annotations: [box] } }));
+ expect(redacted).toBe(false);
+ });
+
+ describe('with an explicit crop', () => {
+ const crop = { x: 100, y: 50, width: 400, height: 300 };
+
+ it('bakes the crop and rebases the annotations that survive it', async () => {
+ const { meta, redacted } = await flattenScreenshot(
+ makeScreenshot({ edits: { viewport: crop, annotations: [box, redaction] } }),
+ );
+
+ expect(renderScreenshot).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ viewport: crop }));
+ expect(meta.width).toBe(400);
+ expect(meta.height).toBe(300);
+ expect(meta.edits?.viewport).toBeUndefined();
+ expect(meta.edits?.annotations).toEqual([{ ...box, x: 100, y: 190 }]);
+ expect(redacted).toBe(true);
+ });
+
+ it('resolves the target once and drops the pre-crop bounds it came from', async () => {
+ const { meta } = await flattenScreenshot(
+ makeScreenshot({
+ bounds: { x: 150, y: 100, width: 50, height: 25 },
+ pixelRatio: 2,
+ edits: { viewport: crop },
+ }),
+ );
+
+ // bounds are CSS pixels: 150 * 2 = 300 device px, then rebased by the crop's x.
+ expect(meta.edits?.target).toMatchObject({ x: 200, y: 150, width: 100, height: 50 });
+ expect(meta.bounds).toBeUndefined();
+ expect(meta.pixelRatio).toBeUndefined();
+ });
+
+ it('keeps the alt text', async () => {
+ const { meta } = await flattenScreenshot(makeScreenshot({ edits: { viewport: crop, alt: 'the save button' } }));
+ expect(meta.edits?.alt).toBe('the save button');
+ });
+ });
+});
diff --git a/src/core/transfer/__tests__/parse.test.ts b/src/core/transfer/__tests__/parse.test.ts
new file mode 100644
index 0000000..1c5b6af
--- /dev/null
+++ b/src/core/transfer/__tests__/parse.test.ts
@@ -0,0 +1,275 @@
+import { strToU8, zipSync } from 'fflate';
+import { describe, expect, it } from 'vitest';
+import { readBundle } from '../parse';
+import { BUNDLE_VERSION, type BundleError, MANIFEST_PATH, parseManifest } from '../schema';
+
+function manifest(overrides: Record<string, unknown> = {}) {
+ return {
+ version: BUNDLE_VERSION,
+ exportedAt: 1_700_000_000_000,
+ guide: { title: 'Reset a password', createdAt: 1_700_000_000_000 },
+ sourceDomain: 'app.example.com',
+ redacted: { screenshots: true, inputValues: true, urls: 'path' },
+ steps: [{ id: 'step-1', index: 0, description: 'Click save', action: 'click', url: '', timestamp: 1 }],
+ screenshots: [
+ {
+ id: 'ss-1',
+ stepId: 'step-1',
+ file: 'screenshots/ss-1.webp',
+ mimeType: 'image/webp',
+ width: 800,
+ height: 600,
+ },
+ ],
+ ...overrides,
+ };
+}
+
+function bundleFile(files: Record<string, Uint8Array>) {
+ return new Blob([zipSync(files) as unknown as BlobPart]);
+}
+
+const caught = async (file: Blob): Promise<BundleError> => {
+ try {
+ await readBundle(file);
+ } catch (err) {
+ return err as BundleError;
+ }
+ throw new Error('expected readBundle to throw');
+};
+
+describe('parseManifest', () => {
+ it('rejects a manifest from a newer Mimik rather than guessing at it', () => {
+ expect(() => parseManifest(manifest({ version: BUNDLE_VERSION + 1 }))).toThrow(
+ expect.objectContaining({ kind: 'unsupported-version' }),
+ );
+ });
+
+ it('rejects a manifest with no usable steps', () => {
+ expect(() => parseManifest(manifest({ steps: [{ noId: true }] }))).toThrow(
+ expect.objectContaining({ kind: 'empty' }),
+ );
+ });
+
+ it('rejects something that is not a manifest at all', () => {
+ expect(() => parseManifest({ hello: 'world' })).toThrow(expect.objectContaining({ kind: 'not-a-bundle' }));
+ });
+
+ it('drops screenshot entries pointing outside the screenshots folder', () => {
+ const parsed = parseManifest(
+ manifest({
+ screenshots: [
+ { id: 'a', stepId: 'step-1', file: '../../etc/passwd', mimeType: 'image/webp', width: 1, height: 1 },
+ { id: 'b', stepId: 'step-1', file: 'screenshots/ok.webp', mimeType: 'image/webp', width: 1, height: 1 },
+ ],
+ }),
+ );
+ expect(parsed.screenshots.map((s) => s.id)).toEqual(['b']);
+ });
+
+ it('drops screenshots whose step is not in the manifest', () => {
+ const parsed = parseManifest(
+ manifest({
+ screenshots: [
+ { id: 'a', stepId: 'ghost', file: 'screenshots/a.webp', mimeType: 'image/webp', width: 1, height: 1 },
+ ],
+ }),
+ );
+ expect(parsed.screenshots).toEqual([]);
+ });
+
+ it('drops malformed annotations instead of replaying a half-built redaction', () => {
+ const parsed = parseManifest(
+ manifest({
+ screenshots: [
+ {
+ id: 'a',
+ stepId: 'step-1',
+ file: 'screenshots/a.webp',
+ mimeType: 'image/webp',
+ width: 1,
+ height: 1,
+ edits: {
+ annotations: [
+ { id: 'bad', type: 'redact', x: 1, y: 2 },
+ { id: 'good', type: 'redact', x: 1, y: 2, w: 3, h: 4, style: 'blur' },
+ ],
+ },
+ },
+ ],
+ }),
+ );
+ expect(parsed.screenshots[0].edits?.annotations?.map((a) => a.id)).toEqual(['good']);
+ });
+
+ it('rejects a traversal that starts inside the screenshots folder', () => {
+ const parsed = parseManifest(
+ manifest({
+ screenshots: [
+ {
+ id: 'a',
+ stepId: 'step-1',
+ file: 'screenshots/../../evil.webp',
+ mimeType: 'image/webp',
+ width: 1,
+ height: 1,
+ },
+ {
+ id: 'b',
+ stepId: 'step-1',
+ file: 'screenshots\\..\\evil.webp',
+ mimeType: 'image/webp',
+ width: 1,
+ height: 1,
+ },
+ { id: 'c', stepId: 'step-1', file: 'screenshots/ok.webp', mimeType: 'image/webp', width: 1, height: 1 },
+ ],
+ }),
+ );
+ expect(parsed.screenshots.map((s) => s.id)).toEqual(['c']);
+ });
+
+ it('refuses a mime type that is not an image', () => {
+ const parsed = parseManifest(
+ manifest({
+ screenshots: [
+ { id: 'a', stepId: 'step-1', file: 'screenshots/a.webp', mimeType: 'text/html', width: 1, height: 1 },
+ ],
+ }),
+ );
+ // Otherwise it becomes a blob: URL in the extension origin, and the
+ // extension of whatever "Download original" writes to disk.
+ expect(parsed.screenshots[0].mimeType).toBe('image/webp');
+ });
+
+ it('drops a javascript: url rather than letting it reach an href', () => {
+ const parsed = parseManifest(
+ manifest({
+ steps: [
+ {
+ id: 's',
+ index: 0,
+ description: 'x',
+ action: 'click',
+ url: 'javascript:fetch("https://evil.tld")',
+ timestamp: 1,
+ elementMeta: { tag: 'a', cssSelector: 'a', href: 'javascript:alert(1)' },
+ },
+ ],
+ }),
+ );
+ expect(parsed.steps[0].url).toBe('');
+ expect(parsed.steps[0].elementMeta?.href).toBeNull();
+ });
+
+ it('clamps absurd screenshot dimensions instead of sizing a canvas from them', () => {
+ const parsed = parseManifest(
+ manifest({
+ screenshots: [
+ { id: 'a', stepId: 'step-1', file: 'screenshots/a.webp', mimeType: 'image/webp', width: 5e9, height: 5e9 },
+ ],
+ }),
+ );
+ expect(parsed.screenshots[0].width).toBeLessThanOrEqual(32_768);
+ expect(parsed.screenshots[0].height).toBeLessThanOrEqual(32_768);
+ });
+
+ it("enforces the manifest's own claim that typed values were stripped", () => {
+ const parsed = parseManifest(
+ manifest({
+ redacted: { screenshots: false, inputValues: true, urls: 'path' },
+ steps: [{ id: 's', index: 0, description: 'x', action: 'input', url: '', timestamp: 1, inputValue: 'hunter2' }],
+ }),
+ );
+ // The recipient is shown the claim, so it is enforced rather than trusted β€”
+ // Guide Me would otherwise replay the value into a live page.
+ expect(parsed.steps[0].inputValue).toBeUndefined();
+ });
+
+ it('keeps typed values when the bundle does not claim to have stripped them', () => {
+ const parsed = parseManifest(
+ manifest({
+ redacted: { screenshots: false, inputValues: false, urls: 'full' },
+ steps: [{ id: 's', index: 0, description: 'x', action: 'input', url: '', timestamp: 1, inputValue: 'hunter2' }],
+ }),
+ );
+ expect(parsed.steps[0].inputValue).toBe('hunter2');
+ });
+
+ it('drops a text annotation with no size, which would compute NaN geometry', () => {
+ const withAnnotations = (annotations: unknown[]) =>
+ parseManifest(
+ manifest({
+ screenshots: [
+ {
+ id: 'a',
+ stepId: 'step-1',
+ file: 'screenshots/a.webp',
+ mimeType: 'image/webp',
+ width: 1,
+ height: 1,
+ edits: { annotations },
+ },
+ ],
+ }),
+ ).screenshots[0].edits?.annotations;
+
+ expect(withAnnotations([{ id: 'bad', type: 'text', x: 1, y: 2, text: 'hi', color: '#000' }])).toBeUndefined();
+ expect(
+ withAnnotations([{ id: 'ok', type: 'text', x: 1, y: 2, text: 'hi', color: '#000', size: 32 }])?.map((a) => a.id),
+ ).toEqual(['ok']);
+ expect(withAnnotations([{ id: 'empty', type: 'freehand', points: [], color: '#000' }])).toBeUndefined();
+ expect(withAnnotations([{ id: 'odd', type: 'freehand', points: [1, 2, 3], color: '#000' }])).toBeUndefined();
+ });
+
+ it('orders steps by their recorded index', () => {
+ const parsed = parseManifest(
+ manifest({
+ steps: [
+ { id: 'b', index: 1, description: 'second', action: 'click', url: '', timestamp: 2 },
+ { id: 'a', index: 0, description: 'first', action: 'click', url: '', timestamp: 1 },
+ ],
+ }),
+ );
+ expect(parsed.steps.map((s) => s.id)).toEqual(['a', 'b']);
+ });
+});
+
+describe('readBundle', () => {
+ it('pairs each manifest screenshot with its image', async () => {
+ const file = bundleFile({
+ [MANIFEST_PATH]: strToU8(JSON.stringify(manifest())),
+ 'screenshots/ss-1.webp': strToU8('pixels'),
+ });
+
+ const { manifest: parsed, images } = await readBundle(file);
+ expect(parsed.guide.title).toBe('Reset a password');
+ expect(images.get('screenshots/ss-1.webp')).toBeInstanceOf(Blob);
+ });
+
+ it('tolerates a manifest pointing at an image the archive does not have', async () => {
+ const { images } = await readBundle(bundleFile({ [MANIFEST_PATH]: strToU8(JSON.stringify(manifest())) }));
+ expect(images.size).toBe(0);
+ });
+
+ it('reports a file that is not a zip', async () => {
+ expect((await caught(new Blob(['just some text']))).kind).toBe('unreadable');
+ });
+
+ it('reports a zip with no manifest', async () => {
+ expect((await caught(bundleFile({ 'readme.txt': strToU8('hi') }))).kind).toBe('not-a-bundle');
+ });
+
+ it('refuses a zip bomb before inflating it', async () => {
+ // 400MB of zeros compresses to a few hundred KB; the guard must fire on the
+ // declared sizes, not on the memory it would otherwise already hold.
+ const huge = new Uint8Array(210 * 1024 * 1024);
+ const bomb = bundleFile({ [MANIFEST_PATH]: strToU8(JSON.stringify(manifest())), 'screenshots/big.webp': huge });
+ expect(bomb.size).toBeLessThan(5 * 1024 * 1024);
+ expect((await caught(bomb)).kind).toBe('unreadable');
+ });
+
+ it('reports a manifest that is not valid JSON', async () => {
+ expect((await caught(bundleFile({ [MANIFEST_PATH]: strToU8('{ nope') }))).kind).toBe('not-a-bundle');
+ });
+});
diff --git a/src/core/transfer/__tests__/scrub.test.ts b/src/core/transfer/__tests__/scrub.test.ts
new file mode 100644
index 0000000..4cc68e1
--- /dev/null
+++ b/src/core/transfer/__tests__/scrub.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import { MIN_BARE_SCRUB, SCRUB_PLACEHOLDER, scrubValues, typedValues } from '../scrub';
+
+describe('scrubValues', () => {
+ it('removes the value from the description the capture pipeline writes', () => {
+ const description = 'Type "hunter2-secret-value" in Search with DuckDuckGo';
+ expect(scrubValues(description, ['hunter2-secret-value'])).toBe(
+ `Type "${SCRUB_PLACEHOLDER}" in Search with DuckDuckGo`,
+ );
+ });
+
+ it('removes a bare occurrence an AI description could have written', () => {
+ expect(scrubValues('Search for hunter2-secret-value and open the result', ['hunter2-secret-value'])).toBe(
+ `Search for ${SCRUB_PLACEHOLDER} and open the result`,
+ );
+ });
+
+ it('removes every occurrence, not just the first', () => {
+ const out = scrubValues('Type "sekrit" then check sekrit appears', ['sekrit']);
+ expect(out).not.toContain('sekrit');
+ });
+
+ it('ignores case, since a rewritten description may recapitalise', () => {
+ expect(scrubValues('The value Sekrit-Value was entered', ['sekrit-value'])).toBe(
+ `The value ${SCRUB_PLACEHOLDER} was entered`,
+ );
+ });
+
+ it('treats the value as text, not as a pattern', () => {
+ expect(scrubValues('Type "a.b*c" in Field', ['a.b*c'])).toBe(`Type "${SCRUB_PLACEHOLDER}" in Field`);
+ expect(scrubValues('Type "axbyc" in Field', ['a.b*c'])).toContain('axbyc');
+ });
+
+ it('quotes the short value but leaves the prose around it alone', () => {
+ const short = 'no';
+ expect(short.length).toBeLessThan(MIN_BARE_SCRUB);
+
+ const out = scrubValues('Type "no" in Comment, then note it is not done', [short]);
+ expect(out).toBe(`Type "${SCRUB_PLACEHOLDER}" in Comment, then note it is not done`);
+ expect(out).toContain('note it is not done');
+ });
+
+ it('scrubs a longer value before the shorter one it contains', () => {
+ const out = scrubValues(
+ 'Type "acme-corp-token" in Key',
+ typedValues([{ inputValue: 'acme' }, { inputValue: 'acme-corp-token' }]),
+ );
+ expect(out).toBe(`Type "${SCRUB_PLACEHOLDER}" in Key`);
+ });
+
+ it('leaves text untouched when there is nothing to scrub', () => {
+ expect(scrubValues('Click the Save button', [])).toBe('Click the Save button');
+ expect(scrubValues('Click the Save button', ['', ' '])).toBe('Click the Save button');
+ });
+});
+
+describe('typedValues', () => {
+ it('collects distinct values, longest first', () => {
+ expect(
+ typedValues([
+ { inputValue: 'short' },
+ { inputValue: 'a much longer value' },
+ { inputValue: 'short' },
+ {},
+ { inputValue: ' ' },
+ ]),
+ ).toEqual(['a much longer value', 'short']);
+ });
+});
diff --git a/src/core/transfer/bundle.ts b/src/core/transfer/bundle.ts
new file mode 100644
index 0000000..4be1e23
--- /dev/null
+++ b/src/core/transfer/bundle.ts
@@ -0,0 +1,157 @@
+import { strToU8, zipSync } from 'fflate';
+import { extractDomain } from '@/core/export/utils';
+import type { Guide, Screenshot, Step } from '@/core/guides/types';
+import { flattenScreenshot } from './flatten';
+import {
+ BUNDLE_MIME,
+ BUNDLE_VERSION,
+ type BundleManifest,
+ type BundleScreenshot,
+ type BundleStep,
+ MANIFEST_PATH,
+ README_PATH,
+ SCREENSHOT_DIR,
+} from './schema';
+import { scrubValues, typedValues } from './scrub';
+
+export type BundleUrlMode = 'full' | 'path' | 'origin';
+
+export interface BundleOptions {
+ /** Typed text can be a name, a token, or a password nobody meant to publish. */
+ stripInputValues: boolean;
+ urls: BundleUrlMode;
+}
+
+export const DEFAULT_BUNDLE_OPTIONS: BundleOptions = {
+ stripInputValues: true,
+ urls: 'path',
+};
+
+/** Query strings and fragments carry session tokens far more often than they carry meaning. */
+export function trimUrl(url: string, mode: BundleUrlMode): string {
+ if (mode === 'full' || !url) return url;
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return '';
+ }
+ // Opaque-origin schemes (file:, about:, chrome:) report an origin of the
+ // literal string "null", so composing origin + pathname would yield
+ // "null/Users/…". They have no host to trim down to, so leave them whole.
+ if (parsed.origin === 'null') return url;
+ return mode === 'origin' ? parsed.origin : `${parsed.origin}${parsed.pathname}`;
+}
+
+function bundleStep(step: Step, options: BundleOptions, secrets: readonly string[]): BundleStep {
+ const { guideId: _guideId, aiPending: _aiPending, screenshotId: _screenshotId, ...rest } = step;
+ const travelling: BundleStep = { ...rest, url: trimUrl(step.url, options.urls) };
+
+ if (options.stripInputValues) {
+ delete travelling.inputValue;
+ // The value is also written into the description at capture time, and an AI
+ // description can quote it again. Removing one copy and shipping the other
+ // would make the setting a lie.
+ travelling.description = scrubValues(travelling.description, secrets);
+ }
+
+ if (travelling.elementMeta) {
+ const meta = travelling.elementMeta;
+ // For the field that was typed into, the captured text *is* the typed value β€”
+ // stored truncated, so a literal scrub can miss it. Drop it outright: Guide Me
+ // matches a field on its selector, label and placeholder, never on the text
+ // the author happened to put in it.
+ const ownText = options.stripInputValues && step.inputValue ? null : meta.textContent;
+ travelling.elementMeta = {
+ ...meta,
+ href: meta.href ? trimUrl(meta.href, options.urls) : null,
+ textContent: ownText && options.stripInputValues ? scrubValues(ownText, secrets) : ownText,
+ };
+ }
+
+ return travelling;
+}
+
+/**
+ * Packs a guide into a `.mimik` zip another Mimik can import.
+ *
+ * Screenshots are flattened first, so redactions are gone rather than merely
+ * hidden. A plain-markdown `README.md` rides along so the file still says
+ * something to someone who does not have Mimik installed.
+ */
+export async function exportGuideAsBundle(
+ guide: Guide,
+ steps: Step[],
+ screenshots: Map<string, Screenshot>,
+ options: BundleOptions = DEFAULT_BUNDLE_OPTIONS,
+): Promise<Blob> {
+ const files: Record<string, Uint8Array | [Uint8Array, { level: 0 }]> = {};
+ const manifestScreenshots: BundleScreenshot[] = [];
+ let anyRedaction = false;
+
+ for (const step of steps) {
+ const screenshot = screenshots.get(step.id);
+ if (!screenshot) continue;
+
+ const { meta, blob, redacted } = await flattenScreenshot(screenshot);
+ anyRedaction ||= redacted;
+
+ const file = `${SCREENSHOT_DIR}/${meta.id}.webp`;
+ // Already-compressed webp: deflating it again costs time and saves nothing.
+ files[file] = [new Uint8Array(await blob.arrayBuffer()), { level: 0 }];
+
+ manifestScreenshots.push({
+ id: meta.id,
+ stepId: meta.stepId,
+ file,
+ mimeType: meta.mimeType,
+ width: meta.width,
+ height: meta.height,
+ ...(meta.bounds ? { bounds: meta.bounds } : {}),
+ ...(meta.pixelRatio !== undefined ? { pixelRatio: meta.pixelRatio } : {}),
+ ...(meta.clickPoint ? { clickPoint: meta.clickPoint } : {}),
+ ...(meta.edits ? { edits: meta.edits } : {}),
+ });
+ }
+
+ const secrets = options.stripInputValues ? typedValues(steps) : [];
+ const scrub = (text: string) => (options.stripInputValues ? scrubValues(text, secrets) : text);
+
+ const manifest: BundleManifest = {
+ version: BUNDLE_VERSION,
+ exportedAt: Date.now(),
+ guide: {
+ // An AI title is written from the step descriptions, so it can carry the
+ // typed value through even though nobody typed it into the title.
+ title: scrub(guide.title),
+ ...(guide.description ? { description: scrub(guide.description) } : {}),
+ createdAt: guide.createdAt,
+ },
+ sourceDomain: extractDomain(steps),
+ redacted: {
+ screenshots: anyRedaction,
+ inputValues: options.stripInputValues,
+ urls: options.urls,
+ },
+ steps: steps.map((step) => bundleStep(step, options, secrets)),
+ screenshots: manifestScreenshots,
+ };
+
+ files[MANIFEST_PATH] = strToU8(JSON.stringify(manifest, null, 2));
+
+ // The README is generated from the guide, so it needs the same scrubbing the
+ // manifest got β€” otherwise the value walks out in the readable copy instead.
+ const { exportGuideAsMarkdown } = await import('@/core/export/markdown-export');
+ const readmeGuide: Guide = {
+ ...guide,
+ title: manifest.guide.title,
+ ...(guide.description ? { description: scrub(guide.description) } : {}),
+ };
+ const readmeSteps = steps.map((step) => ({ ...step, description: scrub(step.description) }));
+ files[README_PATH] = strToU8(await exportGuideAsMarkdown(readmeGuide, readmeSteps, screenshots));
+
+ // Synchronous for the same reason as readBundle: the async variant needs a
+ // blob: Worker that Firefox's extension CSP blocks.
+ const zipped = zipSync(files);
+ return new Blob([zipped as unknown as BlobPart], { type: BUNDLE_MIME });
+}
diff --git a/src/core/transfer/flatten.ts b/src/core/transfer/flatten.ts
new file mode 100644
index 0000000..85d3dad
--- /dev/null
+++ b/src/core/transfer/flatten.ts
@@ -0,0 +1,93 @@
+import type { Screenshot } from '@/core/guides/types';
+import { moveAnnotation, resolveTarget } from '@/core/screenshot/geometry';
+import { renderScreenshot } from '@/core/screenshot/render';
+import type { ScreenshotEdits } from '@/core/screenshot/types';
+
+export interface FlattenedScreenshot {
+ meta: Omit<Screenshot, 'blob'>;
+ blob: Blob;
+ /**
+ * True only when a redaction was burnt in. A crop also destroys pixels, but
+ * the recipient is told "blurred areas were removed", and saying that about a
+ * screenshot the author merely zoomed would be a lie.
+ */
+ redacted: boolean;
+}
+
+const FORMAT = 'image/webp';
+const QUALITY = 0.9;
+
+/**
+ * Prepares a screenshot to leave this browser.
+ *
+ * A `redact` annotation is drawn at render time, so `screenshot.blob` still holds
+ * the unblurred capture underneath it. Shipping that blob would hand the recipient
+ * everything the author hid. So redactions are burnt into the pixels here and then
+ * dropped from `edits`, leaving nothing to undo.
+ *
+ * An explicit crop is baked for the same reason β€” framing is sometimes how people
+ * hide things. The automatic zoom-to-target crop is presentation rather than
+ * concealment, so it stays as data and travels untouched.
+ *
+ * Everything else β€” the target outline, boxes, arrows, text β€” stays editable.
+ */
+export async function flattenScreenshot(screenshot: Screenshot): Promise<FlattenedScreenshot> {
+ const crop = screenshot.edits?.viewport;
+ const frame = crop ?? { x: 0, y: 0, width: screenshot.width, height: screenshot.height };
+ const hadRedactions = (screenshot.edits?.annotations ?? []).some((a) => a.type === 'redact');
+
+ const blob = await renderScreenshot(screenshot, {
+ format: FORMAT,
+ quality: QUALITY,
+ viewport: frame,
+ target: false,
+ annotations: 'redactions',
+ });
+
+ const kept = (screenshot.edits?.annotations ?? []).filter((a) => a.type !== 'redact');
+ const edits: ScreenshotEdits = {};
+ if (screenshot.edits?.alt) edits.alt = screenshot.edits.alt;
+
+ if (!crop) {
+ if (kept.length > 0) edits.annotations = kept;
+ if (screenshot.edits?.target !== undefined) edits.target = screenshot.edits.target;
+
+ return {
+ meta: {
+ ...stripBlob(screenshot),
+ edits: Object.keys(edits).length > 0 ? edits : undefined,
+ },
+ blob,
+ redacted: hadRedactions,
+ };
+ }
+
+ // The crop is now the whole image, so every coordinate moves with it.
+ if (kept.length > 0) edits.annotations = kept.map((a) => moveAnnotation(a, -crop.x, -crop.y));
+
+ // `bounds` is in CSS pixels and only exists so the target and auto-crop can be
+ // derived. Resolve it once, rebase it, and drop the source β€” a rebased image
+ // must never be re-derived from pre-crop coordinates.
+ const target = resolveTarget(screenshot);
+ edits.target = target
+ ? { ...target, x: target.x - crop.x, y: target.y - crop.y }
+ : (screenshot.edits?.target ?? null);
+
+ return {
+ meta: {
+ id: screenshot.id,
+ stepId: screenshot.stepId,
+ mimeType: FORMAT,
+ width: Math.round(crop.width),
+ height: Math.round(crop.height),
+ edits,
+ },
+ blob,
+ redacted: hadRedactions,
+ };
+}
+
+function stripBlob(screenshot: Screenshot): Omit<Screenshot, 'blob' | 'edits'> {
+ const { blob: _blob, edits: _edits, ...rest } = screenshot;
+ return { ...rest, mimeType: FORMAT };
+}
diff --git a/src/core/transfer/parse.ts b/src/core/transfer/parse.ts
new file mode 100644
index 0000000..cf49b21
--- /dev/null
+++ b/src/core/transfer/parse.ts
@@ -0,0 +1,65 @@
+import { strFromU8, unzipSync } from 'fflate';
+import { BundleError, type BundleManifest, MANIFEST_PATH, parseManifest } from './schema';
+
+export interface ParsedBundle {
+ manifest: BundleManifest;
+ /** Zip entry path β†’ image, for the screenshots the manifest actually points at. */
+ images: Map<string, Blob>;
+}
+
+/** 200MB of decompressed entries is far past any real guide and well short of an OOM. */
+const MAX_UNPACKED_BYTES = 200 * 1024 * 1024;
+
+/** A compressed bundle this large is not a guide; reject before reading it into memory. */
+const MAX_FILE_BYTES = 100 * 1024 * 1024;
+
+/**
+ * Reads a `.mimik` file from disk. Everything in it is untrusted: the manifest is
+ * validated, entries it does not reference are ignored, and a file that is not a
+ * bundle fails with a reason the import screen can show.
+ */
+export async function readBundle(file: Blob): Promise<ParsedBundle> {
+ if (file.size > MAX_FILE_BYTES) throw new BundleError('unreadable', 'bundle is implausibly large');
+
+ let entries: Record<string, Uint8Array>;
+ try {
+ // Deliberately the synchronous API. fflate's async variant runs in a Worker
+ // built from a blob: URL, which Firefox's extension CSP refuses to execute β€”
+ // the callback then never fires and the import hangs on its spinner forever.
+ // Screenshots are stored uncompressed, so there is little to inflate anyway.
+ //
+ // The filter runs against the central directory before anything is inflated,
+ // so a zip bomb is refused while it is still a few kilobytes on disk. Summing
+ // the entries afterwards would only measure memory already committed.
+ let unpacked = 0;
+ entries = unzipSync(new Uint8Array(await file.arrayBuffer()), {
+ filter: (entry) => {
+ unpacked += entry.originalSize;
+ if (unpacked > MAX_UNPACKED_BYTES) throw new Error('bundle is implausibly large');
+ return true;
+ },
+ });
+ } catch {
+ throw new BundleError('unreadable', 'file could not be unzipped');
+ }
+
+ const manifestEntry = entries[MANIFEST_PATH];
+ if (!manifestEntry) throw new BundleError('not-a-bundle', `no ${MANIFEST_PATH} in the archive`);
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(strFromU8(manifestEntry));
+ } catch {
+ throw new BundleError('not-a-bundle', `${MANIFEST_PATH} is not valid JSON`);
+ }
+
+ const manifest = parseManifest(raw);
+
+ const images = new Map<string, Blob>();
+ for (const shot of manifest.screenshots) {
+ const entry = entries[shot.file];
+ if (entry) images.set(shot.file, new Blob([entry as unknown as BlobPart], { type: shot.mimeType }));
+ }
+
+ return { manifest, images };
+}
diff --git a/src/core/transfer/schema.ts b/src/core/transfer/schema.ts
new file mode 100644
index 0000000..b13b7b0
--- /dev/null
+++ b/src/core/transfer/schema.ts
@@ -0,0 +1,349 @@
+import type {
+ BlockType,
+ CalloutVariant,
+ DescriptionSource,
+ ElementMeta,
+ ScreenshotBounds,
+ Step,
+} from '@/core/guides/types';
+import type { Annotation, ScreenshotEdits } from '@/core/screenshot/types';
+
+/**
+ * Bump when the manifest shape changes. Readers reject anything newer than they
+ * understand rather than guessing at fields they have never seen.
+ */
+export const BUNDLE_VERSION = 1;
+
+export const BUNDLE_EXTENSION = 'mimik';
+export const BUNDLE_MIME = 'application/zip';
+export const MANIFEST_PATH = 'manifest.json';
+export const SCREENSHOT_DIR = 'screenshots';
+export const README_PATH = 'README.md';
+
+/** A step as it travels: no `guideId`, no transient capture state. */
+export type BundleStep = Omit<Step, 'guideId' | 'aiPending' | 'screenshotId'>;
+
+/** Screenshot metadata plus the zip entry holding its pixels. */
+export interface BundleScreenshot {
+ id: string;
+ stepId: string;
+ file: string;
+ mimeType: string;
+ width: number;
+ height: number;
+ bounds?: ScreenshotBounds;
+ pixelRatio?: number;
+ clickPoint?: { x: number; y: number };
+ edits?: ScreenshotEdits;
+}
+
+export interface BundleManifest {
+ version: number;
+ exportedAt: number;
+ guide: {
+ title: string;
+ description?: string;
+ createdAt: number;
+ };
+ sourceDomain: string | null;
+ /** What the exporter removed, so the import screen can say so. */
+ redacted: {
+ screenshots: boolean;
+ inputValues: boolean;
+ urls: 'full' | 'path' | 'origin';
+ };
+ steps: BundleStep[];
+ screenshots: BundleScreenshot[];
+}
+
+export type BundleErrorKind = 'unreadable' | 'not-a-bundle' | 'unsupported-version' | 'empty';
+
+export class BundleError extends Error {
+ readonly kind: BundleErrorKind;
+
+ constructor(kind: BundleErrorKind, message: string) {
+ super(message);
+ this.name = 'BundleError';
+ this.kind = kind;
+ }
+}
+
+const isObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const str = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined);
+const num = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+/**
+ * Geometry from an untrusted manifest ends up sizing an OffscreenCanvas and
+ * allocating pixels, so it is clamped rather than merely checked for finiteness.
+ * 32768 is past any real capture and far short of an allocation failure.
+ */
+const MAX_DIMENSION = 32_768;
+const MAX_POINTS = 20_000;
+
+const bounded = (value: unknown): number | undefined => {
+ const n = num(value);
+ if (n === undefined) return undefined;
+ return Math.max(-MAX_DIMENSION, Math.min(MAX_DIMENSION, n));
+};
+
+const positive = (value: unknown): number | undefined => {
+ const n = num(value);
+ if (n === undefined || n <= 0) return undefined;
+ return Math.min(n, MAX_DIMENSION);
+};
+
+/** Only schemes a browser can safely open. `javascript:` must never reach an href. */
+const SAFE_SCHEMES = ['http:', 'https:'];
+
+export function safeUrl(value: unknown): string {
+ const raw = str(value)?.trim();
+ if (!raw) return '';
+ try {
+ return SAFE_SCHEMES.includes(new URL(raw).protocol) ? raw : '';
+ } catch {
+ return '';
+ }
+}
+
+const SAFE_IMAGE_TYPES = ['image/webp', 'image/png', 'image/jpeg', 'image/gif'];
+
+function bounds(value: unknown): ScreenshotBounds | undefined {
+ if (!isObject(value)) return undefined;
+ const x = bounded(value.x);
+ const y = bounded(value.y);
+ const width = bounded(value.width);
+ const height = bounded(value.height);
+ if (x === undefined || y === undefined || width === undefined || height === undefined) return undefined;
+ return { x, y, width, height };
+}
+
+function point(value: unknown): { x: number; y: number } | undefined {
+ if (!isObject(value)) return undefined;
+ const x = bounded(value.x);
+ const y = bounded(value.y);
+ return x === undefined || y === undefined ? undefined : { x, y };
+}
+
+const DESCRIPTION_SOURCES: DescriptionSource[] = ['narration', 'ai', 'heuristic', 'manual'];
+const BLOCK_TYPES: BlockType[] = ['heading', 'callout'];
+const CALLOUT_VARIANTS: CalloutVariant[] = ['info', 'warning', 'error', 'success', 'custom'];
+
+const oneOf = <T extends string>(value: unknown, allowed: T[]): T | undefined =>
+ typeof value === 'string' && (allowed as string[]).includes(value) ? (value as T) : undefined;
+
+/**
+ * Annotations are replayed onto a canvas, so a malformed one is dropped rather
+ * than defaulted β€” a half-built redaction is worse than a missing decoration.
+ */
+function annotations(value: unknown): Annotation[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const kept = value.filter((a): a is Annotation => {
+ if (!isObject(a) || typeof a.id !== 'string' || typeof a.type !== 'string') return false;
+ switch (a.type) {
+ case 'redact':
+ return [a.x, a.y, a.w, a.h].every((n) => bounded(n) !== undefined);
+ case 'box':
+ case 'ellipse':
+ case 'target':
+ return [a.x, a.y, a.w, a.h].every((n) => bounded(n) !== undefined) && typeof a.color === 'string';
+ case 'arrow':
+ return [a.x1, a.y1, a.x2, a.y2].every((n) => bounded(n) !== undefined) && typeof a.color === 'string';
+ case 'text':
+ // `size` drives every derived coordinate; without it annotationBounds
+ // yields NaN and resizing persists NaN back into the recipient's DB.
+ return (
+ bounded(a.x) !== undefined &&
+ bounded(a.y) !== undefined &&
+ typeof a.text === 'string' &&
+ typeof a.color === 'string' &&
+ positive(a.size) !== undefined
+ );
+ case 'freehand':
+ // An empty list makes Math.min(...[]) Infinity; an odd length leaves a
+ // dangling x with no y.
+ return (
+ Array.isArray(a.points) &&
+ a.points.length >= 2 &&
+ a.points.length % 2 === 0 &&
+ a.points.length <= MAX_POINTS &&
+ a.points.every((n) => bounded(n) !== undefined) &&
+ typeof a.color === 'string'
+ );
+ default:
+ return false;
+ }
+ });
+ return kept.length > 0 ? kept : undefined;
+}
+
+function edits(value: unknown): ScreenshotEdits | undefined {
+ if (!isObject(value)) return undefined;
+ const result: ScreenshotEdits = {};
+ const viewport = bounds(value.viewport);
+ if (viewport) result.viewport = viewport;
+ if (value.target === null) result.target = null;
+ else {
+ const rect = bounds(value.target);
+ if (rect && isObject(value.target)) {
+ result.target = {
+ ...rect,
+ color: str((value.target as Record<string, unknown>).color) ?? '#4F46E5',
+ border: oneOf((value.target as Record<string, unknown>).border, ['dashed', 'solid'] as const) ?? 'dashed',
+ };
+ }
+ }
+ const list = annotations(value.annotations);
+ if (list) result.annotations = list;
+ const alt = str(value.alt);
+ if (alt) result.alt = alt;
+ return Object.keys(result).length > 0 ? result : undefined;
+}
+
+function parseStep(value: unknown, index: number, stripInputValues: boolean): BundleStep | null {
+ if (!isObject(value)) return null;
+ const id = str(value.id);
+ if (!id) return null;
+
+ const step: BundleStep = {
+ id,
+ index: num(value.index) ?? index,
+ description: str(value.description) ?? '',
+ action: str(value.action) ?? 'click',
+ url: safeUrl(value.url),
+ timestamp: num(value.timestamp) ?? 0,
+ };
+
+ const source = oneOf(value.descriptionSource, DESCRIPTION_SOURCES);
+ if (source) step.descriptionSource = source;
+ const blockType = oneOf(value.blockType, BLOCK_TYPES);
+ if (blockType) step.blockType = blockType;
+ const variant = oneOf(value.calloutVariant, CALLOUT_VARIANTS);
+ if (variant) step.calloutVariant = variant;
+ const color = str(value.calloutColor);
+ if (color) step.calloutColor = color;
+ // A bundle that claims it stripped typed values does not get to carry them
+ // anyway. The claim is what the recipient is shown, so it is enforced here
+ // rather than trusted β€” Guide Me would otherwise replay the value into a page.
+ const inputValue = str(value.inputValue);
+ if (inputValue !== undefined && !stripInputValues) step.inputValue = inputValue;
+ const meta = parseElementMeta(value.elementMeta);
+ if (meta) step.elementMeta = meta;
+
+ return step;
+}
+
+/** Guide Me matches live DOM against these fields, so a partial one still has value. */
+function parseElementMeta(value: unknown): ElementMeta | null {
+ if (!isObject(value)) return null;
+ const tag = str(value.tag);
+ const cssSelector = str(value.cssSelector);
+ if (!tag || !cssSelector) return null;
+
+ const nullableStr = (v: unknown): string | null => str(v) ?? null;
+
+ return {
+ tag,
+ cssSelector,
+ textContent: nullableStr(value.textContent),
+ ariaLabel: nullableStr(value.ariaLabel),
+ placeholder: nullableStr(value.placeholder),
+ altText: nullableStr(value.altText),
+ name: nullableStr(value.name),
+ role: nullableStr(value.role),
+ href: safeUrl(value.href) || null,
+ inputType: nullableStr(value.inputType),
+ dataTestId: nullableStr(value.dataTestId),
+ rect: bounds(value.rect) ?? { x: 0, y: 0, width: 0, height: 0 },
+ devicePixelRatio: positive(value.devicePixelRatio) ?? 1,
+ ...(point(value.clickPoint) ? { clickPoint: point(value.clickPoint) } : {}),
+ };
+}
+
+/** Zip entries are never written to disk, but a manifest should still only point inside itself. */
+function safeEntryPath(file: string): boolean {
+ return file.startsWith(`${SCREENSHOT_DIR}/`) && !file.includes('..') && !file.includes('\\');
+}
+
+function parseScreenshot(value: unknown): BundleScreenshot | null {
+ if (!isObject(value)) return null;
+ const id = str(value.id);
+ const stepId = str(value.stepId);
+ const file = str(value.file);
+ const width = positive(value.width);
+ const height = positive(value.height);
+ if (!id || !stepId || !file || !safeEntryPath(file) || width === undefined || height === undefined) return null;
+
+ const declaredType = str(value.mimeType);
+ const shot: BundleScreenshot = {
+ id,
+ stepId,
+ file,
+ // An arbitrary type would become a blob: URL in the extension's own origin
+ // and the extension of whatever "Download original" writes to disk.
+ mimeType: declaredType && SAFE_IMAGE_TYPES.includes(declaredType) ? declaredType : 'image/webp',
+ width,
+ height,
+ };
+
+ const rect = bounds(value.bounds);
+ if (rect) shot.bounds = rect;
+ const ratio = positive(value.pixelRatio);
+ if (ratio !== undefined) shot.pixelRatio = Math.min(ratio, 8);
+ const click = point(value.clickPoint);
+ if (click) shot.clickPoint = click;
+ const editState = edits(value.edits);
+ if (editState) shot.edits = editState;
+
+ return shot;
+}
+
+/**
+ * Validates a manifest from an untrusted file. Structural problems throw so the
+ * import screen can explain them; individual malformed steps are dropped.
+ */
+export function parseManifest(raw: unknown): BundleManifest {
+ if (!isObject(raw)) throw new BundleError('not-a-bundle', 'manifest is not an object');
+
+ const version = num(raw.version);
+ if (version === undefined) throw new BundleError('not-a-bundle', 'manifest has no version');
+ if (version > BUNDLE_VERSION) {
+ throw new BundleError('unsupported-version', `manifest version ${version} is newer than ${BUNDLE_VERSION}`);
+ }
+
+ const guide = isObject(raw.guide) ? raw.guide : null;
+ if (!guide) throw new BundleError('not-a-bundle', 'manifest has no guide');
+
+ const redacted = isObject(raw.redacted) ? raw.redacted : {};
+ const stripInputValues = redacted.inputValues === true;
+
+ const steps = (Array.isArray(raw.steps) ? raw.steps : [])
+ .map((value, i) => parseStep(value, i, stripInputValues))
+ .filter((step): step is BundleStep => step !== null);
+ if (steps.length === 0) throw new BundleError('empty', 'manifest has no usable steps');
+
+ const stepIds = new Set(steps.map((s) => s.id));
+ const screenshots = (Array.isArray(raw.screenshots) ? raw.screenshots : [])
+ .map(parseScreenshot)
+ .filter((shot): shot is BundleScreenshot => shot !== null && stepIds.has(shot.stepId));
+
+ return {
+ version,
+ exportedAt: num(raw.exportedAt) ?? Date.now(),
+ guide: {
+ title: str(guide.title)?.trim() || 'Untitled Guide',
+ ...(str(guide.description) ? { description: str(guide.description) } : {}),
+ createdAt: num(guide.createdAt) ?? Date.now(),
+ },
+ sourceDomain: str(raw.sourceDomain) ?? null,
+ redacted: {
+ screenshots: redacted.screenshots === true,
+ inputValues: stripInputValues,
+ urls: oneOf(redacted.urls, ['full', 'path', 'origin'] as const) ?? 'full',
+ },
+ steps: steps.sort((a, b) => a.index - b.index),
+ screenshots,
+ };
+}
diff --git a/src/core/transfer/scrub.ts b/src/core/transfer/scrub.ts
new file mode 100644
index 0000000..7cc6fb7
--- /dev/null
+++ b/src/core/transfer/scrub.ts
@@ -0,0 +1,79 @@
+export const SCRUB_PLACEHOLDER = '…';
+
+/**
+ * Bare values shorter than this are left alone. A three-letter value is as likely
+ * to be a word inside an unrelated sentence as it is to be the secret, and
+ * mangling the guide's prose is a worse trade than leaving a short value in.
+ * The quoted form is replaced at any length, because that one is unambiguous.
+ */
+export const MIN_BARE_SCRUB = 4;
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+/**
+ * Removes typed field values from text that is about to leave the browser.
+ *
+ * Stripping `step.inputValue` is not enough on its own: the capture pipeline also
+ * writes the value into the step description (`Type "hunter2" in Search`), and an
+ * AI-written title or description can quote it again. Those are copies of the same
+ * secret, so they have to go the same way.
+ *
+ * Two passes, because they carry different risks. The quoted form is exactly what
+ * the description template produces, so it is replaced whatever its length. A bare
+ * occurrence could be an ordinary word, so it is only replaced once it is long
+ * enough to be unlikely to collide.
+ */
+export function scrubValues(text: string, values: readonly string[]): string {
+ let out = text;
+
+ for (const raw of values) {
+ const value = raw.trim();
+ if (!value) continue;
+ const escaped = escapeRegExp(value);
+
+ out = out.replace(new RegExp(`"${escaped}"`, 'gi'), `"${SCRUB_PLACEHOLDER}"`);
+ if (value.length >= MIN_BARE_SCRUB) {
+ out = out.replace(new RegExp(escaped, 'gi'), SCRUB_PLACEHOLDER);
+ }
+ }
+
+ return out;
+}
+
+/** How far `getCleanText` truncates captured element text. Keep in step with element-meta.ts. */
+const CAPTURED_TEXT_LIMIT = 80;
+
+/**
+ * The forms one typed value can take elsewhere in the guide.
+ *
+ * `elementMeta.textContent` is not a copy of `inputValue` β€” `getCleanText` keeps
+ * only the first meaningful line of `innerText`, cut to 80 characters. A literal
+ * search for the whole value therefore sails straight past it, so the shortened
+ * forms have to be searched for too.
+ */
+function variantsOf(value: string): string[] {
+ const variants = new Set<string>([value]);
+ const firstLine = value
+ .split('\n')
+ .map((line) => line.trim())
+ .find((line) => line.length > 2);
+
+ for (const candidate of [firstLine, value.slice(0, CAPTURED_TEXT_LIMIT), firstLine?.slice(0, CAPTURED_TEXT_LIMIT)]) {
+ if (candidate && candidate.length >= MIN_BARE_SCRUB) variants.add(candidate);
+ }
+ return [...variants];
+}
+
+/** Every distinct value typed anywhere in the guide β€” a later step can echo an earlier one. */
+export function typedValues(steps: readonly { inputValue?: string }[]): string[] {
+ const values = new Set<string>();
+ for (const step of steps) {
+ const value = step.inputValue?.trim();
+ if (!value) continue;
+ for (const variant of variantsOf(value)) values.add(variant);
+ }
+ // Longest first, so a value containing another is replaced before its substring.
+ return [...values].sort((a, b) => b.length - a.length);
+}