fetch.tecint.de / developer

Developer Guide

TecInt - fetch is open source under the MIT licence. This page explains how the extension is built, which rules apply in the code and how to add your own features – detailed enough to start without asking.

Manifest
V3
Language
JavaScript, no build step
Dependencies
none
Licence
MIT
Test suite
66 test scripts

Ready in ten minutes

There is no build step, no package manager, no transpiler. The code you write is the code that runs.

# 1 – Unpack the archive
unzip tecint-fetch-1.65.1.zip && cd tecint-fetch

# 2 – Load in Chrome, Edge, Brave, Opera or Vivaldi
#     chrome://extensions → Developer mode → "Load unpacked"

# 3 – Load in Firefox (separate package, see Variants)
#     about:debugging#/runtime/this-firefox → "Load Temporary Add-on"

# 4 – After every change: reload the extension.
#     Content script changes also require reloading the page.
Two traps when reloading. Chrome caches the background service – after changes to background.js, reloading the extension is sometimes not enough; restarting the browser helps. And a content script is not injected retroactively into open tabs; the page must be reloaded.

Architecture

Four areas that know nothing about each other. They exchange messages only – there is no shared state and no direct access.

Diagram: popup and content script send messages to the background service, which opens the editor
The background service is the only place that sees everything. Popup and content script do not know each other.

Why this separation

Manifest V3 partly enforces it: the background service is a service worker that can be terminated at any time. It must not hold state in memory that others rely on. Everything persistent lives in chrome.storage.local or IndexedDB.

Practical consequence: every function must assume the service was restarted between two messages. Setting a top-level variable and reading it later builds in a bug that only shows up occasionally.

The files

FileLinesPurpose
background.js1831Background service: messages, queue, IndexedDB, downloads
bildverarbeitung.js255Stitch individual shots into one image, split into parts if needed
geraete-emulation.js214Device simulation via chrome.debugger (Chromium only)
fehlerprotokoll.js110Record errors for the diagnostics page
devices.js14268 device profiles with viewport, pixel density, user agent
content.js2246Runs inside the page: scrolls, measures, redacts, shows progress
frames.js133Embedded frames: redact, report data
kommentare.js197Expand comments, with a blocklist against dangerous buttons
datenerfassung.js311Email addresses, wallets, profile IDs (full version only)
profil-erkennung.js248Detect platform profiles from URLs (full version only)
popup/popup.js822Toolbar user interface
editor/editor.js4099Editor: captures, tools, export
editor/zeichnen.js325Draw header and annotations into the image
editor/pdf.js240Searchable PDF without third-party library
editor/bericht.js157HTML report
editor/vergleich.js163Change tracking
editor/zip.js143ZIP bundle, written from scratch
editor/kette-ablage.js173Chain of custody per capture, written continuously to IndexedDB
editor/langbild.js211All captures stacked into one PNG file, without the canvas size limit
editor/integritaet.js77SHA-256 and log
editor/hilfen.js144Stateless helper functions
i18n.js141Language choice and lookups; fetches the English texts when needed
texte-en.js465The English texts. Loaded only when the interface is English
optionen/optionen.js435Settings, redaction rules, backup

Line counts from version 1.65.1. None of the files loads an external library – PDF, ZIP and SHA-256 are written from scratch. That is deliberate: any third-party library would be unreviewed code inside a tool that produces evidence.

File reference

This page describes the full package – the same edition for Chromium browsers and for Firefox. Both contain the same 44 files; they differ only in the manifest (see Variants).

Every file is listed below with its most important functions. Line counts are from version 1.65.1. Files that exist only in other packages are not described here – tests, store material and the findings list are in the developer package, not in the shipped extension.

Background service

FileKey functionsPurpose
background.js
1831 lines, 49 functions
contentInjizieren() · openOrFocusEditor() · mitWarteschlange() · queueCapture() · captureVisibleTabSafe() · selbstpruefung() · sitzungStarten() Receives all messages, calls captureVisibleTab (only the service may), manages the queue and the IndexedDB sessions. captureVisibleTabSafe() retries up to five times – Chrome limits it to roughly two calls per second.
bildverarbeitung.js
255 lines, 6 functions
stitchScreenshots() · stitchScreenshotsInTeile() · alsJpegWennZuGross() · blobToDataUrl() · downloadBlob() Stitches the individual shots. stitchScreenshotsInTeile() decides whether one image suffices or parts are needed, accounting for the overhang of a group. alsJpegWennZuGross() converts parts above 40 MB.
geraete-emulation.js
214 lines
emulationAktivieren() · emulationBeenden() · sendeBefehl() Sets viewport, pixel density, touch and user agent via chrome.debugger. Chromium only; every access first checks whether the API exists.
fehlerprotokoll.js
110 lines
fehlerMerken() · fehlerLesen() · fehlerLeeren() Records recent errors with area, message and timestamp. Caps the list so it does not fill up storage.
devices.js
142 lines
DEVICE_PRESETS (Datenfeld) 68 device profiles: name, width, height, pixel density, touch, user agent. Pure data, no logic.

Inside the page (content scripts)

FileKey functionsPurpose
content.js
2246 lines, 78 functions
runCaptureFullPage() · runCaptureVisible() · runCaptureRegion() · stitchAndOpenEditor() · sanitizeFilename() · buildHeader() · showProgress() · schwaerzeElemente() Most of the work. Scrolls the page, hides sticky bars, covers password fields, shows progress and the stop button inside a shadow DOM (so the page cannot override it) and assembles the info header.
frames.js
133 lines
Nachrichtenempfänger für TECINT_FRAME_* Runs in every embedded frame. Redacts password fields there and reports findings on request. The DATEN_ERFASSEN switch is flipped when building the Lite variant.
kommentare.js
197 lines
istKommentarSchaltflaeche() · klappeAlleAuf() Clicks buttons such as "Show more replies". A blocklist prevents clicks on "Delete", "Report", "Submit" – otherwise a capture could trigger an action.
datenerfassung.js
311 lines
findeEmails() · findeWallets() · findeProfile() · csvAus() Full version only. Searches visible text for email addresses, crypto wallets and profile IDs. Replaced by a stub returning empty lists in FetchLite.
profil-erkennung.js
248 lines
profilAusUrl() · istReserviert() · PLATTFORM_MUSTER Full version only. Derives platform and identifier from a URL. istReserviert() filters paths such as /settings that are not profiles.

Editor

FileKey functionsPurpose
editor/editor.js
4099 lines, 120 functions
render() · addCaptureFromPayload() · setActive() · applyZoom() · baueCsv() · csvFeld() · kombiniere() · speichereArbeitsstand() The largest file. Manages the capture list, draws onto the canvas, keeps annotations as objects (not pixels) and saves the working state continuously so a closed tab costs nothing.
editor/zeichnen.js
325 lines, 9 functions
drawHeaderBand() · measureHeader() · drawAnnotation() · annotationBBox() · pointInBBox() Draws the info header and all annotations. measureHeader() computes the required height in advance – the header must not cover any of the image. annotationBBox() and pointInBBox() enable selecting and moving.
editor/integritaet.js
77 lines, 4 functions
sha256Hex() · protokollEintragen() · exportiereMitPruefsumme() · kontextAus() The heart of the evidence trail. exportiereMitPruefsumme() is the only route exports should take – it computes the checksum, downloads and writes the log entry in one go.
editor/pdf.js
240 lines
erzeugePdf() · textEbene() Builds the PDF byte by byte, without a third-party library. Places an invisible text layer over the image so the PDF is searchable.
editor/bericht.js
157 lines
baueBericht() · htmlEscape() Produces an HTML report with image, metadata and checksum. htmlEscape() neutralises all foreign values before they reach the HTML.
editor/vergleich.js
163 lines
vergleiche() · zeigeUnterschiede() Change tracking: compares the captured text against an earlier capture of the same URL and marks additions green, removals red.
editor/zip.js
143 lines
erzeugeZip() · crc32() Writes a ZIP archive without compression (method "stored"), from scratch. Sufficient for a bundle of image, PDF, report and log.
editor/pdf-seiten.js
paper-size printing
abschnitte() · seitenAus() · ausschnitt() Splits long captures into sections that fit on a sheet – A4 and Letter, portrait and landscape. With 24 pixels of overlap: without it, a line of text could fall exactly on the cut and be halved on both sheets. Each page carries "Section 2 of 7" with the pixel range it comes from.
editor/pdf-deckblatt.js
cover sheet and record
textPdf() · inSeiten() · umbrechen() Produces plain text pages as PDF – for the capture record and the cover sheet. Makes sure signature fields do not fall on a page break: a field whose label is on page 1 and whose line is on page 2 would be useless in print. Verified for A4 and Letter.
editor/export-nachweis.js
export bundle
baueBuendel() · baueDateien() Brings everything together: originals into aufnahmen/, editor results into bearbeitet/, plus nachweis.json and nachweis.txt. The order is mandatory – first the files with their hashes, then the record (which belongs in the list itself), then the manifest hash over all of them. Originals are never overwritten.
editor/protokoll.js
capture record
baueProtokollText() · baueProtokollMarkdown() · protokollAbschnitt5() Produces a pre-filled form with empty signature fields – not a sworn statement, not an affidavit. Sections 6 and 7 use fixed wording and are checked word by word by tests/test-protokoll.js. No field is ever filled from a variable.
editor/kette.js
chain of custody
anhaengen() · pruefeKette() · pruefeVerankerung() · ketteAlsText() · kettenAlsText() · gliedText() Maintains the chain of custody: every step taken with the material is recorded as a link, each containing the hash of the previous one. pruefeKette() detects changed, removed and inserted entries and names exactly one finding – no cascade of follow-up messages. gliedText() defines the hash format: a fixed field order instead of JSON.stringify, whose key order is not guaranteed. Since the append-only log was introduced the record carries two kinds of chain: per capture the one recorded during the work (verlaufsketten), and the package chain (verlaufskette), created when the package is built, whose capture link names the last hash of the recorded chain. pruefeVerankerung() checks exactly that reference: a recorded chain swapped or shortened after the package was built shows up there.
editor/kette-ablage.js
append-only log
anhaengen() · lesen() · vorhanden() · aufraeumen() The storage behind the chain of custody: a separate IndexedDB database (tecint_kette), apart from the working state, with one chain per capture. Every link is written at the moment the step happens – arrival, image tool, export, resuming work after the editor was restarted. Before that the chain was only built at export time, from steps that did carry real timestamps but whose hashes were all computed in the same instant. Writes per capture are serialised so that two tools used in quick succession cannot overwrite each other's links. Chains without material are removed after 30 days.
editor/langbild.js
long image
erzeugen() · masse() · crc32() Writes all selected captures stacked into one PNG file without allocating a large canvas: each capture passes through a small working canvas in strips of 2048 rows, the rows are read and streamed straight into the PNG data (CompressionStream("deflate"), falling back to stored zlib blocks). Combining stops at 16000 pixels per edge; here the file format sets the limit. Captures are only drawn when their turn comes, so ten full pages never sit in memory at once.
editor/pdf-protokoll.js
designed record
baue() · inSeiten() · hoeheVon() Typesets the capture record from blocks rather than running text: heading, field pair, paragraph, rule, signature field. Three font styles (regular, bold, monospace for checksums). A heading alone at the bottom of a page moves to the next page with its content.
editor/nachweis.js
evidence files
manifestHash() · baueNachweis() · baueNachweisText() · slugAusTitel() · zeitBlockStart() · zeitBlockEnde() · pruefeExport() Produces nachweis.json and nachweis.txt. manifestHash() follows a fixed procedure so the value can be recomputed outside the software – byte-wise sorting with sort(), never localeCompare. zeitBlockEnde() compares wall clock and monotonic clock and thus detects a system clock changed during the capture.
editor/hilfen.js
144 lines, 10 functions
sanitizeName() · loadImage() · uid() · filenameTimestamp() · chromeSendMessage() · defaultHeader() Stateless helper functions – hence easy to test and the main target of the fuzzing test.
editor/editor.html
interface
– Structure of the editor: toolbar, capture list, canvas, header fields. Tools are identified via data-tool.
editor/editor.css – Styling of the editor, including the layout for narrow windows.

Interfaces and resources

FilePurpose
popup/popup.htmlStructure of the popup: capture mode, options, full-version note, language choice
popup/popup.js
822 lines
Popup behaviour. At the end it hides sections whose APIs are missing (chrome.debugger, chrome.pageCapture).
optionen/optionen.htmlSettings page: redaction rules, backup, self-check, diagnostics
optionen/optionen.js
435 lines
Saves settings, manages redaction rules, creates and restores backups. On restore, rules are merged rather than replaced.
i18n.js
141 lines
Language choice, interface translation and t() for lookups. German lives directly in the HTML; the English texts are fetched when needed.
texte-en.js
465 lines
The English text table with 424 keys. It arrives only once someone switches the interface to English - before that it weighed 25 kilobytes in every window.
manifest.jsonManifest V3: permissions, background service, icons, keyboard shortcuts, browser_specific_settings for Firefox
icons/Icons at 16, 32, 48 and 128 pixels, per variant

Documentation in the package

FilePurpose
docs/index.htmlUser manual, German – opened from the popup
docs/index.en.htmlUser manual, English
docs/docs.css, docs/docs.jsStyling and table of contents of the manual
README.mdOverview, installation, variants, Firefox notes
LICENSEMIT licence text

The tests/ folder holds 105 further files – checks, build scripts and tools. They are described in the test suite section and are not part of the shipped package.

Images and licence

Not program files, but part of the package – and referenced in several places. If one is missing, the extension still starts but shows an empty icon.

FileFormatPurpose
icons/icon16.pngPNG, 16 × 16 Toolbar icon at single resolution. Declared in the manifest under icons and action.default_icon.
icons/icon32.pngPNG, 32 × 32 Toolbar at double resolution; also the favicon of the manual (docs/index.html).
icons/icon48.pngPNG, 48 × 48 Extension management (chrome://extensions) and context menu.
icons/icon128.pngPNG, 128 × 128 Store listing and install dialog. The largest version; the smaller ones are derived from it.
images/logo.pngPNG, 75 × 32 Wordmark as a raster image. Kept as a fallback, for instance for the selection dialog and older views.
images/logo.svgSVG, 1.2 KB The same wordmark as a vector, for the light appearance. Popup, editor and settings embed it through <picture> so it stays sharp at any resolution.
images/logo-hell.svgSVG, 1.2 KB The light version of the same mark, selected through prefers-color-scheme: dark. On a dark background the dark lettering would not be readable.
images/logo_dialog.pngPNG, 150 × 64 The same mark at double resolution, for the selection dialog on the page. The only file listed under web_accessible_resources – it is embedded into the captured page and must be reachable from there.
LICENSEText, 37 Zeilen The MIT licence verbatim. It requires the licence text and copyright notice to be kept on every redistribution – which is why the file is in the lean runtime packages too.

What happens during a capture

Five steps of a full-page capture: prepare, scroll, buffer, stitch, hand over
The full-page capture in five steps. Every step has a reason that came from a real bug.

Step 3: why each shot is stored immediately

Every screen is written to IndexedDB right after capture, not at the end. A capture spanning 30 screens takes half a minute; if the browser crashes, everything would be lost without buffering. The editor offers such sessions for recovery on next start.

Steps 4 and 5: two limits you need to know

Two technical limits shape this part of the code:

From experience: both limits only became visible through error messages from real use – "Message exceeded maximum allowed size of 64MiB" on an image-heavy page. If you change anything here, run tests/test-groessen.js: it checks six orders of magnitude up to 120,000 pixels using noise-like test images. Solid-colour images produce almost no data and let every size pass – which is exactly why the bug went unnoticed for so long.

Message contracts

The areas communicate via chrome.runtime.sendMessage. Every message has a type field prefixed with TECINT_. Version 1.65.1 has 44 types; the most important ones follow.

MessageFrom → ToMeaning
TECINT_STARTPopup → ContentStart capture; mode is visible, region or fullpage
TECINT_CAPTUREContent → BackgroundCapture one screen (only the service may call captureVisibleTab)
TECINT_SHOT_SPEICHERNContent → BackgroundStore one part in IndexedDB
TECINT_STITCHContent → BackgroundStitch parts; the reply contains either dataUrl or teileInfo
TECINT_TEIL_HOLENContent → BackgroundFetch a single part (because of the 64 MB limit)
TECINT_OPEN_EDITORContent → BackgroundOpen the editor and hand over the capture
TECINT_PULL_PENDING_CAPTURESEditor → BackgroundFetch pending captures and remove them from the queue
TECINT_KANN_ARCHIVContent → BackgroundIs chrome.pageCapture available? Only then is the button shown
TECINT_SELBSTPRUEFUNGOptions → BackgroundCheck stored data for readability and format
TECINT_FRAME_DATENBackground → all framesBroadcast; each frame replies with TECINT_FRAME_MELDUNG

The rule for new messages

A handler without a sender is dead code; a sender without a handler is a silent failure. The static analysis checks both – a handler nobody calls makes tests/test-statisch.js fail.

// In the background service: add a handler
if (msg.type === "TECINT_MEINE_FUNKTION") {
  // Always reply – including on failure. A caller waiting for a reply
  // that never arrives hangs until the timeout.
  try {
    const ergebnis = await meineFunktion(msg.parameter);
    sendResponse({ ok: true, ergebnis });
  } catch (e) {
    sendResponse({ ok: false, error: String(e && e.message || e) });
  }
  return;   // important: return, otherwise further checks run
}
// In the content script or editor: call it
const res = await sendBg({ type: "TECINT_MEINE_FUNKTION", parameter: 42 });
if (!res || !res.ok) {
  // Handle the failure – do not assume it worked
  showProgress("Could not be executed.", 4000);
  return;
}
Why sendResponse must always be called: if it is forgotten, the caller hangs until Chrome closes the channel – without an error message. This is the nastiest kind of bug in extensions, because it looks like a freeze rather than a failure.

Where things are stored

Two stores with different purposes. chrome.storage.local for settings and lists, IndexedDB for image data – the settings store would run out of space quickly.

KeyContents
tecint_settingsSettings: delay, filename template, format
tecint_schwaerzregelnCustom redaction rules (CSS selector, optionally per site)
tecint_protokollChecksum log: datei, sha256, groesse, exportiertAm, quellUrl
tecint_historyHistory of earlier captures, used for change tracking
tecint_pending_capturesQueue: captures the editor has not fetched yet
tecint_zeitplaeneScheduled captures (full version only)
tecint_sprachede, en or empty for browser language
tecint_fehlerprotokollRecent errors for the diagnostics page

If you add a key

Three places need updating, otherwise the value is lost during backup or migration:

  1. Backup in optionen/optionen.js – otherwise the value is missing from the backup file
  2. Self-check in background.js, function pruefeEintrag() – if it is a list
  3. Test in tests/test-sicherung.js
Look up field names, do not guess. The self-check once reported problems on intact data because it looked for hash while the log writes sha256. A false alarm is almost as bad as a missed error – it teaches users to ignore the warning.

Adding your own features

Example: a new editor tool

Tools are identified by a data attribute. Four steps:

<!-- 1. editor/editor.html – button in the toolbar -->
<button class="tool" data-tool="stern">★ Stern</button>
// 2. editor/editor.js – add the drawing logic.
//    Annotations are objects, not pixels: they can be moved,
//    deleted and redrawn on export.
function zeichneStern(ctx, a) {
  ctx.strokeStyle = a.farbe;
  ctx.lineWidth = a.staerke;
  ctx.beginPath();
  for (let i = 0; i < 10; i++) {
    const r = i % 2 === 0 ? a.radius : a.radius / 2.4;
    const w = (Math.PI / 5) * i - Math.PI / 2;
    ctx[i ? "lineTo" : "moveTo"](a.x + Math.cos(w) * r, a.y + Math.sin(w) * r);
  }
  ctx.closePath();
  ctx.stroke();
}
// 3. Register it in the drawing loop
if (a.typ === "stern") zeichneStern(ctx, a);
// 4. i18n.js – both languages. A missing key makes
//    tests/test-sprache.js fail.
"editor.stern": "Star",   // German lives in the HTML, English here

Example: a new export format

Exports go through exportiereMitPruefsumme() in editor/integritaet.js. Using it gives you the checksum and the log entry automatically:

const blob = await meinFormatErzeugen(canvas);
await exportiereMitPruefsumme(
  blob,
  dateiname + ".mein",
  saveAs,            // does the user pick the location?
  kontext,           // { url, titel, aufgenommen } – goes into the log
  downloadFn,
  anzeigenFn
);
Do not export around the log. A file without a log entry cannot later be shown to be unchanged – which is exactly what this tool is for.

Example: a new language

i18n.js holds English as a translation table; German lives directly in the HTML. For a third language:

// i18n.js – add a second table
const FR = { "popup.start": "Démarrer la capture", /* … */ };
const TABELLEN = { en: EN, fr: FR };

About 400 keys need translating. tests/test-sprache.js checks that none is missing and that no German remnants stay in the foreign-language interface.

The three variants

There is one code base. Full version, FetchLite and the Firefox builds are generated from it on every build – nothing is copied and maintained separately.

Diagram: two build scripts turn one source into the FetchLite and Firefox builds
Two build scripts, one source. A change takes effect in every variant.
VariantBuilt byDifference
Full version–all features, 9 required permissions
FetchLitetests/baue-store-variante.jsno data extraction, device simulation or batch; no debugger
Firefoxtests/baue-firefox-variante.jsmanifest.json at the top level, without debugger and pageCapture

How the omission works

The store variant replaces modules with stubs and flips switches in the code. An example from the build script:

// frames.js is injected separately and does not see the stubs.
// Without this switch it kept reporting email addresses from
// embedded frames in the Lite version.
ersetze('frames.js', 'const DATEN_ERFASSEN = true;', 'const DATEN_ERFASSEN = false;');
If you add a feature that must not exist in FetchLite, three places need attention: exclude the module in WEGLASSEN, add a stub in store-attrappen.js, hide the control in the HTML. The corresponding check is tests/test-store-variante.js (92 checks). It also catches the reverse case: a full-version feature that slips into the Lite build.

What is missing in Firefox – and why

FeatureRequiresBehaviour there
Device simulationchrome.debuggersection is hidden
MHTML archivechrome.pageCapturebutton is hidden
// This is how to check – never assume an API is present:
if (!chrome.pageCapture) {
  const knopf = document.getElementById("archivBtn");
  if (knopf) knopf.style.display = "none";
}
Top-level access is dangerous. chrome.debugger.onDetach.addListener(...) once sat outside any function. Without the permission, chrome.debugger is undefined – the background service crashed on startup before anything else ran. Check the API before accessing it, including for event listeners.

The background service and its lifecycle

This is where most bugs in Manifest V3 extensions come from. The background service is a service worker: Chrome terminates it after about 30 seconds of inactivity and restarts it on the next message.

Diagram: the service starts, is terminated after 30 seconds of inactivity and restarts – variables are gone
Between two messages everything in memory may be gone.

What this means in practice is shown by a bug that actually occurred in this project:

// WRONG – does not survive a pause of the service
let laufendeSitzung = null;

if (msg.type === "TECINT_SITZUNG_START") {
  laufendeSitzung = msg.id;          // set
  sendResponse({ ok: true });
}
if (msg.type === "TECINT_SHOT_SPEICHERN") {
  await speichern(laufendeSitzung);  // may be null – the service restarted
}
// RIGHT – the state lives in storage, not in a variable
if (msg.type === "TECINT_SITZUNG_START") {
  await chrome.storage.local.set({ tecint_sitzung: msg.id });
  sendResponse({ ok: true });
}
if (msg.type === "TECINT_SHOT_SPEICHERN") {
  const { tecint_sitzung } = await chrome.storage.local.get("tecint_sitzung");
  await speichern(tecint_sitzung);
}
This applies to event listeners too. A top-level addListener runs again on every restart – that is intended and correct. It becomes dangerous when it touches an API that is not available everywhere: chrome.debugger.onDetach.addListener(...) crashed the service on startup in Firefox because chrome.debugger is undefined there.

Concurrent access

Reading and writing are two steps with an await in between. If two operations run concurrently, they overwrite each other – observed when capturing multiple tabs and during batch processing.

Diagram: without serialisation two accesses overwrite each other; with a queue both survive
Two tabs, one queue: without ordering, one capture is lost.
// background.js – every change to the queue runs in sequence
let warteschlangenKette = Promise.resolve();

function mitWarteschlange(arbeit) {
  // Append to the chain – keep going even after a failure,
  // otherwise one failure blocks every following access.
  const naechste = warteschlangenKette.then(arbeit, arbeit);
  warteschlangenKette = naechste.catch(() => {});
  return naechste;
}

// Usage: never read and write directly
await mitWarteschlange(async () => {
  const daten = await chrome.storage.local.get(PENDING_KEY);
  const liste = daten[PENDING_KEY] || [];
  liste.push(neueAufnahme);
  await chrome.storage.local.set({ [PENDING_KEY]: liste });
});
When you need this: Whenever you read a stored value, modify it and write it back. A plain set without a preceding get does not need it.

Neutralising foreign data

Page titles, URLs and page content come from arbitrary websites. Three functions prepare them before they end up in filenames, spreadsheets or HTML.

Diagram: three functions turn dangerous input into harmless output
Input on the left, result on the right. All three are stateless and therefore easy to test.
// editor/hilfen.js – filenames
function sanitizeName(name) {
  return (name || "bild")
    .replace(/\.(png|jpe?g|pdf)$/i, "")
    // Control characters first: a null byte can truncate a filename at
    // the OS level – the visible name and the file actually written
    // would then differ.
    .replace(/[\x00-\x1f\x7f]+/g, "")
    .replace(/[\\/:*?"<>|]+/g, "_")   // path separators and wildcards
    .replace(/\s+/g, "_")
    .slice(0, 80) || "bild";           // never return empty
}
// editor/editor.js – CSV fields
function csvFeld(wert) {
  let s = String(wert === undefined || wert === null ? "" : wert);
  // If the value starts with one of these, Excel or LibreOffice
  // executes it as a formula. The apostrophe prevents that.
  if (/^[=+\-@]/.test(s)) s = "'" + s;
  return '"' + s.replace(/"/g, '""') + '"';
}
Verified with random input. tests/test-fuzzing.js sends 24,000 randomly assembled strings through these functions and checks that none lets a path separator, a formula or a control character through. That is exactly how the null byte was found that the sanitiser used to let pass.

The evidence layer

The most involved layer of the extension – and the one with the strictest rules. Its purpose: someone without TecInt - fetch should be able to verify that the files have not changed since the capture. Everything here is designed to stay reproducible outside the software.

The manifest hash

The single value you can write down or send by email. It covers renaming, removal and addition in one number. The procedure is fixed and must not be changed – otherwise the value can no longer be recomputed:

The manifest hash in five steps: first a SHA-256 sum per file. Second one line of sum, two spaces and path. Third sort by character code, never with localeCompare. Fourth join with newlines and a trailing newline. Fifth SHA-256 over the whole thing – that is the manifest hash.
The procedure is fixed so the value stays verifiable outside the software. Any deviation – one space, a missing newline, a different sort order – yields a different hash.
function manifestZeilen(dateien) {
  return dateien
    .filter((d) => d && typeof d === "object")
    // 1. One line per entry: "<sha256>  <path>" – TWO spaces, like sha256sum
    .map((d) => `${d.sha256}  ${String(d.pfad).replace(/^\.\//, "")}`)
    // 2. sort() WITHOUT a comparator – byte-wise by UTF-8 code points
    .sort()
    // 3. join with \n, append a trailing \n
    .join("\n") + "\n";
}

async function manifestHash(dateien) {
  return hashBytes(new TextEncoder().encode(manifestZeilen(dateien)));
}
Never localeCompare. It sorts differently depending on the locale – in Turkish, I and i sit elsewhere than in English. The hash would then differ between two machines, which is exactly what must not happen. tests/test-statisch.js checks that localeCompare does not appear in this file.

Because the procedure is fixed, the value can be recomputed with standard tools:

# The list is in plain text inside nachweis.txt.
# Extract the lines, sort them, hash the result:
grep -E '^[0-9a-f]{64}  ' nachweis.txt | sort | sha256sum

What the record contains

nachweis.json follows a fixed schema. Two rules are easy to miss and both matter:

{
  "format": "tecint-fetch-nachweis",
  "format_version": 1,
  "zeit": {
    "utc": "2026-09-08T14:23:07.412Z",
    "lokal": "2026-09-08T16:23:07.412+02:00",
    "zeitzone": "Europe/Berlin",
    "offset_minuten": -120,
    "quelle": "systemuhr",
    "monotonic_start_ms": 48213.7,
    "monotonic_ende_ms": 53034.9,
    "uhr_sprung_erkannt": false
    // server_date and abweichung_sekunden are OMITTED when no
    // Date header was present – they are not set to null.
  },
  "dateien": [
    {
      "pfad": "aufnahmen/001-beispiel.png",
      "rolle": "original",
      "sha256": "9f2c…",
      "abgeleitet_von": null
    },
    {
      "pfad": "bearbeitet/001-beispiel-b1.png",
      "rolle": "bearbeitet",
      "sha256": "1ad7…",
      // The HASH of the original, not its path.
      // Paths can be renamed, hashes cannot.
      "abgeleitet_von": "9f2c…",
      "bearbeitungen": ["rechteck", "text"]
    }
  ],
  "manifest_sha256": "7e11…"
}
A missing value is not the same as a null value. If no Date header was present, server_date and abweichung_sekunden are omitted entirely. A null would claim that we looked and found nothing – in fact we did not look. In FetchLite both fields are always absent because the webRequest permission is not present there.

No self-reference

nachweis.json contains no hash of itself – that could not be computed. The hash of nachweis.json is in nachweis.txt, and not the other way round. The protection is deliberately one-directional; a circular hash does not exist.

The build order

It is mandatory. Changing it produces values that can no longer be recomputed:

  1. Write all payload files and compute their hashes
  2. Generate the record – it belongs in the file list itself
  3. Manifest hash over the complete list
  4. Write nachweis.json
  5. Compute the hash of nachweis.json
  6. Write nachweis.txt – containing that hash

Checking the system clock

The extension cannot prevent anyone from changing the clock. It can detect it happening during a capture, though – the monotonic clock cannot be changed:

// Wall clock and monotonic clock must agree. If they do not,
// the system clock was changed in between.
const wanduhrDiff  = endeMs - Date.parse(start.startUtc);
const monotonDiff  = performance.now() - start.monotonicStart;
block.uhr_sprung_erkannt = Math.abs(wanduhrDiff - monotonDiff) > 2000;

The capture record

The strictest rules in the whole project apply here. The extension produces a form with empty signature fields – not a sworn statement, not an affidavit. Such a declaration is an act by a person, not a property of a file.

RuleReason
Forbidden wordsAffidavit, sworn statement, certified, legally binding, notarised – except in the explicit negation
No document stylingNo seals, coats of arms, stamps or court-like appearance. The form looks like a technical listing
Fields stay emptyNo pre-filling from system user names, no stored identity, no "last used name"
Sections 6 and 7 verbatimThey easily become too strong otherwise. tests/test-protokoll.js checks them word by word
Why this strictness: a form that promises more than it delivers harms the user in proceedings more than it helps. With a locally running extension, the declaration can only come from the capturing person – and in a dispute that person is a party. Services capturing server-side have an uninvolved third party sign; software cannot close that gap.

If you extend the evidence layer

The corresponding checks: tests/test-nachweis.js (36), tests/test-protokoll.js (25), tests/test-export-nachweis.js (21), tests/test-nachweis-fuzz.js (10, 7,100 calls), tests/test-pdf-deckblatt.js (26), tests/test-zeitzonen.js (36) and tests/test-beweis-live.js (11) in a real browser.

Coding guidelines

These rules come from bugs found in real use – not from a style guide.

Language in the code

Handling errors

Security

What the code must not do

The test suite

66 test scripts, together over 2200 individual assertions. A full pass takes about 30 minutes.

# Both: two full passes in different order
bash tests/beide.sh

# A single check
node tests/test-live.js
node tests/test-groessen.js

# Check against a different build
TECINT_PFAD=/path/to/other/build node tests/test-live.js

The most important checks

FileChecks
test-statisch.jsSyntax, manifest, startability, CSP, dead handlers, licence headers
test-live.jsCapture, editor, export – four perspectives
test-groessen.jsSix orders of magnitude up to 120,000 pixels
test-fuzzing.js24,000 random inputs against the security functions
test-echte-seiten.jsReplicas of real patterns: sticky bars, dialogs, infinite scroll
test-live-webseiten.jsReal pages fetched from the internet
test-versionswechsel.jsUpgrade from 1.25 to current with real data
test-beschaedigt.jsTen cases of corrupted data
test-wiederholung.jsTiming-sensitive checks five times each – reveals flaky failures
test-store-variante.js92 checks of the Lite build
test-website.jsChecks of this website

The rule for changes

When a bug is found and fixed, everything is checked again – a fix can break something elsewhere. A test run is only complete when two full passes in different order both come back clean. Two identical passes only prove the tests are repeatable; a bug that depends on ordering would stay invisible.

docs/blickwinkel.md in the package lists the perspectives and the findings they produced – worth reading before writing your own tests.

docs/pruefbericht-1.65.1.md is the audit report for the current release: 2 findings by severity, each with file, risk and fix, plus the optimisations with measurements and before/after code. The reports of earlier releases sit next to it; each closes with what the audit taught about auditing. For anyone building on the code that is the more useful half. The reports are in German.

Notable changes by version

32 versions are archived and serve as a basis for comparison. These steps matter if you build on the code:

VersionWhat changed
1.26–1.31Large files split into modules (editor/, bildverarbeitung.js)
1.34FetchLite introduced; two variants generated from one source since then
1.36–1.37Firefox groundwork: background.scripts alongside service_worker
1.44Package structure fixed – manifest.json was in a subfolder
1.49Long pages split into parts instead of being cropped
1.5064 MB limit: parts are transferred individually
1.51Group overhang – in an extreme case 4.7 % of the page was missing
1.53Null byte in filename sanitising, found by fuzzing
1.55Self-check validates entries, not just the container
1.56MHTML button in the completion dialog; top-level access guarded
1.57Firefox released; SEO groundwork
If you build on an older version: before 1.49 long pages were cropped, before 1.50 the transfer broke on image-heavy pages. Both are bugs you will notice in daily use.

Licence and redistribution

TecInt - fetch is released under the MIT licence. You may use, modify, redistribute and commercially deploy the code – under two conditions:

MIT License

Copyright (c) 2026 Lukas Weis <mail@tecint.de>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

If you publish your own build

Contributing to the original

Bug reports and suggestions are welcome at mail@tecint.de. Helpful: which version, which browser, which page, and the message verbatim – the exact wording often leads straight to the cause.

Further reading in the package

FileContents
README.mdOverview, installation, variants
docs/index.htmlUser manual, German and English
tests/105 files: checks, build scripts, tools

← Back to the home page