@snapwonders/report 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/model.js CHANGED
@@ -1,566 +1,578 @@
1
- /*
2
- * snapWONDERS API — Result renderer (JavaScript)
3
- * API version: 1.0
4
- *
5
- * Copyright (c) 2026 Kenneth Springer @ snapWONDERS. MIT Licensed — see LICENSE.
6
- * The MIT licence covers this client library only; the snapWONDERS API it calls is proprietary.
7
- *
8
- * Author: Kenneth Springer @ snapWONDERS <kenneth@snapwonders.com> (https://kennethbspringer.au)
9
- *
10
- * All the snapWONDERS API services are available over the Clearnet / **Web** and Dark Web **Tor** and **I2P**
11
- * Read details: https://snapwonders.com/developers
12
- */
13
-
14
- /**
15
- * Turns one analyse result (GET /api/analyse/result/{job_uid}) into a plain view model, for the
16
- * card or the full report. No DOM and no network here, so it runs (and is tested) anywhere. The
17
- * wording mirrors the snapWONDERS report page, so every surface says the same thing.
18
- */
19
-
20
- // The result contract this renderer understands. A result with any newer version, minor too, gets a
21
- // non-blocking "new version available" note; everything this renderer knows is still drawn.
22
- export const SUPPORTED_SCHEMA_MAJOR = 1;
23
- export const SUPPORTED_SCHEMA_MINOR = 4;
24
- export const SUPPORTED_SCHEMA = `${SUPPORTED_SCHEMA_MAJOR}.${SUPPORTED_SCHEMA_MINOR}`;
25
-
26
- // Where the note links unless the host (extension, plugin, app) passes its own release notes
27
- export const DEFAULT_RELEASE_NOTES_URL = 'https://github.com/snapWONDERS/snapWONDERS-Report/blob/main/CHANGELOG.md';
28
-
29
- /**
30
- * True when a result is newer than this renderer (any bump, minor too) or its version is unreadable.
31
- */
32
- export function isNewerSchema(version) {
33
- if (version === null) return true;
34
- if (version.major !== SUPPORTED_SCHEMA_MAJOR) return version.major > SUPPORTED_SCHEMA_MAJOR;
35
- return version.minor > SUPPORTED_SCHEMA_MINOR;
36
- }
37
-
38
- // The update note's wording: gentle for a minor bump (fields only added), firmer for a major one
39
- // (a field changed meaning or was removed) or an unreadable version (owner 2026-11-20)
40
- export const UPDATE_NOTE = Object.freeze({
41
- minor: 'A new version is available, with more in this report.',
42
- major: 'Update needed: this report comes from a newer snapWONDERS version, so some parts may be missing or shown wrongly.',
43
- });
44
-
45
- /**
46
- * The update note for a result, or null when none is due. The note is dismissable: the host keeps the
47
- * version the user dismissed (`dismissedUpdate`, e.g. in extension storage) and the note stays hidden
48
- * for that version and older ones, and comes back on the next version.
49
- */
50
- function updateNote(version, dismissedUpdate) {
51
- if (!isNewerSchema(version)) return null;
52
- const level = version === null || version.major > SUPPORTED_SCHEMA_MAJOR ? 'major' : 'minor';
53
- const dismissed = typeof dismissedUpdate === 'string' ? parseSchemaVersion(dismissedUpdate) : null;
54
- if (version !== null && dismissed !== null
55
- && (dismissed.major > version.major || (dismissed.major === version.major && dismissed.minor >= version.minor))) {
56
- return null;
57
- }
58
- return {
59
- level,
60
- text: UPDATE_NOTE[level],
61
- schemaVersion: version === null ? null : `${version.major}.${version.minor}`,
62
- };
63
- }
64
-
65
- // Grade words, as on the report page
66
- export const GRADE_WORDS = Object.freeze({
67
- A: 'Nothing significant found',
68
- B: 'Low risk',
69
- C: 'Moderate risk',
70
- D: 'High risk',
71
- F: 'Critical',
72
- });
73
-
74
- export const CONFIDENCE_WORDS = Object.freeze({ high: 'High', medium: 'Medium', low: 'Low' });
75
-
76
- // AI generation verdicts, as on the report page's AI card
77
- export const AI_VERDICT_WORDS = Object.freeze({
78
- likely_authentic: 'Verified camera capture',
79
- likely_real: 'Likely real (camera signals)',
80
- real_edited: 'Real capture, edited',
81
- no_evidence: 'No AI-generation evidence found',
82
- inconclusive: 'Inconclusive',
83
- ai_edited: 'AI-edited',
84
- ai_processed: 'Processed by an AI image generator',
85
- possible_aigc: 'Possible AI generation',
86
- declared_ai: 'Declared AI-generated or AI-edited',
87
- });
88
-
89
- export const PIXEL_ANALYSIS_WORDS = Object.freeze({
90
- flagged: 'Signs of AI generation detected',
91
- clear: 'No signs found at this image quality',
92
- not_assessable: 'Not yet calibrated for this file type or size',
93
- });
94
-
95
- // Hidden content — never names the checks that ran
96
- export const HIDDEN_CONTENT_WORDS = Object.freeze({
97
- not_analysed: 'Not checked',
98
- none: 'Nothing found by the checks that ran',
99
- anomalies: 'Irregularities found — not conclusive on their own',
100
- unusual_reading: 'An unusual reading — not evidence of hidden content',
101
- watermark_pattern_unconfirmed: 'A pattern was flagged but not confirmed',
102
- generator_watermark_matched: 'A known AI image generator watermark was found',
103
- });
104
-
105
- export const CHECK_WORDS = Object.freeze({
106
- clean: 'Nothing found',
107
- possible: 'Possible signs found',
108
- suspect: 'Signs found',
109
- });
110
-
111
- // Analysis images the full report shows, in order, with their titles
112
- export const IMAGE_TITLES = Object.freeze({
113
- display_image: 'Your file',
114
- face_map: 'Faces found',
115
- text_map: 'Readable text found',
116
- forensic_ela: 'Error Level Analysis',
117
- forensic_ela_anomaly: 'Error Level Analysis — areas that stand out',
118
- forensic_noise_map: 'Noise map',
119
- forensic_clone: 'Copied areas',
120
- });
121
-
122
- // Evidence maps, in the web report's order, with its titles and the line each panel opens with.
123
- // The NSS chart is not a map, but sits in the same group (approved design). Never the ghost curve.
124
- export const EVIDENCE_MAPS = Object.freeze({
125
- forensic_roi: { title: 'Regions', text: 'Boxes show areas where a check found something. Each box has a number. A box is something to look at, not proof of editing.' },
126
- forensic_noise_field: { title: 'Noise', text: 'Colour shows areas with less camera grain than expected. Stronger colour means less grain. Smooth things like sky, water and skin can show colour on their own.' },
127
- forensic_ela_field: { title: 'Compression', text: 'Colour shows areas that change differently when the photo is saved again. Sharp edges and text often differ. Look for a solid patch that stands out from what is around it.' },
128
- forensic_dct_map: { title: 'Save history', text: 'This photo was saved as a JPEG more than once. Colour shows areas that do not share that save history, as a part pasted in from another picture often does. Many edits do not show here, and busy detail can show colour on its own.' },
129
- forensic_nss_chart: { title: 'Natural Scene Statistics Check', text: null },
130
- forensic_ghost_map: { title: 'Earlier save', text: 'Colour marks an area that looks like it was saved as a JPEG at a lower quality before the rest of the photo. A piece pasted in from another photo can do this. Smooth, very bright and very dark areas cannot be read.' },
131
- forensic_camera_map: { title: 'Since the camera', text: 'Your camera saved a small preview inside the file when the photo was taken. Colour marks areas that now look different from that preview. Something added or removed after the photo was taken can show here. Many editing apps replace the preview, and then nothing shows. This is evidence, not a verdict.' },
132
- });
133
-
134
- // The maps replace these older pictures, as on the web report
135
- const REPLACED_BY_MAPS = Object.freeze(['forensic_ela', 'forensic_ela_anomaly', 'forensic_noise_map']);
136
-
137
- export const EVIDENCE_INTRO = 'These maps look for signs of editing only. Your grade also looks at AI, origin and metadata. A quiet map does not mean a good grade.';
138
- export const NO_REGIONS = 'No check marked an area in this photo. This is not proof the photo is unedited. Some edits leave no trace these checks can see.';
139
- export const NO_REGIONS_DCT = 'No check flagged an area in this photo. The Save history map below shows colour on its own terms. This is not proof the photo is unedited. Some edits leave no trace these checks can see.';
140
-
141
- // The five categories behind the two grades, in the web report's order
142
- export const CATEGORY_WORDS = Object.freeze({
143
- origin: 'Origin', manipulation: 'Manipulation', ai_generation: 'AI generation',
144
- privacy: 'Privacy', security: 'Security',
145
- });
146
-
147
- // "Also noted" (schema 1.3), worded as the web report's box under each category
148
- export const ALSO_NOTED_TITLE = 'Also noted - not used for your grade';
149
- export function alsoNotedText(media) {
150
- return `These checks picked something up, but they do the same on most ${media === 'video' ? 'videos' : 'photos'}, including untouched ones. On their own they tell us very little, so they don't change your grade.`;
151
- }
152
-
153
- // When, where and what took it (schema 1.4): the line tags, as on the web report's card
154
- export const CAPTURE_LINES = Object.freeze(['when', 'where', 'what', 'apps']);
155
- export const CAPTURE_SOURCES = Object.freeze({
156
- file: 'From the file',
157
- file_name: 'Inferred from the file name',
158
- fingerprint: 'Inferred from the compression',
159
- });
160
- export const CAPTURE_TITLE = 'When, where and what took it';
161
- export const MAP_LINK_TEXT = 'View on map';
162
- const OSM_CREDIT_URL = 'https://www.openstreetmap.org/copyright';
163
-
164
- // "Since the camera": the preview stored in the file does not line up with the photo
165
- export const CAMERA_NO_MATCH = "The camera's preview does not match this photo. This can happen when a photo is heavily changed or swapped, or when an app crops or rotates it. This is evidence, not a verdict.";
166
-
167
- export const PARTIAL_CARD ="some checks couldn't run.";
168
- export const PARTIAL_FULL = "some checks couldn't run, so this isn't a clean bill of health.";
169
- export const SOFTENED = "Softened by a step because we're less sure about this finding.";
170
- export const WARNING_TAIL = "We've eased this grade because we're not sure. Check the matching card in the report below before relying on it.";
171
-
172
- // Findings are listed most serious first; the card shows the top few
173
- export const SEVERITY_ORDER = Object.freeze({ critical: 0, high: 1, medium: 2, low: 3, info: 4 });
174
- export const MAX_FINDINGS = 5;
175
-
176
- // Attribution links are drawn only when they point at snapWONDERS
177
- export const ATTRIBUTION_HOSTS = Object.freeze(['snapwonders.com']);
178
-
179
- // Link parameters a host may add to the attribution links (e.g. ?src=wp&site=…)
180
- export const LINK_PARAM_KEYS = Object.freeze(['src', 'site', 'r']);
181
-
182
- /**
183
- * Reads `schema_version` ("major.minor"). A result from before versioning carries none and is the
184
- * 1.0 contract. Anything unreadable returns null.
185
- */
186
- export function parseSchemaVersion(value) {
187
- if (value === undefined || value === null) {
188
- return { major: 1, minor: 0 };
189
- }
190
- const match = /^(\d+)\.(\d+)$/.exec(String(value));
191
- if (!match) {
192
- return null;
193
- }
194
- return { major: Number(match[1]), minor: Number(match[2]) };
195
- }
196
-
197
- /**
198
- * Parses a host's link parameters ("src=wp&site=abc") keeping only the allowed keys and plain
199
- * values, so nothing a host passes can turn a snapWONDERS link into something else.
200
- */
201
- export function parseLinkParams(value) {
202
- const out = [];
203
- if (typeof value !== 'string' || value === '') {
204
- return out;
205
- }
206
- for (const pair of value.split('&')) {
207
- const [key, val] = pair.split('=');
208
- if (LINK_PARAM_KEYS.includes(key) && typeof val === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(val)) {
209
- out.push([key, val]);
210
- }
211
- }
212
- return out;
213
- }
214
-
215
- /** An https link on a snapWONDERS host, with the host's link parameters added; otherwise null. */
216
- export function snapwondersLink(value, linkParams = []) {
217
- let url;
218
- try {
219
- url = new URL(String(value));
220
- } catch {
221
- return null;
222
- }
223
- const host = url.hostname.toLowerCase();
224
- const ours = ATTRIBUTION_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
225
- if (url.protocol !== 'https:' || !ours || url.username || url.password) {
226
- return null;
227
- }
228
- for (const [key, val] of linkParams) {
229
- url.searchParams.set(key, val);
230
- }
231
- return url.href;
232
- }
233
-
234
- function has(map, key) {
235
- return typeof key === 'string' && Object.prototype.hasOwnProperty.call(map, key);
236
- }
237
-
238
- function textLink(block, linkParams) {
239
- if (!block || typeof block !== 'object' || typeof block.text !== 'string' || block.text === '') {
240
- return null;
241
- }
242
- const url = snapwondersLink(block.url, linkParams);
243
- return url ? { text: block.text, url } : null;
244
- }
245
-
246
- // Why a headline grade is what it is (schema 1.2). Missing or unreadable: nothing is said.
247
- function explained(file, kind) {
248
- const e = file.explanation && typeof file.explanation === 'object' ? file.explanation[kind] : null;
249
- if (!e || typeof e !== 'object') {
250
- return { weakestArea: null, softened: false, warnings: [], notAssessed: false };
251
- }
252
- return {
253
- weakestArea: has(CATEGORY_WORDS, e.decided_by) ? CATEGORY_WORDS[e.decided_by] : null,
254
- softened: e.softened === true,
255
- warnings: Array.isArray(e.warnings) ? e.warnings.filter((w) => typeof w === 'string' && w.trim() !== '').map((w) => w.trim()) : [],
256
- notAssessed: Array.isArray(e.not_assessed) && e.not_assessed.some((c) => has(CATEGORY_WORDS, c)),
257
- };
258
- }
259
-
260
- // A check's label as a list item: the report's row labels are questions ("Noise level inconsistency?")
261
- function itemLabel(value) {
262
- return typeof value === 'string' ? value.trim().replace(/\?+$/, '').trim() : '';
263
- }
264
-
265
- // The five categories, each with its reasons and (1.3) the checks only noted. Full mode only.
266
- function categories(file) {
267
- const c = file.explanation && file.explanation.categories && typeof file.explanation.categories === 'object' ? file.explanation.categories : {};
268
- return Object.keys(CATEGORY_WORDS)
269
- .filter((k) => c[k] && typeof c[k] === 'object' && has(GRADE_WORDS, c[k].grade))
270
- .map((k) => ({
271
- name: CATEGORY_WORDS[k],
272
- grade: c[k].grade,
273
- reasons: (Array.isArray(c[k].reasons) ? c[k].reasons : [])
274
- .filter((r) => r && itemLabel(r.label) !== '')
275
- .map((r) => ({ label: itemLabel(r.label), reassuring: r.effect === 'reassuring' })),
276
- alsoNoted: (Array.isArray(c[k].also_noted) ? c[k].also_noted : [])
277
- .map((r) => (r ? itemLabel(r.label) : ''))
278
- .filter((l) => l !== ''),
279
- }));
280
- }
281
-
282
- /**
283
- * The evidence maps the host supplies, in order, with what each shows. When no map marks an area,
284
- * the report says so, and that it is not proof of an unedited photo: an absent Regions map is never
285
- * shown as a clean result.
286
- */
287
- function evidenceMaps(file, assetUrl) {
288
- if (typeof assetUrl !== 'function' || !Array.isArray(file.assets)) {
289
- return null;
290
- }
291
- const isImage = (a) => a && typeof a.mime_type === 'string' && a.mime_type.startsWith('image/');
292
- const order = Object.keys(EVIDENCE_MAPS);
293
- const maps = file.assets
294
- .filter((a) => isImage(a) && has(EVIDENCE_MAPS, a.category))
295
- .sort((a, b) => order.indexOf(a.category) - order.indexOf(b.category))
296
- .map((a) => ({ category: a.category, ...EVIDENCE_MAPS[a.category], src: assetUrl(a) }))
297
- .filter((m) => typeof m.src === 'string' && m.src !== '');
298
-
299
- // Since the camera (schema 1.4): whether the map marked anything, and whether the preview lined up
300
- const cam = file.verdicts && file.verdicts.forensic && file.verdicts.forensic.camera_map;
301
- const camKnown = cam && typeof cam === 'object' && typeof cam.marked === 'boolean';
302
- let noMatch = null;
303
- if (cam && cam.matched === false) {
304
- const thumb = file.assets.find((a) => isImage(a) && a.category === 'exif_thumbnail');
305
- const src = thumb ? assetUrl(thumb) : null;
306
- if (typeof src === 'string' && src !== '') {
307
- noMatch = { text: CAMERA_NO_MATCH, preview: { title: "The camera's preview, stored in the file", src } };
308
- }
309
- }
310
- if (!maps.length && !noMatch) {
311
- return null;
312
- }
313
- const shown = (c) => maps.some((m) => m.category === c);
314
- // Before 1.4 a Since-the-camera map may have marked areas we cannot see, so it keeps the note off
315
- const camMarked = shown('forensic_camera_map') && (!camKnown || cam.marked === true);
316
- const marked = shown('forensic_roi') || shown('forensic_ghost_map') || camMarked || noMatch !== null;
317
- return {
318
- intro: EVIDENCE_INTRO,
319
- note: marked ? null : (shown('forensic_dct_map') ? NO_REGIONS_DCT : NO_REGIONS),
320
- noMatch,
321
- maps,
322
- };
323
- }
324
-
325
- // A map link built from the numbers only, never from a name or a URL in the result
326
- function mapUrl(lat, lng) {
327
- if (!Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) {
328
- return null;
329
- }
330
- const la = lat.toFixed(5);
331
- const lo = lng.toFixed(5);
332
- return `https://www.openstreetmap.org/?mlat=${la}&mlon=${lo}#map=15/${la}/${lo}`;
333
- }
334
-
335
- /**
336
- * When, where and what took it (schema 1.4): the web report's card, line for line. Null on older
337
- * results, where the section is hidden. `hideLocation` drops the Where line (public pages).
338
- */
339
- function capture(file, full, hideLocation) {
340
- const c = file.capture;
341
- if (!c || typeof c !== 'object') {
342
- return null;
343
- }
344
- const str = (v) => (typeof v === 'string' ? v.trim() : '');
345
- const lines = [];
346
- for (const id of CAPTURE_LINES) {
347
- const l = c[id];
348
- if (!l || typeof l !== 'object' || str(l.label) === '' || str(l.value) === '') continue;
349
- if (id === 'where' && hideLocation) continue;
350
- const line = {
351
- id,
352
- label: str(l.label),
353
- value: str(l.value),
354
- why: full && str(l.why) !== '' ? str(l.why) : null,
355
- recorded: l.recorded === true,
356
- sources: full && Array.isArray(l.sources) ? [...new Set(l.sources.filter((s) => has(CAPTURE_SOURCES, s)))].map((s) => ({ key: s, text: CAPTURE_SOURCES[s] })) : [],
357
- map: null,
358
- credit: null,
359
- };
360
- if (id === 'where' && l.state === 'location') {
361
- line.map = mapUrl(l.lat, l.lng);
362
- // OpenStreetMap's credit goes wherever the place is shown; only its own copyright page is linked
363
- const credit = l.credit && typeof l.credit === 'object' ? l.credit : null;
364
- line.credit = {
365
- text: credit && str(credit.text) !== '' ? str(credit.text) : 'Map data from OpenStreetMap',
366
- url: OSM_CREDIT_URL,
367
- };
368
- }
369
- lines.push(line);
370
- }
371
- if (!lines.length) {
372
- return null;
373
- }
374
- // Card only: when, where and the camera all say the same "not recorded", say it once
375
- const blank = lines.filter((l) => ['when', 'where', 'what'].includes(l.id) && !l.recorded);
376
- if (!full && blank.length === 3 && blank.every((l) => l.value === blank[0].value)) {
377
- const merged = { ...blank[0], id: 'when_where_what', label: blank.map((l) => l.label).join(' · ') };
378
- lines.splice(lines.indexOf(blank[0]), 3, merged);
379
- }
380
- return { title: CAPTURE_TITLE, lines, tip: full && str(c.tip) !== '' ? str(c.tip) : null };
381
- }
382
-
383
- function headline(kind, grade, confidence, file = {}) {
384
- const graded = has(GRADE_WORDS, grade);
385
- const why = graded ? explained(file, kind) : explained({}, kind);
386
- const flag = file[kind === 'authenticity' ? 'grade_partial_coverage' : 'exposure_partial_coverage'] === true;
387
- return {
388
- weakestArea: why.weakestArea,
389
- softened: why.softened,
390
- warnings: why.warnings,
391
- partial: graded && (flag || why.notAssessed),
392
- kind,
393
- title: kind === 'authenticity' ? 'Authenticity' : 'Exposure',
394
- question: kind === 'authenticity' ? 'Has this file been edited or AI-generated?' : 'What does this file give away?',
395
- grade: graded ? grade : null,
396
- word: graded ? GRADE_WORDS[grade] : "Couldn't tell",
397
- note: graded ? null : "We couldn't check this side of the file. That isn't the same as a clean result.",
398
- confidence: graded && has(CONFIDENCE_WORDS, confidence) ? CONFIDENCE_WORDS[confidence] : null,
399
- lowConfidence: graded && confidence === 'low',
400
- };
401
- }
402
-
403
- function plural(n, one, many) {
404
- return `${n} ${n === 1 ? one : many}`;
405
- }
406
-
407
- function evidence(file, full, version) {
408
- const rows = [];
409
- const verdicts = file.verdicts && typeof file.verdicts === 'object' ? file.verdicts : {};
410
-
411
- // AI generation, and the pixel analysis beside it
412
- const ai = verdicts.ai_generation;
413
- if (ai && has(AI_VERDICT_WORDS, ai.verdict)) {
414
- rows.push({ label: 'AI generation', value: AI_VERDICT_WORDS[ai.verdict] });
415
- }
416
- if (ai && has(PIXEL_ANALYSIS_WORDS, ai.pixel_analysis)) {
417
- rows.push({ label: 'Pixel analysis', value: PIXEL_ANALYSIS_WORDS[ai.pixel_analysis] });
418
- }
419
-
420
- // Content Credentials (C2PA)
421
- const c2pa = verdicts.c2pa;
422
- if (c2pa && c2pa.has_manifest === true) {
423
- rows.push({ label: 'Content Credentials', value: c2pa.trusted === true ? 'Present, trusted signer' : 'Present, signer not verified' });
424
- } else if (full && c2pa && c2pa.has_manifest === false) {
425
- rows.push({ label: 'Content Credentials', value: 'None present' });
426
- }
427
-
428
- // Faces — low-confidence detections are possible faces, never dropped
429
- if (Number.isInteger(file.face_count)) {
430
- const split = file.face_count_by_confidence;
431
- const low = split && Number.isInteger(split.low) ? split.low : 0;
432
- const sure = Math.max(0, file.face_count - low);
433
- const parts = [];
434
- if (sure > 0) parts.push(plural(sure, 'face', 'faces'));
435
- if (low > 0) parts.push(plural(low, 'possible face', 'possible faces'));
436
- rows.push({ label: 'Faces', value: parts.length ? parts.join(', ') : 'None found' });
437
- }
438
-
439
- // Readable text
440
- if (Number.isInteger(file.text_region_count)) {
441
- rows.push({ label: 'Readable text', value: file.text_region_count === 0 ? 'None found' : plural(file.text_region_count, 'area', 'areas') });
442
- }
443
-
444
- // Watermark — the web report's top-card wording, sent by the API as a label
445
- const wm = verdicts.watermark;
446
- if (wm && typeof wm.label === 'string' && wm.label.trim() !== '') {
447
- rows.push({ label: 'Watermark', value: wm.label.trim() });
448
- }
449
-
450
- if (!full) {
451
- return rows;
452
- }
453
-
454
- // Hidden content
455
- const stego = verdicts.steganography;
456
- if (stego && has(HIDDEN_CONTENT_WORDS, stego.verdict)) {
457
- rows.push({ label: 'Hidden content', value: HIDDEN_CONTENT_WORDS[stego.verdict] });
458
- }
459
-
460
- // Encoder fingerprint
461
- const fp = verdicts.camera_fingerprint;
462
- if (fp && fp.applicable === true) {
463
- const name = typeof fp.encoder_name === 'string' && fp.encoder_name !== '' ? fp.encoder_name : null;
464
- rows.push({ label: 'Encoder fingerprint', value: fp.matched === true ? (name ? `Matches ${name}` : 'Matched') : 'No known match' });
465
- }
466
-
467
- // Compression and noise differences — counts only
468
- const ela = verdicts.forensic && verdicts.forensic.ela;
469
- if (ela && typeof ela.high_fraction === 'number' && ela.high_fraction >= 0 && ela.high_fraction <= 1) {
470
- rows.push({ label: 'Compression differences', value: `${Math.round(ela.high_fraction * 100)}% of the image` });
471
- }
472
- // Noise differences: only from schema 1.2, where anomaly_tile_count counts the same tiles as the
473
- // web report. Before 1.2 it was an older count that could contradict the Regions map.
474
- const noise = verdicts.forensic && verdicts.forensic.noise_inconsistency;
475
- const sameCountAsWeb = version !== null && (version.major > 1 || version.minor >= 2);
476
- if (sameCountAsWeb && noise && Number.isInteger(noise.anomaly_tile_count)) {
477
- rows.push({ label: 'Noise differences', value: noise.anomaly_tile_count === 0 ? 'None found' : plural(noise.anomaly_tile_count, 'area', 'areas') });
478
- }
479
-
480
- // Video and audio checks
481
- const audio = verdicts.audio_splice;
482
- if (audio && has(CHECK_WORDS, audio.verdict)) {
483
- rows.push({ label: 'Audio edits', value: CHECK_WORDS[audio.verdict] });
484
- }
485
- const video = verdicts.video_tamper || {};
486
- if (video.inter_frame_tamper && has(CHECK_WORDS, video.inter_frame_tamper.verdict)) {
487
- rows.push({ label: 'Frame-to-frame edits', value: CHECK_WORDS[video.inter_frame_tamper.verdict] });
488
- }
489
- if (video.frame_duplicate && has(CHECK_WORDS, video.frame_duplicate.dup_verdict)) {
490
- rows.push({ label: 'Repeated frames', value: CHECK_WORDS[video.frame_duplicate.dup_verdict] });
491
- }
492
- return rows;
493
- }
494
-
495
- function findings(file, full) {
496
- const list = file.verdicts && Array.isArray(file.verdicts.findings) ? file.verdicts.findings : [];
497
- const clean = list
498
- .filter((f) => f && typeof f.label === 'string' && f.label !== '')
499
- .map((f) => ({ label: f.label, severity: has(SEVERITY_ORDER, f.severity) ? f.severity : 'info' }))
500
- .sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
501
- const cap = full ? clean.length : MAX_FINDINGS;
502
- return { shown: clean.slice(0, cap), more: Math.max(0, clean.length - cap) };
503
- }
504
-
505
- /**
506
- * The analysis images, in display order. The renderer never fetches anything itself: the host's
507
- * `assetUrl(asset)` maps each asset to where the host keeps it (its own server, its uploads
508
- * folder). Assets it returns nothing for are left out.
509
- */
510
- function images(file, assetUrl, mapsShown) {
511
- if (typeof assetUrl !== 'function' || !Array.isArray(file.assets)) {
512
- return [];
513
- }
514
- const order = Object.keys(IMAGE_TITLES);
515
- return file.assets
516
- .filter((a) => a && has(IMAGE_TITLES, a.category) && typeof a.mime_type === 'string' && a.mime_type.startsWith('image/'))
517
- .filter((a) => !(mapsShown && REPLACED_BY_MAPS.includes(a.category)))
518
- .sort((a, b) => order.indexOf(a.category) - order.indexOf(b.category))
519
- .map((a) => ({ title: IMAGE_TITLES[a.category], category: a.category, src: assetUrl(a) }))
520
- .filter((i) => typeof i.src === 'string' && i.src !== '');
521
- }
522
-
523
- /**
524
- * Builds the view model.
525
- *
526
- * @param {object} result the JSON from GET /api/analyse/result/{job_uid}
527
- * @param {{fileIndex?: number, mode?: 'card'|'full', assetUrl?: function, linkParams?: string}} [options]
528
- * @returns {object} `{ok: false, message}` when there is nothing to show
529
- */
530
- export function buildCardModel(result, options = {}) {
531
- if (!result || typeof result !== 'object' || !Array.isArray(result.files)) {
532
- return { ok: false, message: 'No result to show.' };
533
- }
534
- const fileIndex = Number.isInteger(options.fileIndex) ? options.fileIndex : 0;
535
- const file = result.files[fileIndex];
536
- if (!file || typeof file !== 'object') {
537
- return { ok: false, message: 'No result to show.' };
538
- }
539
- const full = options.mode === 'full';
540
- const linkParams = parseLinkParams(options.linkParams);
541
- const version = parseSchemaVersion(result.schema_version);
542
- const maps = full ? evidenceMaps(file, options.assetUrl) : null;
543
- const media = file.verdicts && file.verdicts.video_tamper ? 'video' : 'photo';
544
- return {
545
- ok: true,
546
- mode: full ? 'full' : 'card',
547
- updateAvailable: isNewerSchema(version),
548
- // Null when none is due or the user dismissed it for this version
549
- update: updateNote(version, options.dismissedUpdate),
550
- name: typeof file.name === 'string' ? file.name : '',
551
- headlines: [
552
- headline('authenticity', file.grade, file.confidence, file),
553
- headline('exposure', file.exposure_grade, file.exposure_confidence, file),
554
- ],
555
- capture: capture(file, full, options.hideLocation === true),
556
- evidence: evidence(file, full, version),
557
- findings: findings(file, full),
558
- categories: full ? categories(file) : [],
559
- alsoNoted: { title: ALSO_NOTED_TITLE, text: alsoNotedText(media) },
560
- evidenceMaps: maps,
561
- images: full ? images(file, options.assetUrl, maps !== null && maps.maps.some((m) => m.category !== 'forensic_nss_chart')) : [],
562
- // Service output only (schema 1.1): the renderer never adds a credit of its own
563
- attribution: textLink(result.attribution, linkParams),
564
- vaultifyCta: textLink(file.vaultify_cta, linkParams),
565
- };
566
- }
1
+ /*
2
+ * snapWONDERS API — Result renderer (JavaScript)
3
+ * API version: 1.0
4
+ *
5
+ * Copyright (c) 2026 Kenneth Springer @ snapWONDERS. MIT Licensed — see LICENSE.
6
+ * The MIT licence covers this client library only; the snapWONDERS API it calls is proprietary.
7
+ *
8
+ * Author: Kenneth Springer @ snapWONDERS <kenneth@snapwonders.com> (https://kennethbspringer.au)
9
+ *
10
+ * All the snapWONDERS API services are available over the Clearnet / **Web** and Dark Web **Tor** and **I2P**
11
+ * Read details: https://snapwonders.com/developers
12
+ */
13
+
14
+ /**
15
+ * Turns one analyse result (GET /api/analyse/result/{job_uid}) into a plain view model, for the
16
+ * card or the full report. No DOM and no network here, so it runs (and is tested) anywhere. The
17
+ * wording mirrors the snapWONDERS report page, so every surface says the same thing.
18
+ */
19
+
20
+ // The result contract this renderer understands. A result with any newer version, minor too, gets a
21
+ // non-blocking "new version available" note; everything this renderer knows is still drawn.
22
+ export const SUPPORTED_SCHEMA_MAJOR = 1;
23
+ export const SUPPORTED_SCHEMA_MINOR = 5;
24
+ export const SUPPORTED_SCHEMA = `${SUPPORTED_SCHEMA_MAJOR}.${SUPPORTED_SCHEMA_MINOR}`;
25
+
26
+ // Where the note links unless the host (extension, plugin, app) passes its own release notes
27
+ export const DEFAULT_RELEASE_NOTES_URL = 'https://github.com/snapWONDERS/snapWONDERS-Report/blob/main/CHANGELOG.md';
28
+
29
+ /**
30
+ * True when a result is newer than this renderer (any bump, minor too) or its version is unreadable.
31
+ */
32
+ export function isNewerSchema(version) {
33
+ if (version === null) return true;
34
+ if (version.major !== SUPPORTED_SCHEMA_MAJOR) return version.major > SUPPORTED_SCHEMA_MAJOR;
35
+ return version.minor > SUPPORTED_SCHEMA_MINOR;
36
+ }
37
+
38
+ // The update note's wording: gentle for a minor bump (fields only added), firmer for a major one
39
+ // (a field changed meaning or was removed) or an unreadable version (owner 2026-11-20)
40
+ export const UPDATE_NOTE = Object.freeze({
41
+ minor: 'A new version is available, with more in this report.',
42
+ major: 'Update needed: this report comes from a newer snapWONDERS version, so some parts may be missing or shown wrongly.',
43
+ });
44
+
45
+ /**
46
+ * The update note for a result, or null when none is due. The note is dismissable: the host keeps the
47
+ * version the user dismissed (`dismissedUpdate`, e.g. in extension storage) and the note stays hidden
48
+ * for that version and older ones, and comes back on the next version.
49
+ */
50
+ function updateNote(version, dismissedUpdate) {
51
+ if (!isNewerSchema(version)) return null;
52
+ const level = version === null || version.major > SUPPORTED_SCHEMA_MAJOR ? 'major' : 'minor';
53
+ const dismissed = typeof dismissedUpdate === 'string' ? parseSchemaVersion(dismissedUpdate) : null;
54
+ if (version !== null && dismissed !== null
55
+ && (dismissed.major > version.major || (dismissed.major === version.major && dismissed.minor >= version.minor))) {
56
+ return null;
57
+ }
58
+ return {
59
+ level,
60
+ text: UPDATE_NOTE[level],
61
+ schemaVersion: version === null ? null : `${version.major}.${version.minor}`,
62
+ };
63
+ }
64
+
65
+ // Grade words, as on the report page
66
+ export const GRADE_WORDS = Object.freeze({
67
+ A: 'Nothing significant found',
68
+ B: 'Low risk',
69
+ C: 'Moderate risk',
70
+ D: 'High risk',
71
+ F: 'Critical',
72
+ });
73
+
74
+ export const CONFIDENCE_WORDS = Object.freeze({ high: 'High', medium: 'Medium', low: 'Low' });
75
+
76
+ // AI generation verdicts, as on the report page's AI card
77
+ export const AI_VERDICT_WORDS = Object.freeze({
78
+ likely_authentic: 'Verified camera capture',
79
+ likely_real: 'Likely real (camera signals)',
80
+ real_edited: 'Real capture, edited',
81
+ no_evidence: 'No AI-generation evidence found',
82
+ inconclusive: 'Inconclusive',
83
+ ai_edited: 'AI-edited',
84
+ ai_processed: 'Processed by an AI image generator',
85
+ possible_aigc: 'Possible AI generation',
86
+ declared_ai: 'Declared AI-generated or AI-edited',
87
+ });
88
+
89
+ export const PIXEL_ANALYSIS_WORDS = Object.freeze({
90
+ flagged: 'Signs of AI generation detected',
91
+ clear: 'No signs found at this image quality',
92
+ not_assessable: 'Not yet calibrated for this file type or size',
93
+ });
94
+
95
+ // Hidden content — never names the checks that ran
96
+ export const HIDDEN_CONTENT_WORDS = Object.freeze({
97
+ not_analysed: 'Not checked',
98
+ none: 'Nothing found by the checks that ran',
99
+ anomalies: 'Irregularities found — not conclusive on their own',
100
+ unusual_reading: 'An unusual reading — not evidence of hidden content',
101
+ watermark_pattern_unconfirmed: 'A pattern was flagged but not confirmed',
102
+ generator_watermark_matched: 'A known AI image generator watermark was found',
103
+ });
104
+
105
+ export const CHECK_WORDS = Object.freeze({
106
+ clean: 'Nothing found',
107
+ possible: 'Possible signs found',
108
+ suspect: 'Signs found',
109
+ });
110
+
111
+ // Analysis images the full report shows, in order, with their titles
112
+ export const IMAGE_TITLES = Object.freeze({
113
+ display_image: 'Your file',
114
+ face_map: 'Faces found',
115
+ text_map: 'Readable text found',
116
+ forensic_ela: 'Error Level Analysis',
117
+ forensic_ela_anomaly: 'Error Level Analysis — areas that stand out',
118
+ forensic_noise_map: 'Noise map',
119
+ forensic_clone: 'Copied areas',
120
+ });
121
+
122
+ // Evidence maps, in the web report's order, with its titles and the line each panel opens with.
123
+ // The NSS chart is not a map, but sits in the same group (approved design). Never the ghost curve.
124
+ export const EVIDENCE_MAPS = Object.freeze({
125
+ forensic_roi: { title: 'Regions', text: 'Boxes show areas where a check found something. Each box has a number. A box is something to look at, not proof of editing.' },
126
+ forensic_noise_field: { title: 'Noise', text: 'Colour shows areas with less camera grain than expected. Stronger colour means less grain. Smooth things like sky, water and skin can show colour on their own.' },
127
+ forensic_ela_field: { title: 'Compression', text: 'Colour shows areas that change differently when the photo is saved again. Sharp edges and text often differ. Look for a solid patch that stands out from what is around it.' },
128
+ forensic_dct_map: { title: 'Save history', text: 'This photo was saved as a JPEG more than once. Colour shows areas that do not share that save history, as a part pasted in from another picture often does. Many edits do not show here, and busy detail can show colour on its own.' },
129
+ forensic_nss_chart: { title: 'Natural Scene Statistics Check', text: null },
130
+ forensic_ghost_map: { title: 'Earlier save', text: 'Colour marks an area that looks like it was saved as a JPEG at a lower quality before the rest of the photo. A piece pasted in from another photo can do this. Smooth, very bright and very dark areas cannot be read.' },
131
+ forensic_camera_map: { title: 'Since the camera', text: 'Your camera saved a small preview inside the file when the photo was taken. Colour marks areas that now look different from that preview. Something added or removed after the photo was taken can show here. Many editing apps replace the preview, and then nothing shows. This is evidence, not a verdict.' },
132
+ });
133
+
134
+ // The maps replace these older pictures, as on the web report
135
+ const REPLACED_BY_MAPS = Object.freeze(['forensic_ela', 'forensic_ela_anomaly', 'forensic_noise_map']);
136
+
137
+ export const EVIDENCE_INTRO = 'These maps look for signs of editing only. Your grade also looks at AI, origin and metadata. A quiet map does not mean a good grade.';
138
+ export const NO_REGIONS = 'No check marked an area in this photo. This is not proof the photo is unedited. Some edits leave no trace these checks can see.';
139
+ export const NO_REGIONS_DCT = 'No check flagged an area in this photo. The Save history map below shows colour on its own terms. This is not proof the photo is unedited. Some edits leave no trace these checks can see.';
140
+
141
+ // The five categories behind the two grades, in the web report's order
142
+ export const CATEGORY_WORDS = Object.freeze({
143
+ origin: 'Origin', manipulation: 'Manipulation', ai_generation: 'AI generation',
144
+ privacy: 'Privacy', security: 'Security',
145
+ });
146
+
147
+ // "Also noted" (schema 1.3), worded as the web report's box under each category
148
+ export const ALSO_NOTED_TITLE = 'Also noted - not used for your grade';
149
+ export function alsoNotedText(media) {
150
+ return `These checks picked something up, but they do the same on most ${media === 'video' ? 'videos' : 'photos'}, including untouched ones. On their own they tell us very little, so they don't change your grade.`;
151
+ }
152
+
153
+ // When, where and what took it (schema 1.4): the line tags, as on the web report's card
154
+ export const CAPTURE_LINES = Object.freeze(['when', 'where', 'what', 'apps']);
155
+ export const CAPTURE_SOURCES = Object.freeze({
156
+ file: 'From the file',
157
+ file_name: 'Inferred from the file name',
158
+ fingerprint: 'Inferred from the compression',
159
+ });
160
+ export const CAPTURE_TITLE = 'When, where and what took it';
161
+ export const MAP_LINK_TEXT = 'View on map';
162
+ const OSM_CREDIT_URL = 'https://www.openstreetmap.org/copyright';
163
+
164
+ // "Since the camera": the preview stored in the file does not line up with the photo
165
+ export const CAMERA_NO_MATCH = "The camera's preview does not match this photo. This can happen when a photo is heavily changed or swapped, or when an app crops or rotates it. This is evidence, not a verdict.";
166
+
167
+ export const PARTIAL_CARD ="some checks couldn't run.";
168
+ export const PARTIAL_FULL = "some checks couldn't run, so this isn't a clean bill of health.";
169
+ export const SOFTENED = "Softened by a step because we're less sure about this finding.";
170
+ export const WARNING_TAIL = "We've eased this grade because we're not sure. Check the matching card in the report below before relying on it.";
171
+
172
+ // Findings are listed most serious first; the card shows the top few
173
+ export const SEVERITY_ORDER = Object.freeze({ critical: 0, high: 1, medium: 2, low: 3, info: 4 });
174
+ export const MAX_FINDINGS = 5;
175
+
176
+ // Attribution links are drawn only when they point at snapWONDERS
177
+ export const ATTRIBUTION_HOSTS = Object.freeze(['snapwonders.com']);
178
+
179
+ // Link parameters a host may add to the attribution links (e.g. ?src=wp&site=…)
180
+ export const LINK_PARAM_KEYS = Object.freeze(['src', 'site', 'r']);
181
+
182
+ /**
183
+ * Reads `schema_version` ("major.minor"). A result from before versioning carries none and is the
184
+ * 1.0 contract. Anything unreadable returns null.
185
+ */
186
+ export function parseSchemaVersion(value) {
187
+ if (value === undefined || value === null) {
188
+ return { major: 1, minor: 0 };
189
+ }
190
+ const match = /^(\d+)\.(\d+)$/.exec(String(value));
191
+ if (!match) {
192
+ return null;
193
+ }
194
+ return { major: Number(match[1]), minor: Number(match[2]) };
195
+ }
196
+
197
+ /**
198
+ * Parses a host's link parameters ("src=wp&site=abc") keeping only the allowed keys and plain
199
+ * values, so nothing a host passes can turn a snapWONDERS link into something else.
200
+ */
201
+ export function parseLinkParams(value) {
202
+ const out = [];
203
+ if (typeof value !== 'string' || value === '') {
204
+ return out;
205
+ }
206
+ for (const pair of value.split('&')) {
207
+ const [key, val] = pair.split('=');
208
+ if (LINK_PARAM_KEYS.includes(key) && typeof val === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(val)) {
209
+ out.push([key, val]);
210
+ }
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /** An https link on a snapWONDERS host, with the host's link parameters added; otherwise null. */
216
+ export function snapwondersLink(value, linkParams = []) {
217
+ let url;
218
+ try {
219
+ url = new URL(String(value));
220
+ } catch {
221
+ return null;
222
+ }
223
+ const host = url.hostname.toLowerCase();
224
+ const ours = ATTRIBUTION_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
225
+ if (url.protocol !== 'https:' || !ours || url.username || url.password) {
226
+ return null;
227
+ }
228
+ for (const [key, val] of linkParams) {
229
+ url.searchParams.set(key, val);
230
+ }
231
+ return url.href;
232
+ }
233
+
234
+ function has(map, key) {
235
+ return typeof key === 'string' && Object.prototype.hasOwnProperty.call(map, key);
236
+ }
237
+
238
+ // Which file was checked (schema 1.5): one line, drawn word for word. Missing or unreadable: no line.
239
+ function checkedFile(result) {
240
+ const block = result.checked_file;
241
+ if (!block || typeof block !== 'object' || typeof block.text !== 'string' || block.text.trim() === '') {
242
+ return null;
243
+ }
244
+ return { kind: typeof block.kind === 'string' ? block.kind : null, text: block.text.trim() };
245
+ }
246
+
247
+ function textLink(block, linkParams) {
248
+ if (!block || typeof block !== 'object' || typeof block.text !== 'string' || block.text === '') {
249
+ return null;
250
+ }
251
+ const url = snapwondersLink(block.url, linkParams);
252
+ return url ? { text: block.text, url } : null;
253
+ }
254
+
255
+ // Why a headline grade is what it is (schema 1.2). Missing or unreadable: nothing is said.
256
+ function explained(file, kind) {
257
+ const e = file.explanation && typeof file.explanation === 'object' ? file.explanation[kind] : null;
258
+ if (!e || typeof e !== 'object') {
259
+ return { weakestArea: null, softened: false, warnings: [], notAssessed: false };
260
+ }
261
+ return {
262
+ weakestArea: has(CATEGORY_WORDS, e.decided_by) ? CATEGORY_WORDS[e.decided_by] : null,
263
+ softened: e.softened === true,
264
+ warnings: Array.isArray(e.warnings) ? e.warnings.filter((w) => typeof w === 'string' && w.trim() !== '').map((w) => w.trim()) : [],
265
+ notAssessed: Array.isArray(e.not_assessed) && e.not_assessed.some((c) => has(CATEGORY_WORDS, c)),
266
+ };
267
+ }
268
+
269
+ // A check's label as a list item: the report's row labels are questions ("Noise level inconsistency?")
270
+ function itemLabel(value) {
271
+ return typeof value === 'string' ? value.trim().replace(/\?+$/, '').trim() : '';
272
+ }
273
+
274
+ // The five categories, each with its reasons and (1.3) the checks only noted. Full mode only.
275
+ function categories(file) {
276
+ const c = file.explanation && file.explanation.categories && typeof file.explanation.categories === 'object' ? file.explanation.categories : {};
277
+ return Object.keys(CATEGORY_WORDS)
278
+ .filter((k) => c[k] && typeof c[k] === 'object' && has(GRADE_WORDS, c[k].grade))
279
+ .map((k) => ({
280
+ name: CATEGORY_WORDS[k],
281
+ grade: c[k].grade,
282
+ reasons: (Array.isArray(c[k].reasons) ? c[k].reasons : [])
283
+ .filter((r) => r && itemLabel(r.label) !== '')
284
+ .map((r) => ({ label: itemLabel(r.label), reassuring: r.effect === 'reassuring' })),
285
+ alsoNoted: (Array.isArray(c[k].also_noted) ? c[k].also_noted : [])
286
+ .map((r) => (r ? itemLabel(r.label) : ''))
287
+ .filter((l) => l !== ''),
288
+ }));
289
+ }
290
+
291
+ /**
292
+ * The evidence maps the host supplies, in order, with what each shows. When no map marks an area,
293
+ * the report says so, and that it is not proof of an unedited photo: an absent Regions map is never
294
+ * shown as a clean result.
295
+ */
296
+ function evidenceMaps(file, assetUrl) {
297
+ if (typeof assetUrl !== 'function' || !Array.isArray(file.assets)) {
298
+ return null;
299
+ }
300
+ const isImage = (a) => a && typeof a.mime_type === 'string' && a.mime_type.startsWith('image/');
301
+ const order = Object.keys(EVIDENCE_MAPS);
302
+ const maps = file.assets
303
+ .filter((a) => isImage(a) && has(EVIDENCE_MAPS, a.category))
304
+ .sort((a, b) => order.indexOf(a.category) - order.indexOf(b.category))
305
+ .map((a) => ({ category: a.category, ...EVIDENCE_MAPS[a.category], src: assetUrl(a) }))
306
+ .filter((m) => typeof m.src === 'string' && m.src !== '');
307
+
308
+ // Since the camera (schema 1.4): whether the map marked anything, and whether the preview lined up
309
+ const cam = file.verdicts && file.verdicts.forensic && file.verdicts.forensic.camera_map;
310
+ const camKnown = cam && typeof cam === 'object' && typeof cam.marked === 'boolean';
311
+ let noMatch = null;
312
+ if (cam && cam.matched === false) {
313
+ const thumb = file.assets.find((a) => isImage(a) && a.category === 'exif_thumbnail');
314
+ const src = thumb ? assetUrl(thumb) : null;
315
+ if (typeof src === 'string' && src !== '') {
316
+ noMatch = { text: CAMERA_NO_MATCH, preview: { title: "The camera's preview, stored in the file", src } };
317
+ }
318
+ }
319
+ if (!maps.length && !noMatch) {
320
+ return null;
321
+ }
322
+ const shown = (c) => maps.some((m) => m.category === c);
323
+ // Before 1.4 a Since-the-camera map may have marked areas we cannot see, so it keeps the note off
324
+ const camMarked = shown('forensic_camera_map') && (!camKnown || cam.marked === true);
325
+ const marked = shown('forensic_roi') || shown('forensic_ghost_map') || camMarked || noMatch !== null;
326
+ return {
327
+ intro: EVIDENCE_INTRO,
328
+ note: marked ? null : (shown('forensic_dct_map') ? NO_REGIONS_DCT : NO_REGIONS),
329
+ noMatch,
330
+ maps,
331
+ };
332
+ }
333
+
334
+ // A map link built from the numbers only, never from a name or a URL in the result
335
+ function mapUrl(lat, lng) {
336
+ if (!Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) {
337
+ return null;
338
+ }
339
+ const la = lat.toFixed(5);
340
+ const lo = lng.toFixed(5);
341
+ return `https://www.openstreetmap.org/?mlat=${la}&mlon=${lo}#map=15/${la}/${lo}`;
342
+ }
343
+
344
+ /**
345
+ * When, where and what took it (schema 1.4): the web report's card, line for line. Null on older
346
+ * results, where the section is hidden. `hideLocation` drops the Where line (public pages).
347
+ */
348
+ function capture(file, full, hideLocation) {
349
+ const c = file.capture;
350
+ if (!c || typeof c !== 'object') {
351
+ return null;
352
+ }
353
+ const str = (v) => (typeof v === 'string' ? v.trim() : '');
354
+ const lines = [];
355
+ for (const id of CAPTURE_LINES) {
356
+ const l = c[id];
357
+ if (!l || typeof l !== 'object' || str(l.label) === '' || str(l.value) === '') continue;
358
+ if (id === 'where' && hideLocation) continue;
359
+ const line = {
360
+ id,
361
+ label: str(l.label),
362
+ value: str(l.value),
363
+ why: full && str(l.why) !== '' ? str(l.why) : null,
364
+ recorded: l.recorded === true,
365
+ sources: full && Array.isArray(l.sources) ? [...new Set(l.sources.filter((s) => has(CAPTURE_SOURCES, s)))].map((s) => ({ key: s, text: CAPTURE_SOURCES[s] })) : [],
366
+ map: null,
367
+ credit: null,
368
+ };
369
+ if (id === 'where' && l.state === 'location') {
370
+ line.map = mapUrl(l.lat, l.lng);
371
+ // OpenStreetMap's credit goes wherever the place is shown; only its own copyright page is linked
372
+ const credit = l.credit && typeof l.credit === 'object' ? l.credit : null;
373
+ line.credit = {
374
+ text: credit && str(credit.text) !== '' ? str(credit.text) : 'Map data from OpenStreetMap',
375
+ url: OSM_CREDIT_URL,
376
+ };
377
+ }
378
+ lines.push(line);
379
+ }
380
+ if (!lines.length) {
381
+ return null;
382
+ }
383
+ // Card only: when, where and the camera all say the same "not recorded", say it once
384
+ const blank = lines.filter((l) => ['when', 'where', 'what'].includes(l.id) && !l.recorded);
385
+ if (!full && blank.length === 3 && blank.every((l) => l.value === blank[0].value)) {
386
+ const merged = { ...blank[0], id: 'when_where_what', label: blank.map((l) => l.label).join(' · ') };
387
+ lines.splice(lines.indexOf(blank[0]), 3, merged);
388
+ }
389
+ return { title: CAPTURE_TITLE, lines, tip: full && str(c.tip) !== '' ? str(c.tip) : null };
390
+ }
391
+
392
+ function headline(kind, grade, confidence, file = {}) {
393
+ const graded = has(GRADE_WORDS, grade);
394
+ const why = graded ? explained(file, kind) : explained({}, kind);
395
+ const flag = file[kind === 'authenticity' ? 'grade_partial_coverage' : 'exposure_partial_coverage'] === true;
396
+ return {
397
+ weakestArea: why.weakestArea,
398
+ softened: why.softened,
399
+ warnings: why.warnings,
400
+ partial: graded && (flag || why.notAssessed),
401
+ kind,
402
+ title: kind === 'authenticity' ? 'Authenticity' : 'Exposure',
403
+ question: kind === 'authenticity' ? 'Has this file been edited or AI-generated?' : 'What does this file give away?',
404
+ grade: graded ? grade : null,
405
+ word: graded ? GRADE_WORDS[grade] : "Couldn't tell",
406
+ note: graded ? null : "We couldn't check this side of the file. That isn't the same as a clean result.",
407
+ confidence: graded && has(CONFIDENCE_WORDS, confidence) ? CONFIDENCE_WORDS[confidence] : null,
408
+ lowConfidence: graded && confidence === 'low',
409
+ };
410
+ }
411
+
412
+ function plural(n, one, many) {
413
+ return `${n} ${n === 1 ? one : many}`;
414
+ }
415
+
416
+ function evidence(file, full, version) {
417
+ const rows = [];
418
+ const verdicts = file.verdicts && typeof file.verdicts === 'object' ? file.verdicts : {};
419
+
420
+ // AI generation, and the pixel analysis beside it
421
+ const ai = verdicts.ai_generation;
422
+ if (ai && has(AI_VERDICT_WORDS, ai.verdict)) {
423
+ rows.push({ label: 'AI generation', value: AI_VERDICT_WORDS[ai.verdict] });
424
+ }
425
+ if (ai && has(PIXEL_ANALYSIS_WORDS, ai.pixel_analysis)) {
426
+ rows.push({ label: 'Pixel analysis', value: PIXEL_ANALYSIS_WORDS[ai.pixel_analysis] });
427
+ }
428
+
429
+ // Content Credentials (C2PA)
430
+ const c2pa = verdicts.c2pa;
431
+ if (c2pa && c2pa.has_manifest === true) {
432
+ rows.push({ label: 'Content Credentials', value: c2pa.trusted === true ? 'Present, trusted signer' : 'Present, signer not verified' });
433
+ } else if (full && c2pa && c2pa.has_manifest === false) {
434
+ rows.push({ label: 'Content Credentials', value: 'None present' });
435
+ }
436
+
437
+ // Faces — low-confidence detections are possible faces, never dropped
438
+ if (Number.isInteger(file.face_count)) {
439
+ const split = file.face_count_by_confidence;
440
+ const low = split && Number.isInteger(split.low) ? split.low : 0;
441
+ const sure = Math.max(0, file.face_count - low);
442
+ const parts = [];
443
+ if (sure > 0) parts.push(plural(sure, 'face', 'faces'));
444
+ if (low > 0) parts.push(plural(low, 'possible face', 'possible faces'));
445
+ rows.push({ label: 'Faces', value: parts.length ? parts.join(', ') : 'None found' });
446
+ }
447
+
448
+ // Readable text
449
+ if (Number.isInteger(file.text_region_count)) {
450
+ rows.push({ label: 'Readable text', value: file.text_region_count === 0 ? 'None found' : plural(file.text_region_count, 'area', 'areas') });
451
+ }
452
+
453
+ // Watermark — the web report's top-card wording, sent by the API as a label
454
+ const wm = verdicts.watermark;
455
+ if (wm && typeof wm.label === 'string' && wm.label.trim() !== '') {
456
+ rows.push({ label: 'Watermark', value: wm.label.trim() });
457
+ }
458
+
459
+ if (!full) {
460
+ return rows;
461
+ }
462
+
463
+ // Hidden content
464
+ const stego = verdicts.steganography;
465
+ if (stego && has(HIDDEN_CONTENT_WORDS, stego.verdict)) {
466
+ rows.push({ label: 'Hidden content', value: HIDDEN_CONTENT_WORDS[stego.verdict] });
467
+ }
468
+
469
+ // Encoder fingerprint
470
+ const fp = verdicts.camera_fingerprint;
471
+ if (fp && fp.applicable === true) {
472
+ const name = typeof fp.encoder_name === 'string' && fp.encoder_name !== '' ? fp.encoder_name : null;
473
+ rows.push({ label: 'Encoder fingerprint', value: fp.matched === true ? (name ? `Matches ${name}` : 'Matched') : 'No known match' });
474
+ }
475
+
476
+ // Compression and noise differences — counts only
477
+ const ela = verdicts.forensic && verdicts.forensic.ela;
478
+ if (ela && typeof ela.high_fraction === 'number' && ela.high_fraction >= 0 && ela.high_fraction <= 1) {
479
+ rows.push({ label: 'Compression differences', value: `${Math.round(ela.high_fraction * 100)}% of the image` });
480
+ }
481
+ // Noise differences: only from schema 1.2, where anomaly_tile_count counts the same tiles as the
482
+ // web report. Before 1.2 it was an older count that could contradict the Regions map.
483
+ const noise = verdicts.forensic && verdicts.forensic.noise_inconsistency;
484
+ const sameCountAsWeb = version !== null && (version.major > 1 || version.minor >= 2);
485
+ if (sameCountAsWeb && noise && Number.isInteger(noise.anomaly_tile_count)) {
486
+ rows.push({ label: 'Noise differences', value: noise.anomaly_tile_count === 0 ? 'None found' : plural(noise.anomaly_tile_count, 'area', 'areas') });
487
+ }
488
+
489
+ // Video and audio checks
490
+ const audio = verdicts.audio_splice;
491
+ if (audio && has(CHECK_WORDS, audio.verdict)) {
492
+ rows.push({ label: 'Audio edits', value: CHECK_WORDS[audio.verdict] });
493
+ }
494
+ const video = verdicts.video_tamper || {};
495
+ if (video.inter_frame_tamper && has(CHECK_WORDS, video.inter_frame_tamper.verdict)) {
496
+ rows.push({ label: 'Frame-to-frame edits', value: CHECK_WORDS[video.inter_frame_tamper.verdict] });
497
+ }
498
+ if (video.frame_duplicate && has(CHECK_WORDS, video.frame_duplicate.dup_verdict)) {
499
+ rows.push({ label: 'Repeated frames', value: CHECK_WORDS[video.frame_duplicate.dup_verdict] });
500
+ }
501
+ return rows;
502
+ }
503
+
504
+ function findings(file, full) {
505
+ const list = file.verdicts && Array.isArray(file.verdicts.findings) ? file.verdicts.findings : [];
506
+ const clean = list
507
+ .filter((f) => f && typeof f.label === 'string' && f.label !== '')
508
+ .map((f) => ({ label: f.label, severity: has(SEVERITY_ORDER, f.severity) ? f.severity : 'info' }))
509
+ .sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
510
+ const cap = full ? clean.length : MAX_FINDINGS;
511
+ return { shown: clean.slice(0, cap), more: Math.max(0, clean.length - cap) };
512
+ }
513
+
514
+ /**
515
+ * The analysis images, in display order. The renderer never fetches anything itself: the host's
516
+ * `assetUrl(asset)` maps each asset to where the host keeps it (its own server, its uploads
517
+ * folder). Assets it returns nothing for are left out.
518
+ */
519
+ function images(file, assetUrl, mapsShown) {
520
+ if (typeof assetUrl !== 'function' || !Array.isArray(file.assets)) {
521
+ return [];
522
+ }
523
+ const order = Object.keys(IMAGE_TITLES);
524
+ return file.assets
525
+ .filter((a) => a && has(IMAGE_TITLES, a.category) && typeof a.mime_type === 'string' && a.mime_type.startsWith('image/'))
526
+ .filter((a) => !(mapsShown && REPLACED_BY_MAPS.includes(a.category)))
527
+ .sort((a, b) => order.indexOf(a.category) - order.indexOf(b.category))
528
+ .map((a) => ({ title: IMAGE_TITLES[a.category], category: a.category, src: assetUrl(a) }))
529
+ .filter((i) => typeof i.src === 'string' && i.src !== '');
530
+ }
531
+
532
+ /**
533
+ * Builds the view model.
534
+ *
535
+ * @param {object} result the JSON from GET /api/analyse/result/{job_uid}
536
+ * @param {{fileIndex?: number, mode?: 'card'|'full', assetUrl?: function, linkParams?: string}} [options]
537
+ * @returns {object} `{ok: false, message}` when there is nothing to show
538
+ */
539
+ export function buildCardModel(result, options = {}) {
540
+ if (!result || typeof result !== 'object' || !Array.isArray(result.files)) {
541
+ return { ok: false, message: 'No result to show.' };
542
+ }
543
+ const fileIndex = Number.isInteger(options.fileIndex) ? options.fileIndex : 0;
544
+ const file = result.files[fileIndex];
545
+ if (!file || typeof file !== 'object') {
546
+ return { ok: false, message: 'No result to show.' };
547
+ }
548
+ const full = options.mode === 'full';
549
+ const linkParams = parseLinkParams(options.linkParams);
550
+ const version = parseSchemaVersion(result.schema_version);
551
+ const maps = full ? evidenceMaps(file, options.assetUrl) : null;
552
+ const media = file.verdicts && file.verdicts.video_tamper ? 'video' : 'photo';
553
+ return {
554
+ ok: true,
555
+ mode: full ? 'full' : 'card',
556
+ updateAvailable: isNewerSchema(version),
557
+ // Null when none is due or the user dismissed it for this version
558
+ update: updateNote(version, options.dismissedUpdate),
559
+ name: typeof file.name === 'string' ? file.name : '',
560
+ // Schema 1.5: the line at the top saying which file was checked, and the full report on snapWONDERS
561
+ checkedFile: checkedFile(result),
562
+ reportUrl: result.report_url ? snapwondersLink(result.report_url, linkParams) : null,
563
+ headlines: [
564
+ headline('authenticity', file.grade, file.confidence, file),
565
+ headline('exposure', file.exposure_grade, file.exposure_confidence, file),
566
+ ],
567
+ capture: capture(file, full, options.hideLocation === true),
568
+ evidence: evidence(file, full, version),
569
+ findings: findings(file, full),
570
+ categories: full ? categories(file) : [],
571
+ alsoNoted: { title: ALSO_NOTED_TITLE, text: alsoNotedText(media) },
572
+ evidenceMaps: maps,
573
+ images: full ? images(file, options.assetUrl, maps !== null && maps.maps.some((m) => m.category !== 'forensic_nss_chart')) : [],
574
+ // Service output only (schema 1.1): the renderer never adds a credit of its own
575
+ attribution: textLink(result.attribution, linkParams),
576
+ vaultifyCta: textLink(file.vaultify_cta, linkParams),
577
+ };
578
+ }