Repository navigation
Expand file tree
/
Copy pathcomb-secure.html
More file actions
466 lines (447 loc) · 111 KB
/
Copy pathcomb-secure.html
File metadata and controls
466 lines (447 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
<!doctype html><!-- Comb Code, Copyright (c) 2026 Avi Shor. Free to use, with or without credit. See LICENSE.md. No warranty. --><html lang="en"><head><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' blob:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' data: blob:; media-src 'self' blob: data:; object-src 'none'; base-uri 'self'; form-action 'self'"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#F4F4F6"><link rel="icon" href="brand/icon-32.png"><link rel="apple-touch-icon" href="brand/icon-180.png"><title>Comb Code Secure</title>
<style>section,[id^="pane"]{scroll-margin-top:84px}
@font-face{font-family:Poppins;font-weight:400;src:url(brand/fonts/Poppins-Regular.ttf)}
@font-face{font-family:Poppins;font-weight:600;src:url(brand/fonts/Poppins-SemiBold.ttf)}
@font-face{font-family:Poppins;font-weight:700;src:url(brand/fonts/Poppins-Bold.ttf)}
:root{--ink:#1b1b1b;--muted:#585254;--ground:#F4F4F6;--green:#367464;--line:#E2E2E7;--red:#D7263D;--orange:#F77F00;--yellow:#F5C518;--ok:#2DB35A;--blue:#2E5BFF}
*{box-sizing:border-box}[hidden]{display:none!important}
body{margin:0;font:400 16px/1.55 Poppins,system-ui,sans-serif;color:var(--ink);background:#fff}
.strip{display:flex;height:8px}.strip i{flex:1}
.wrap{max-width:720px;margin:auto;padding:0 18px 60px}
nav{display:flex;align-items:center;justify-content:space-between;padding:16px 0 6px}nav img{height:40px}
.pill{font-size:13px;font-weight:600;background:var(--ground);border-radius:99px;padding:5px 12px;color:var(--green)}
h1{font-size:34px;line-height:1.1;letter-spacing:-.02em;margin:14px 0 6px}
.lead{color:var(--muted);margin:0 0 18px}
.tabs{display:flex;background:var(--ground);border-radius:16px;padding:4px;margin:0 0 18px}
.tabs button{flex:1;border:0;background:transparent;font:600 15px Poppins,system-ui;padding:11px;border-radius:12px;color:var(--muted);cursor:pointer}
.tabs button.on{background:#fff;color:var(--ink);box-shadow:0 1px 4px rgba(0,0,0,.12)}
.step{border:1px solid var(--line);border-radius:20px;padding:18px;margin:0 0 14px;background:#fff}
.step h2{font-size:17px;margin:0 0 12px;display:flex;align-items:center;gap:10px;letter-spacing:-.01em}
.num{width:28px;height:28px;border-radius:50%;background:var(--ink);color:#fff;font-size:14px;display:inline-flex;align-items:center;justify-content:center;flex:none}
textarea,input[type=text]{width:100%;font:400 16px Poppins,system-ui;color:var(--ink);padding:12px 14px;border:1.5px solid var(--line);border-radius:12px;background:#fff;outline:0}
textarea{min-height:84px;resize:vertical}textarea:focus,input[type=text]:focus{border-color:var(--green)}
.hint{font-size:13px;color:var(--muted);margin:6px 2px 0}
.opt{display:flex;gap:12px;align-items:flex-start;border:1.5px solid var(--line);border-radius:14px;padding:13px;margin:0 0 10px;cursor:pointer}
.opt.on{border-color:var(--green);background:#f1f7f5}
.opt input{margin-top:5px;width:18px;height:18px;accent-color:var(--green);flex:none}
.opt b{display:block;font-size:15px}.opt span{font-size:13px;color:var(--muted);display:block}
.row{display:flex;gap:8px}.row input{flex:1;min-width:0}
.btn{font:600 15px Poppins,system-ui;border:0;border-radius:14px;padding:13px 20px;background:var(--ink);color:#fff;cursor:pointer}
.btn.alt{background:var(--ground);color:var(--ink)}.btn.small{padding:10px 14px;font-size:14px;border-radius:12px}
.btn.big{width:100%;padding:16px;font-size:17px}.btn[disabled]{opacity:.55}
.meter{display:flex;gap:5px;margin:10px 0 4px}.meter i{flex:1;height:6px;border-radius:3px;background:var(--line)}
.mtext{font-size:13px;font-weight:600}.mw{font-size:13px;color:var(--muted)}
.result{text-align:center}
canvas#code{width:100%;max-width:420px;height:auto;border:1px solid var(--line);border-radius:16px;margin:6px auto 12px;display:block}
.chips{display:flex;flex-wrap:wrap;gap:6px;justify-content:center;margin:6px 0}
.chip{font-size:13px;font-weight:600;border-radius:99px;padding:5px 12px;background:var(--ground)}
.chip.ok{background:#dff3e6;color:#17663a}.chip.warn{background:#fdecc8;color:#A65200}.chip.bad{background:#fbd9de;color:#9b1226}.chip.info{background:var(--ground);color:var(--muted)}
.actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin-top:8px}
.verdict{border-radius:16px;padding:14px 16px;margin:10px 0;display:flex;gap:12px;align-items:flex-start}
.verdict.ok{background:#e9f6ee}.verdict.warn{background:#fff4d9}.verdict.bad{background:#fde8eb}
.verdict .ic{font-size:22px;line-height:1.2}.verdict b{display:block}.verdict span{font-size:14px;color:var(--muted)}
.secret{font-family:ui-monospace,Menlo,monospace;background:var(--ground);border-radius:10px;padding:10px 12px;word-break:break-all;margin:8px 0;font-size:15px}
.msgbox{background:var(--ground);border-radius:12px;padding:12px 14px;word-break:break-word;white-space:pre-wrap;text-align:left}
details{border:1px solid var(--line);border-radius:16px;padding:4px 16px;margin:0 0 12px}
summary{cursor:pointer;font-weight:600;padding:12px 0;font-size:15px}details[open] summary{border-bottom:1px solid var(--line);margin-bottom:8px}
details ul{padding-left:20px;color:var(--muted);font-size:14px;margin:6px 0 12px}details li{margin:5px 0}
.fp{font-family:ui-monospace,Menlo,monospace;font-weight:700}
.spin{display:inline-block;width:14px;height:14px;border:2px solid #fff6;border-top-color:#fff;border-radius:50%;animation:s .7s linear infinite;vertical-align:-2px;margin-right:8px}@keyframes s{to{transform:rotate(360deg)}}
#log{white-space:pre-wrap;font:12px monospace;color:#999}
@media(max-width:480px){h1{font-size:28px}.step{padding:14px;border-radius:18px}}
.tabs{position:relative}
.tabs .segpill{position:absolute;top:0;left:0;border-radius:12px;background:#fff;box-shadow:0 1px 4px rgba(0,0,0,.12);transition:transform .25s ease,width .25s ease,height .25s ease;pointer-events:none;z-index:0}
.tabs.seg-on button{background:transparent!important;box-shadow:none!important;position:relative;z-index:1}
#paneMake:not([hidden]),#paneOpen:not([hidden]){animation:pcfade .22s ease both}
@media(max-width:760px){#secureLogoHero{width:100vw!important;max-width:none!important;margin-left:calc(50% - 50vw)!important;border-radius:0!important}}
</style><link rel="stylesheet" href="site.css"><link rel="stylesheet" href="site-secure.css"><link rel="stylesheet" href="a11y.css"><link rel="stylesheet" href="controls-motion.css"><meta property="og:type" content="website"><meta property="og:title" content="Comb Code Secure"><meta property="og:description" content="A color code that holds more."><meta name="description" content="A color code that holds more."><meta property="og:url" content="https://getcombcode.github.io/comb-secure.html"><meta property="og:image" content="https://getcombcode.github.io/brand/share-banner-1200x630.png?v=2"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Comb Code Secure"><meta name="twitter:description" content="A color code that holds more."><meta name="twitter:image" content="https://getcombcode.github.io/brand/share-banner-1200x630.png?v=2"></head><body><div class="sbstrip"><i style="background:#D7263D"></i><i style="background:#F77F00"></i><i style="background:#F5C518"></i><i style="background:#2DB35A"></i><i style="background:#00B8D9"></i><i style="background:#2E5BFF"></i><i style="background:#B5179E"></i></div><div class="sitebar"><div class="sb-in"><a class="brand" href="index.html" aria-label="Comb Code home"><img class="full" src="brand/logo-horizontal.png" alt="Comb Code"><img class="ic" src="brand/icon-192.png" alt=""></a><div class="sl"><a href="index.html">Home</a><a href="use.html">Use</a><a href="comb.html">Advanced</a><a href="docs.html">Docs</a></div><a class="scanpill" href="scan.html"><span class="l">Scan a code</span><span class="s">Scan</span></a></div></div>
<div class="wrap">
<nav><img src="brand/logo-horizontal.png" alt="Comb Code"><span class="pill">AES-256 encryption</span></nav>
<div id="secureLogoHero" style="background:#000;border-radius:24px;overflow:hidden;margin:14px 0 26px;aspect-ratio:1060/600;display:flex;align-items:center;justify-content:center"><img src="brand/comb-secure-lock-locked-on-dark.svg" alt="Comb Code Secure lock" width="260" height="260" style="width:min(180px,40%);height:auto"></div>
<h1>Comb Code Secure</h1>
<script src="secure-logo.js?v=2026-11-25-5"></script>
<script>window.PrismSecureLogo&&PrismSecureLogo.mount(document.getElementById("secureLogoHero"),document.getElementById("secureLogoHero"));</script>
<p class="lead">Lock a Comb code with a password so only people who have it can read it. Everything happens on this device, offline.</p>
<div class="tabs"><button id="tabMake" class="on">Make</button><button id="tabOpen">Open</button></div>
<section id="paneMake">
<div class="step"><h2><span class="num">1</span>What goes in the code?</h2>
<textarea id="msg" placeholder="A link or a message">https://example.com/ticket/8812?token=abc</textarea>
<div class="hint"><span id="count">0</span> characters. A locked code adds about 56 bytes.</div></div>
<div class="step"><h2><span class="num">2</span>How should it be protected?</h2>
<label class="opt on" id="optLock"><input type="checkbox" id="dolock" checked><div><b>Lock with a password</b><span>Nobody can read it without the password.</span></div></label>
<div id="pwbox">
<div class="row"><input type="text" id="pw" aria-label="Password" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Password"><button class="btn alt small" id="genpw" type="button">Random</button></div>
<div class="meter" id="bars"><i></i><i></i><i></i><i></i></div><div id="meter"><span class="mtext"></span></div>
<div class="hint">Random makes a 140-bit password. Anyone with a photo of the code can try to guess the password, so a weak one is easy to break.</div></div>
<label class="opt" id="optSign" style="margin-top:12px"><input type="checkbox" id="dosign"><div><b>Sign it as me</b><span>Proves the code is unchanged and made with your key. Optional.</span></div></label>
<div id="keybox" hidden class="hint" style="margin:-2px 2px 4px">Your key: <span class="fp" id="fp">none yet</span> <button class="btn alt small" id="expkey" type="button">Back up key</button> <button class="btn alt small" id="impkey" type="button">Import</button><input type="file" id="impfile" accept=".json" hidden><div>The backup file holds your private key. Keep it private.</div></div></div>
<div class="step"><h2><span class="num">3</span>Create</h2>
<button class="btn big" id="make" type="button">Create secure code</button>
<div id="info" class="chips"></div>
<div class="result" id="resultbox" hidden><canvas id="code" hidden></canvas>
<div class="actions"><button class="btn small" id="dlpng" type="button">Download PNG</button><button class="btn alt small" id="cpw" type="button">Copy password</button><button class="btn alt small" id="goopen" type="button">Test opening it</button></div>
<div class="hint" id="savewarn">Save the password somewhere safe. There is no way to recover it.</div></div></div>
</section>
<section id="paneOpen" hidden>
<div class="step"><h2><span class="num">1</span>Which code?</h2>
<div class="actions" style="justify-content:flex-start;margin:0"><button class="btn small" id="pick" type="button">Choose an image</button><button class="btn alt small" id="scan" type="button">Use the code I just made</button></div>
<input type="file" id="codefile" accept="image/*" hidden><div class="hint" id="picked">Pick a photo or screenshot of a Comb code. For live camera scanning, the Comb scanner comes next.</div></div>
<div class="step"><h2><span class="num">2</span>Password</h2>
<input type="text" id="pw2" aria-label="Password (if the code is locked)" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Password (if the code is locked)"></div>
<div class="step"><h2><span class="num">3</span>Result</h2><div id="out"><div class="hint">Pick a code above.</div></div></div>
</section>
<details><summary>What this protects</summary><ul>
<li><b>Protects:</b> anyone who scans or photographs a locked code sees only random data. Any change to the code is detected.</li>
<li><b>Lock:</b> AES-256-GCM. The password goes through Argon2id (128 MiB, 3 passes), which makes guessing expensive. Every code has its own random salt and nonce.</li>
<li><b>Sign:</b> ECDSA P-256. Shows the code is unchanged and made by one key.</li>
</ul></details>
<pre id="log"></pre>
<script>window.onerror=(m,s,l,c)=>{document.getElementById("log").textContent+="ERR "+m+" line "+l+"\n"}</script>
<script>
/* Trace captures the real decoder path only when requested. */
globalThis.PrismTrace={active:false,events:[],images:[],start:0,last:0,counts:{},dropped:0,suppressed:{},
begin(image,on){this.active=!!on;this.sampleImage=0;this.events=[];this.images=[];this.counts={};this.dropped=0;this.suppressed={};this.start=this.last=performance.now();if(on)this.image('Input pixels',image);},
add(name,data={},view=null,state='info'){if(!this.active)return;let now=performance.now();this.counts[name]=(this.counts[name]||0)+1;if(/^(RS |ECC or CRC rejected)/.test(name)&&this.counts[name]>120){this.suppressed[name]=(this.suppressed[name]||0)+1;return;}if(this.events.length>=2400){this.dropped++;return;}this.events.push({name,state,at:now-this.start,elapsed:now-this.last,data:structuredClone(data),view:view?structuredClone(view):null});this.last=now;},
image(name,im){if(!this.active)return null;let scale=Math.min(1,640/Math.max(im.width,im.height)),w=Math.max(1,Math.round(im.width*scale)),h=Math.max(1,Math.round(im.height*scale)),data=new Uint8ClampedArray(w*h*4);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let a=(y*w+x)*4,b=(Math.min(im.height-1,Math.floor(y/scale))*im.width+Math.min(im.width-1,Math.floor(x/scale)))*4;data.set(im.data.subarray(b,b+4),a);}let id=this.images.length;this.images.push({name,width:w,height:h,sourceWidth:im.width,sourceHeight:im.height,data});this.add(name,{width:im.width,height:im.height},{image:id});this.currentImage=id;return id;},
mask(name,mask,w,h,sourceW,sourceH){if(!this.active)return;let data=new Uint8ClampedArray(w*h*4);for(let i=0;i<mask.length;i++){let k=i*4;data[k]=data[k+1]=data[k+2]=mask[i]?235:20;data[k+3]=255;}let id=this.images.length;this.images.push({name,width:w,height:h,sourceWidth:sourceW,sourceHeight:sourceH,data});this.add(name,{width:w,height:h,meaning:'Bright pixels survive the actual saturation/darkness mask and morphology.'},{image:id});},
finish(result,error){if(!this.active)return null;if(this.events.length>=2400){this.events.pop();this.dropped++;}this.add(error?'Scan rejected':'Payload CRC verified',error?{stage:error.stage||'other',message:error.message}:{header:result.header,bytes:result.bytes.length,correctedBytes:result.corrected,erasures:result.erasures,quality:result.quality,format:result.variant||'original',fallback:result.fallback||null},null,error?'fail':'pass');let out={events:this.events,images:this.images,counts:this.counts,suppressed:this.suppressed,dropped:this.dropped,totalMs:performance.now()-this.start,note:'Real stage and candidate trace. Timings include debug capture overhead; elapsed is time since the previous event, not an isolated profiler. Optimizer pixel evaluations are counted, not saved individually. Repeated ECC event families keep the first 120 events each; totals remain in evaluationCounts. At most 2,400 events and 1,800 sampled-cell dots per view are saved. Notch orientation is inferred by known-cell/header/CRC agreement, not an independent notch detector.'};this.active=false;return out;}};
'use strict';
/* Comb Code. Self-contained experimental optical format. */
const Prism = (() => {
const trace=(...a)=>globalThis.PrismTrace?.add(...a);
const S3=Math.sqrt(3), Q=3*S3, SIZES=[[21,24],[29,33],[41,47],[57,66],[81,94],[113,130]], HEX=['#1B1B1B','#2E5BFF','#00B8D9','#2DB35A','#F5C518','#F77F00','#D7263D','#B5179E','#FFFFFF'];
let decodeDeadline=Infinity;
const CFG={detectionWidth:320,saturation:.25,darkness:.55,minScore:.5,refineStop:.03,meshRadius:.6,sigmaFloor:6,llrClamp:12,minRadius:4,glareThreshold:.90};
const clamp=(x,a=0,b=1)=>Math.max(a,Math.min(b,x));
const rng=seed=>()=>{seed|=0;seed=seed+0x6D2B79F5|0;let t=Math.imul(seed^seed>>>15,1|seed);t=t+Math.imul(t^t>>>7,61|t)^t;return ((t^t>>>14)>>>0)/4294967296;};
const median=a=>{a.sort((x,y)=>x-y);return a[a.length>>1]};
const EXP=new Uint8Array(512), LOG=new Uint8Array(256);let z=1;for(let i=0;i<255;i++){EXP[i]=z;LOG[z]=i;z<<=1;if(z&256)z^=0x11d;}for(let i=255;i<512;i++)EXP[i]=EXP[i-255];
const mul=(a,b)=>a&&b?EXP[LOG[a]+LOG[b]]:0, div=(a,b)=>{if(!b)throw Error('GF division by zero');return a?EXP[(LOG[a]+255-LOG[b])%255]:0;};
const peval=(p,x)=>{let y=0;for(let i=p.length-1;i>=0;i--)y=mul(y,x)^p[i];return y;};
const pmul=(a,b)=>{let o=new Uint8Array(a.length+b.length-1);for(let i=0;i<a.length;i++)for(let j=0;j<b.length;j++)o[i+j]^=mul(a[i],b[j]);return o;};
const genCache=new Map();
function rsEncode(m,nsym){let g=genCache.get(nsym);if(!g){g=new Uint8Array([1]);for(let i=0;i<nsym;i++)g=pmul(g,new Uint8Array([1,EXP[i]]));genCache.set(nsym,g);}let out=new Uint8Array(m.length+nsym);out.set(m);for(let i=0;i<m.length;i++){let c=out[i];if(c)for(let j=1;j<g.length;j++)out[i+j]^=mul(g[j],c);}out.set(m);return out;}
function syndromes(r,n){let s=new Uint8Array(n);for(let j=0;j<n;j++){let y=0;for(let i=0;i<r.length;i++)y=mul(y,EXP[j])^r[i];s[j]=y;}return s;}
function bm(s){let c=new Uint8Array(s.length+1), b=new Uint8Array(s.length+1);c[0]=b[0]=1;let L=0,m=1,bb=1;for(let n=0;n<s.length;n++){let d=s[n];for(let i=1;i<=L;i++)d^=mul(c[i],s[n-i]);if(!d){m++;continue;}let t=c.slice(),v=div(d,bb);for(let i=0;i+m<c.length;i++)c[i+m]^=mul(v,b[i]);if(2*L<=n){L=n+1-L;b=t;bb=d;m=1;}else m++;}return c.slice(0,L+1);}
function rsDecode(input,nsym,erasures=[]){let r=Uint8Array.from(input),s=syndromes(r,nsym);if(s.every(x=>x===0))return {bytes:r,corrected:0};if(erasures.length>nsym)throw Error('Too many erasures');let G=new Uint8Array([1]),T=Array.from(s);for(let p of erasures){if(p<0||p>=r.length)throw Error('Erasure index');let X=EXP[r.length-1-p];G=pmul(G,new Uint8Array([1,X]));for(let j=0;j<T.length-1;j++)T[j]=mul(T[j],X)^T[j+1];T.pop();}let E=bm(T);if(2*(E.length-1)+erasures.length>nsym)throw Error('RS correction limit');let loc=pmul(G,E),pos=[];for(let p=0;p<r.length;p++){let e=r.length-1-p;if(peval(loc,EXP[(255-e)%255])===0)pos.push(p);}if(pos.length!==loc.length-1)throw Error('RS roots');let omega=pmul(s,loc).slice(0,nsym),der=new Uint8Array(Math.max(1,loc.length-1));for(let i=1;i<loc.length;i+=2)der[i-1]=loc[i];for(let p of pos){let e=r.length-1-p,X=EXP[e],xi=EXP[(255-e)%255];r[p]^=div(mul(X,peval(omega,xi)),peval(der,xi));}if(!syndromes(r,nsym).every(x=>x===0))throw Error('RS syndrome check');return {bytes:r,corrected:pos.length};}
const crcTable=Uint32Array.from({length:256},(_,n)=>{for(let j=0;j<8;j++)n=n&1?0xEDB88320^(n>>>1):n>>>1;return n>>>0;});
const crc32=bytes=>{let c=0xFFFFFFFF;for(let b of bytes)c=crcTable[(c^b)&255]^(c>>>8);return (c^0xFFFFFFFF)>>>0;};
function crc4(bits){let r=0;for(let b of bits){let f=((r>>3)&1)^b;r=(r<<1)&15;if(f)r^=3;}return r;}
const pushBits=(a,x,n)=>{for(let k=n-1;k>=0;k--)a.push((x>>>k)&1);};
const cache=new Map();
function layout(size){if(cache.has(size))return cache.get(size);if(!SIZES[size])throw Error('Unknown size');let [C,R]=SIZES[size],cells=[],M=[],known=[];for(let j=0;j<R;j++)for(let i=0;i<C;i++){let role='data',symbol=-1,pi=(i-2)/5,pj=(j-2)/5;if(j<=2&&i<=2){role='gap';symbol=8;}else if(j===0||j===R-1||i===0||i===C-1){role='ring';symbol=(j*5+i*3)%8;}else if(i%5===2&&j%5===2){role='pilot';symbol=(pi*2+pj*3)%9;}let c={i,j,x:S3*(i+.5+.5*(j&1)),y:1+1.5*j,role,symbol,pi,pj,index:cells.length};cells.push(c);if(role==='data')M.push(c);else if(role!=='gap')known.push(c);}let headers=[];for(let n=0;n<72;n++){let c=M[Math.floor((n+.5)*M.length/72)];c.role='header';c.header=n;headers.push(c);}let data=cells.filter(c=>c.role==='data'),rand=rng(0x5EED^size);for(let i=data.length-1;i>0;i--){let j=Math.floor(rand()*(i+1));[data[i],data[j]]=[data[j],data[i]];}let l={size,C,R,W:S3*(C+.5),H:2+1.5*(R-1),cells,headers,data,known};cache.set(size,l);return l;}
function capacity(size,ecc=1,mode=0){let l=layout(size),n=Math.floor(l.data.length*(mode?1:3)/8),B=Math.ceil(n/255),blocks=[];for(let i=0;i<B;i++){let len=Math.floor(n/B)+(i<n%B?1:0),nsym=Math.max(4,2*Math.round(len*[.1,.2,.3,.4][ecc]/2));blocks.push({n:len,nsym,k:len-nsym});}return {n,blocks,k:blocks.reduce((v,b)=>v+b.k,0),payload:Math.max(0,blocks.reduce((v,b)=>v+b.k,0)-4)};}
function headerBits(size,ecc,mode,type,L){let b=[];pushBits(b,size,3);pushBits(b,ecc,2);pushBits(b,mode,1);pushBits(b,type,1);pushBits(b,L,13);pushBits(b,crc4(b),4);return b;}
function encode(bytes,{size=-1,ecc=1,mode=0,type=0}={}){bytes=Uint8Array.from(bytes);if(bytes.length>8191)throw Error('Payload exceeds 8191 bytes');if(size<0){size=SIZES.findIndex((_,i)=>capacity(i,ecc,mode).k>=bytes.length+4);if(size<0)throw Error('Payload too large for this mode and ECC');}let cap=capacity(size,ecc,mode);if(cap.k<bytes.length+4)throw Error('Payload does not fit: maximum '+cap.payload+' bytes');let msg=new Uint8Array(cap.k);msg.set(bytes);let crc=crc32(bytes);for(let k=0;k<4;k++)msg[bytes.length+k]=(crc>>>(24-8*k))&255;let off=0,blocks=cap.blocks.map(b=>{let r=rsEncode(msg.slice(off,off+b.k),b.nsym);off+=b.k;return r;}),stream=[];for(let p=0;p<Math.max(...blocks.map(x=>x.length));p++)for(let b of blocks)if(p<b.length)pushBits(stream,b[p],8);let rand=rng(0xBEEF),l=layout(size),symbols=new Uint8Array(l.cells.length);symbols.fill(8);for(let c of l.known)symbols[c.index]=knownSymbol(c,mode);let hb=headerBits(size,ecc,mode,type,bytes.length);for(let c of l.headers)symbols[c.index]=hb[c.header%24]?0:8;let at=0;for(let c of l.data){if(mode)symbols[c.index]=(stream[at++]??(rand()>.5?1:0))?0:8;else{let b=0;for(let k=0;k<3;k++)b=(b<<1)|(stream[at++]??(rand()>.5?1:0));let v=b;v^=v>>1;v^=v>>2;symbols[c.index]=v;}}return {size,ecc,mode,type,bytes,symbols,layout:l,capacity:cap};}
function knownSymbol(c,mode){return mode?(c.role==='ring'?0:(c.pi+c.pj)%2===0?0:8):c.symbol;}
function render(code,r=12,canvas){canvas=canvas||document.createElement('canvas');let l=code.layout;canvas.width=Math.ceil((l.W+2*Q)*r);canvas.height=Math.ceil((l.H+2*Q)*r);let ctx=canvas.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,canvas.width,canvas.height);for(let c of l.cells){let s=code.symbols[c.index];if(s===8)continue;ctx.fillStyle=HEX[s];ctx.beginPath();for(let k=0;k<6;k++){let a=(30+60*k)*Math.PI/180,x=(c.x+Q+1.03*Math.cos(a))*r,y=(c.y+Q+1.03*Math.sin(a))*r;k?ctx.lineTo(x,y):ctx.moveTo(x,y);}ctx.closePath();ctx.fill();}return canvas;}
const lin=x=>x<=.04045?x/12.92:((x+.055)/1.055)**2.4, srgb=x=>x<=.0031308?12.92*x:1.055*x**(1/2.4)-.055;
const LUT=Float32Array.from({length:256},(_,i)=>lin(i/255));
function lab(c){let x=(.4124564*c[0]+.3575761*c[1]+.1804375*c[2])/.95047,y=.2126729*c[0]+.7151522*c[1]+.072175*c[2],z=(.0193339*c[0]+.119192*c[1]+.9503041*c[2])/1.08883;let f=v=>v>.008856?Math.cbrt(v):7.787*v+16/116;let a=f(x),b=f(y),d=f(z);return [116*b-16,500*(a-b),200*(b-d)];}
const PAL=HEX.map(h=>[1,3,5].map(i=>lin(parseInt(h.slice(i,i+2),16)/255))), LAB=PAL.map(lab);
const dist=(a,b)=>(a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2;
function solve(a,b){let n=b.length,m=a.map((r,i)=>[...r,b[i]]);for(let j=0;j<n;j++){let p=j;for(let k=j+1;k<n;k++)if(Math.abs(m[k][j])>Math.abs(m[p][j]))p=k;if(Math.abs(m[p][j])<1e-10)throw Error('Singular geometry');[m[j],m[p]]=[m[p],m[j]];let v=m[j][j];for(let k=j;k<=n;k++)m[j][k]/=v;for(let i=0;i<n;i++)if(i!==j){v=m[i][j];for(let k=j;k<=n;k++)m[i][k]-=v*m[j][k];}}return m.map(r=>r[n]);}
function homography(src,dst){let a=[],b=[];for(let i=0;i<4;i++){let [x,y]=src[i],[u,v]=dst[i];a.push([x,y,1,0,0,0,-u*x,-u*y],[0,0,0,x,y,1,-v*x,-v*y]);b.push(u,v);}return solve(a,b);}
const map=(h,x,y)=>{if(h.warp){let {W,H,p}=h.warp,u=2*x/W-1,v=2*y/H-1; x+=(1-u*u)*(p[0]+p[1]*v)+p[2]*(1-v*v)+(p[6]||0)*u*(1-u*u)+(p[8]||0)*u*(1-v*v);y+=(1-v*v)*(p[3]+p[4]*u)+p[5]*(1-u*u)+(p[7]||0)*v*(1-u*u)+(p[9]||0)*v*(1-v*v);}let d=h[6]*x+h[7]*y+1;return [(h[0]*x+h[1]*y+h[2])/d,(h[3]*x+h[4]*y+h[5])/d];};
const corners=l=>[[0,0],[l.W,0],[l.W,l.H],[0,l.H]];
function frame(image){let {width:w,height:h,data}=image,p=new Float32Array(w*h*3);for(let i=0,j=0;i<data.length;i+=4){p[j++]=LUT[data[i]];p[j++]=LUT[data[i+1]];p[j++]=LUT[data[i+2]];}return {w,h,p,image};}
function pixel(f,x,y){if(x<0||y<0||x>=f.w-1||y>=f.h-1)return [1,1,1];let i=Math.floor(x),j=Math.floor(y),a=x-i,b=y-j,k=(j*f.w+i)*3,o=[];for(let c=0;c<3;c++)o[c]=(f.p[k+c]*(1-a)+f.p[k+3+c]*a)*(1-b)+(f.p[k+f.w*3+c]*(1-a)+f.p[k+f.w*3+3+c]*a)*b;return o;}
const OFF=[[0,0],...Array.from({length:6},(_,k)=>[.45*Math.cos(k*Math.PI/3),.45*Math.sin(k*Math.PI/3)])];
function meshAt(mesh,x,y){if(!mesh||!mesh.length)return [0,0];let list=[];for(let m of mesh){let d=(m.x-x)**2+(m.y-y)**2;if(list.length<4||d<list[3].d){list.push({d,m});list.sort((a,b)=>a.d-b.d);list.length=Math.min(list.length,4);}}let sx=0,sy=0,sw=0;for(let a of list){let w=1/(a.d+.05);sx+=a.m.dx*w;sy+=a.m.dy*w;sw+=w;}return [sx/sw,sy/sw];}
function sample(f,h,c,white=[1,1,1],mesh=null,fast=false){let of=meshAt(mesh,c.x,c.y),a=[[],[],[]];for(let o of (fast?OFF.slice(0,1):OFF)){let q=map(h,c.x+o[0],c.y+o[1]),v=pixel(f,q[0]+of[0],q[1]+of[1]);for(let k=0;k<3;k++)a[k].push(v[k]/white[k]);}return a.map(median);}
function whiteBalance(f,h,l){let a=[[],[],[]];for(let t=0;t<24;t++){let u=(t+.5)/24;for(let [x,y] of [[u*l.W,-2.5],[u*l.W,l.H+2.5],[-2.5,u*l.H],[l.W+2.5,u*l.H]]){let q=map(h,x,y);if(q[0]<0||q[1]<0||q[0]>=f.w-1||q[1]>=f.h-1)continue;let v=pixel(f,...q);for(let k=0;k<3;k++)a[k].push(v[k]);}}return a.map(x=>Math.max(.08,x.length?median(x):1));}
function nearest(c,mode=0){let v=lab(c),best=-1,d=Infinity;for(let i=0;i<9;i++){if(mode&&i!==0&&i!==8)continue;let q=dist(v,LAB[i]);if(q<d){d=q;best=i;}}return {symbol:best,d:Math.sqrt(d)};}
function hypothesisScore(f,h,l,mode,white,fast=true){if(globalThis.PrismTrace?.active)globalThis.PrismTrace.counts.hypothesisScoreEvaluations=(globalThis.PrismTrace.counts.hypothesisScoreEvaluations||0)+1;let cost=0,n=0,match=0,stride=Math.max(1,Math.floor(l.known.length/120));for(let z=0;z<l.known.length;z+=stride){let c=l.known[z];if(mode&&c.role==='ring')continue;let v=sample(f,h,c,white,null,fast),expect=knownSymbol(c,mode),near=nearest(v,mode),d=Math.sqrt(dist(lab(v),LAB[expect]));cost+=Math.min(d/30,1);match+=near.symbol===expect?1:0;n++;}return {cost:cost/n,score:match/n};}
function refine(f,h,l,mode,quad,white){let q=quad.map(p=>p.slice()),radius=Math.hypot(q[1][0]-q[0][0],q[1][1]-q[0][1])/l.W,step=radius*.5,best=hypothesisScore(f,h,l,mode,white,false).cost;for(;step>radius*CFG.refineStop;step*=.5){for(let pass=0;pass<2;pass++){let changed=false;for(let i=0;i<4;i++)for(let j=0;j<2;j++){let v=q[i][j],win=v;for(let s of [-1,1]){q[i][j]=v+s*step;let hh=homography(corners(l),q),cost=hypothesisScore(f,hh,l,mode,white,false).cost;if(cost<best){best=cost;win=q[i][j];h=hh;changed=true;}}q[i][j]=win;}if(!changed)break;}}return {h,quad:q,cost:best};}
const cross=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
function hull(points){points.sort((a,b)=>a[0]-b[0]||a[1]-b[1]);let a=[],b=[];for(let p of points){while(a.length>1&&cross(a[a.length-2],a[a.length-1],p)<=0)a.pop();a.push(p);}for(let i=points.length-1;i>=0;i--){let p=points[i];while(b.length>1&&cross(b[b.length-2],b[b.length-1],p)<=0)b.pop();b.push(p);}a.pop();b.pop();return a.concat(b);}
const area=q=>Math.abs(q.reduce((s,p,i)=>s+p[0]*q[(i+1)%q.length][1]-p[1]*q[(i+1)%q.length][0],0))/2;
function morph(a,w,h,r,max){let tmp=new Uint8Array(a.length),out=new Uint8Array(a.length);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let v=max?0:1;for(let d=-r;d<=r;d++){let xx=clamp(x+d,0,w-1);if(max)v|=a[y*w+xx];else v&=a[y*w+xx];}tmp[y*w+x]=v;}for(let y=0;y<h;y++)for(let x=0;x<w;x++){let v=max?0:1;for(let d=-r;d<=r;d++){let yy=clamp(y+d,0,h-1);if(max)v|=tmp[yy*w+x];else v&=tmp[yy*w+x];}out[y*w+x]=v;}return out;}
function smoothFilter(a,w,h,r,isMax){let tmp=new Float32Array(a.length),out=new Float32Array(a.length);for(let y=0;y<h;y++){let dq=[],head=0,sum=0;for(let x=-r;x<w+r;x++){let v=a[y*w+clamp(x,0,w-1)];if(isMax){while(dq.length>head&&dq[dq.length-1].v<=v)dq.pop();dq.push({x,v});while(dq[head].x<x-2*r)head++;}else{sum+=v;if(x>r)sum-=a[y*w+clamp(x-2*r-1,0,w-1)];}if(x>=r)tmp[y*w+x-r]=isMax?dq[head].v:sum/(2*r+1);}}for(let x=0;x<w;x++){let dq=[],head=0,sum=0;for(let y=-r;y<h+r;y++){let v=tmp[clamp(y,0,h-1)*w+x];if(isMax){while(dq.length>head&&dq[dq.length-1].v<=v)dq.pop();dq.push({y,v});while(dq[head].y<y-2*r)head++;}else{sum+=v;if(y>r)sum-=tmp[clamp(y-2*r-1,0,h-1)*w+x];}if(y>=r)out[(y-r)*w+x]=isMax?dq[head].v:sum/(2*r+1);}}return out;}
function fitLine(points){let x=0,y=0;for(let p of points){x+=p[0];y+=p[1];}x/=points.length;y/=points.length;let xx=0,xy=0,yy=0;for(let p of points){let a=p[0]-x,b=p[1]-y;xx+=a*a;xy+=a*b;yy+=b*b;}let t=.5*Math.atan2(2*xy,xx-yy),nx=-Math.sin(t),ny=Math.cos(t);return [nx,ny,nx*x+ny*y];}
const intersect=(a,b)=>{let d=a[0]*b[1]-a[1]*b[0];if(Math.abs(d)<1e-6)throw Error('Parallel edges');return [(a[2]*b[1]-a[1]*b[2])/d,(a[0]*b[2]-a[2]*b[0])/d];};
function detect(f){let scale=Math.min(1,CFG.detectionWidth/Math.max(f.w,f.h)),w=Math.round(f.w*scale),h=Math.round(f.h*scale),V=new Float32Array(w*h),sat=new Float32Array(w*h);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let p=pixel(f,x/scale,y/scale).map(srgb),mx=Math.max(...p),mn=Math.min(...p);V[y*w+x]=mx;sat[y*w+x]=mx?(mx-mn)/mx:0;}let paper=smoothFilter(smoothFilter(V,w,h,7,true),w,h,15,false),mask=new Uint8Array(w*h);for(let k=0;k<mask.length;k++)mask[k]=sat[k]>CFG.saturation&&V[k]>.15||V[k]<CFG.darkness*Math.max(paper[k],.4)?1:0;mask=morph(morph(mask,w,h,2,true),w,h,2,false);globalThis.PrismTrace?.mask('Boundary segmentation mask',mask,w,h,f.w,f.h);let seen=new Uint8Array(mask.length),queue=new Int32Array(mask.length),candidates=[];for(let k=0;k<mask.length;k++){if(!mask[k]||seen[k])continue;let head=0,tail=1,boundary=[];queue[0]=k;seen[k]=1;while(head<tail){let p=queue[head++],x=p%w,y=Math.floor(p/w),edge=false;for(let q of [x>0?p-1:-1,x<w-1?p+1:-1,y>0?p-w:-1,y<h-1?p+w:-1]){if(q<0||!mask[q]){edge=true;continue;}if(!seen[q]){seen[q]=1;queue[tail++]=q;}}if(edge)boundary.push([x,y]);}if(tail<100)continue;let hu=hull(boundary),ar=area(hu),xs=hu.map(p=>p[0]),ys=hu.map(p=>p[1]),aspect=(Math.max(...xs)-Math.min(...xs))/(Math.max(...ys)-Math.min(...ys));if(tail/ar<.04||aspect<.4||aspect>2.5)continue;candidates.push({hu,tail,boundary,ar});}candidates.sort((a,b)=>b.ar-a.ar);if(!candidates.length)throw stageError('detect','No code found. Use a plain background with a wide white margin.');let out=[];for(let cc of candidates.slice(0,3)){let poly=cc.hu.map(p=>p.slice());let per=poly.reduce((s,p,i)=>s+Math.hypot(p[0]-poly[(i+1)%poly.length][0],p[1]-poly[(i+1)%poly.length][1]),0);while(poly.length>4){let min=Infinity,at=0;for(let i=0;i<poly.length;i++){let a=poly[(i+poly.length-1)%poly.length],b=poly[(i+1)%poly.length],v=Math.abs(cross(a,poly[i],b))/Math.hypot(b[0]-a[0],b[1]-a[1]);if(v<min){min=v;at=i;}}if(min>.7)break;poly.splice(at,1);}let edges=poly.map((a,i)=>({a,b:poly[(i+1)%poly.length],i,len:Math.hypot(a[0]-poly[(i+1)%poly.length][0],a[1]-poly[(i+1)%poly.length][1])})).sort((a,b)=>b.len-a.len).slice(0,4).sort((a,b)=>a.i-b.i);let lines=[];for(let i=0;i<4;i++){let a=edges[i].a,b=edges[i].b,dx=b[0]-a[0],dy=b[1]-a[1],len=Math.hypot(dx,dy),points=cc.boundary.filter(p=>Math.abs(cross(a,b,p))/len<2);lines.push(points.length>=2?fitLine(points):fitLine([a,b]));}try{let quad=lines.map((l,i)=>intersect(lines[(i+3)%4],l)).map(p=>p.map(v=>(v+.5)/scale));out.push(quad);}catch(e){}}if(!out.length)throw stageError('detect','Could not fit four edges');trace('Legacy boundary candidates',{count:out.length}, {quads:out,image:globalThis.PrismTrace?.currentImage||0});return out;}
function detectCurved(f){let scale=Math.min(1,CFG.detectionWidth/Math.max(f.w,f.h)),w=Math.round(f.w*scale),h=Math.round(f.h*scale),V=new Float32Array(w*h),sat=new Float32Array(w*h);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let p=pixel(f,x/scale,y/scale).map(srgb),mx=Math.max(...p),mn=Math.min(...p);V[y*w+x]=mx;sat[y*w+x]=mx?(mx-mn)/mx:0;}let paper=smoothFilter(smoothFilter(V,w,h,7,true),w,h,15,false),mask=new Uint8Array(w*h);for(let k=0;k<mask.length;k++)mask[k]=sat[k]>CFG.saturation&&V[k]>.15||V[k]<CFG.darkness*Math.max(paper[k],.4)?1:0;mask=morph(morph(mask,w,h,2,true),w,h,2,false);globalThis.PrismTrace?.mask('Boundary segmentation mask',mask,w,h,f.w,f.h);let seen=new Uint8Array(mask.length),queue=new Int32Array(mask.length),candidates=[];for(let k=0;k<mask.length;k++){if(!mask[k]||seen[k])continue;let head=0,tail=1,boundary=[];queue[0]=k;seen[k]=1;while(head<tail){let p=queue[head++],x=p%w,y=Math.floor(p/w),edge=false;for(let q of [x>0?p-1:-1,x<w-1?p+1:-1,y>0?p-w:-1,y<h-1?p+w:-1]){if(q<0||!mask[q]){edge=true;continue;}if(!seen[q]){seen[q]=1;queue[tail++]=q;}}if(edge)boundary.push([x,y]);}if(tail<100)continue;let hu=hull(boundary),ar=area(hu),xs=hu.map(p=>p[0]),ys=hu.map(p=>p[1]),aspect=(Math.max(...xs)-Math.min(...xs))/(Math.max(...ys)-Math.min(...ys));if(tail/ar<.04||aspect<.4||aspect>2.5)continue;candidates.push({hu,tail,boundary,ar});}candidates.sort((a,b)=>b.ar-a.ar);if(!candidates.length)throw stageError('detect','No code found. Use a plain background with a wide white margin.');let out=[];for(let cc of candidates.slice(0,3)){let rect=null,rectArea=Infinity;for(let ii=0;ii<cc.hu.length;ii++){let a=cc.hu[ii],b=cc.hu[(ii+1)%cc.hu.length],dx=b[0]-a[0],dy=b[1]-a[1],len=Math.hypot(dx,dy);dx/=len;dy/=len;let ux=cc.hu.map(p=>p[0]*dx+p[1]*dy),vy=cc.hu.map(p=>-p[0]*dy+p[1]*dx),lo=Math.min(...ux),hi=Math.max(...ux),bot=Math.min(...vy),top=Math.max(...vy),ar=(hi-lo)*(top-bot);if(ar<rectArea){rectArea=ar;rect=[[lo,bot],[hi,bot],[hi,top],[lo,top]].map(([u,v])=>[(u*dx-v*dy+.5)/scale,(u*dy+v*dx+.5)/scale]);}}if(rect)out.push(rect);let coarse=cc.hu.map(p=>p.slice());while(coarse.length>4){let min=Infinity,at=0;for(let i=0;i<coarse.length;i++){let a=coarse[(i+coarse.length-1)%coarse.length],b=coarse[(i+1)%coarse.length],v=Math.abs(cross(a,coarse[i],b))/Math.max(.1,Math.hypot(b[0]-a[0],b[1]-a[1]));if(v<min){min=v;at=i;}}coarse.splice(at,1);}if(coarse.length===4){out.push(coarse.map(p=>p.map(v=>(v+.5)/scale)));let lines=[];for(let i=0;i<4;i++){let a=coarse[i],b=coarse[(i+1)%4],start=cc.hu.findIndex(p=>p[0]===a[0]&&p[1]===a[1]),end=cc.hu.findIndex(p=>p[0]===b[0]&&p[1]===b[1]),edge=null,maxLen=0;for(let j=start;j!==end;j=(j+1)%cc.hu.length){let c=cc.hu[j],d=cc.hu[(j+1)%cc.hu.length],len=Math.hypot(c[0]-d[0],c[1]-d[1]);if(len>maxLen){maxLen=len;edge=[c,d];}}let [c,d]=edge||[a,b],points=cc.boundary.filter(p=>Math.abs(cross(c,d,p))/Math.max(1,maxLen)<2);lines.push(fitLine(points.length>2?points:[c,d]));}try{let q=lines.map((l,i)=>intersect(lines[(i+3)%4],l));if(area(q)>cc.ar*.6&&area(q)<cc.ar*1.5)out.push(q.map(p=>p.map(v=>(v+.5)/scale)));}catch(e){}}let poly=cc.hu.map(p=>p.slice());let per=poly.reduce((s,p,i)=>s+Math.hypot(p[0]-poly[(i+1)%poly.length][0],p[1]-poly[(i+1)%poly.length][1]),0);while(poly.length>4){let min=Infinity,at=0;for(let i=0;i<poly.length;i++){let a=poly[(i+poly.length-1)%poly.length],b=poly[(i+1)%poly.length],v=Math.abs(cross(a,poly[i],b))/Math.hypot(b[0]-a[0],b[1]-a[1]);if(v<min){min=v;at=i;}}if(min>.7)break;poly.splice(at,1);}let edges=poly.map((a,i)=>({a,b:poly[(i+1)%poly.length],i,len:Math.hypot(a[0]-poly[(i+1)%poly.length][0],a[1]-poly[(i+1)%poly.length][1])})).sort((a,b)=>b.len-a.len).slice(0,4).sort((a,b)=>a.i-b.i);let lines=[];for(let i=0;i<4;i++){let a=edges[i].a,b=edges[i].b,dx=b[0]-a[0],dy=b[1]-a[1],len=Math.hypot(dx,dy),points=cc.boundary.filter(p=>Math.abs(cross(a,b,p))/len<2);lines.push(points.length>=2?fitLine(points):fitLine([a,b]));}try{let quad=lines.map((l,i)=>intersect(lines[(i+3)%4],l)).map(p=>p.map(v=>(v+.5)/scale));out.push(quad);}catch(e){}}if(!out.length)throw stageError('detect','Could not fit four edges');trace('Curved boundary candidates',{count:out.length},{quads:out,image:globalThis.PrismTrace?.currentImage||0});return out;}
function stageError(stage,msg){let e=Error(msg);e.stage=stage;return e;}
function calibrate(f,h,l,mode,white,mesh){let refs=l.known.map(c=>({c,o:sample(f,h,c,white,mesh),E:PAL[knownSymbol(c,mode)]})).filter(v=>knownSymbol(v.c,mode)===8||!v.o.every(x=>x>CFG.glareThreshold)),A=Array.from({length:4},()=>[0,0,0,0]),b=Array.from({length:3},()=>[0,0,0,0]);for(let v of refs){let o=[...v.o,1];for(let i=0;i<4;i++){for(let j=0;j<4;j++)A[i][j]+=o[i]*o[j];for(let k=0;k<3;k++)b[k][i]+=o[i]*v.E[k];}}for(let i=0;i<4;i++)A[i][i]+=.001;let M=b.map(v=>solve(A,v));const apply=o=>M.map(row=>row[0]*o[0]+row[1]*o[1]+row[2]*o[2]+row[3]);for(let v of refs){let a=apply(v.o);v.res=v.E.map((x,k)=>x-a[k]);}function correction(o,c){let a=apply(o),near=[];for(let v of refs){let d=(v.c.x-c.x)**2+(v.c.y-c.y)**2;if(near.length<6||d<near[5].d){near.push({d,v});near.sort((a,b)=>a.d-b.d);near.length=Math.min(6,near.length);}}let sw=0,res=[0,0,0];for(let {d,v} of near){let w=1/(d+.05);sw+=w;for(let k=0;k<3;k++)res[k]+=w*v.res[k];}return a.map((x,k)=>clamp(x+res[k]/sw));}let errors=refs.filter(v=>v.c.role==='pilot').map(v=>Math.sqrt(dist(lab(correction(v.o,v.c)),lab(v.E))))||[6];return {correction,sigma:Math.max(CFG.sigmaFloor,1.4*median(errors.length?errors:[6])),refs,M};}
function buildMesh(f,h,l,mode,white,previous){let pilots=l.known.filter(c=>c.role==='pilot'),scale=Math.hypot(...mapDelta(h,l.W/2,l.H/2,1,0)),offsets=[];for(let c of pilots){let base=map(h,c.x,c.y),prior=meshAt(previous,c.x,c.y),best=Infinity,win=null,expect=knownSymbol(c,mode);for(let iy=-2;iy<=2;iy++)for(let ix=-2;ix<=2;ix++){let dx=prior[0]+ix*.3*scale,dy=prior[1]+iy*.3*scale;let v=pixel(f,base[0]+dx,base[1]+dy).map((v,k)=>v/white[k]),d=dist(lab(v),LAB[expect]);let reg=.2*(dx*dx+dy*dy)/(scale*scale);if(d+reg<best){best=d+reg;win={x:c.x,y:c.y,dx,dy};}}offsets.push(win);}return offsets.filter(m=>{let near=offsets.filter(n=>n!==m).map(n=>({n,d:(n.x-m.x)**2+(n.y-m.y)**2})).sort((a,b)=>a.d-b.d).slice(0,8);if(!near.length)return true;let dx=median(near.map(n=>n.n.dx)),dy=median(near.map(n=>n.n.dy));return Math.hypot(m.dx-dx,m.dy-dy)<=.3*scale;});}
function buildDenseMesh(f,h,l,mode,white,previous){let pilots=l.known,scale=Math.hypot(...mapDelta(h,l.W/2,l.H/2,1,0)),offsets=[];for(let c of pilots){let base=map(h,c.x,c.y),prior=meshAt(previous,c.x,c.y),best=Infinity,win=null,expect=knownSymbol(c,mode);for(let iy=-2;iy<=2;iy++)for(let ix=-2;ix<=2;ix++){let dx=prior[0]+ix*.3*scale,dy=prior[1]+iy*.3*scale;let v=pixel(f,base[0]+dx,base[1]+dy).map((v,k)=>v/white[k]),d=dist(lab(v),LAB[expect]);let reg=.2*(dx*dx+dy*dy)/(scale*scale);if(d+reg<best){best=d+reg;win={x:c.x,y:c.y,dx,dy};}}offsets.push(win);}return offsets.filter(m=>{let near=offsets.filter(n=>n!==m).map(n=>({n,d:(n.x-m.x)**2+(n.y-m.y)**2})).sort((a,b)=>a.d-b.d).slice(0,8);if(!near.length)return true;let dx=median(near.map(n=>n.n.dx)),dy=median(near.map(n=>n.n.dy));return Math.hypot(m.dx-dx,m.dy-dy)<=.8*scale;});}
function mapDelta(h,x,y,dx,dy){let a=map(h,x,y),b=map(h,x+dx,y+dy);return [b[0]-a[0],b[1]-a[1]];}
function llr(c,mode,sigma,glare=false){if(glare)return mode?[0]:[0,0,0];let v=lab(c),classes=mode?[0,8]:[0,1,2,3,4,5,6,7],logp=classes.map(k=>-dist(v,LAB[k])/(2*sigma*sigma)),max=Math.max(...logp),p=logp.map(x=>Math.exp(x-max)),out=[];for(let b=0;b<(mode?1:3);b++){let a=1e-6,z=1e-6;for(let i=0;i<classes.length;i++){let sym=classes[i],bit=mode?(sym===0?1:0):((sym^(sym>>1))>>(2-b))&1;if(bit)a+=p[i];else z+=p[i];}out.push(clamp(Math.log(z/a),-CFG.llrClamp,CFG.llrClamp));}return out;}
function parseHeader(hb){let bits=Array.from(hb,x=>x<0?1:0),at=0;const read=n=>{let v=0;while(n--)v=(v<<1)|bits[at++];return v;};let size=read(3),ecc=read(2),mode=read(1),type=read(1),length=read(13),crc=read(4);if(crc4(bits.slice(0,20))!==crc||size>5)throw stageError('header','Header checksum did not pass');if(length>capacity(size,ecc,mode).payload)throw stageError('header','Invalid length');return {size,ecc,mode,type,length};}
function headerCandidates(hb,size,mode){let soft=Float32Array.from(hb);for(let k=0;k<3;k++)soft[k]=((size>>(2-k))&1)?-36:36;soft[5]=mode?-36:36;let uncertain=Array.from({length:24},(_,i)=>i).filter(i=>![0,1,2,5].includes(i)).sort((i,j)=>Math.abs(hb[i])-Math.abs(hb[j])).slice(0,12),out=[];function test(flips){let b=Float32Array.from(soft),cost=0;for(let i of flips){b[i]=-b[i];cost+=Math.abs(hb[i]);}try{let h=parseHeader(b);if(h.size===size&&h.mode===mode)out.push({h,cost});}catch(e){}}test([]);for(let i=0;i<uncertain.length;i++){test([uncertain[i]]);for(let j=i+1;j<uncertain.length;j++){test([uncertain[i],uncertain[j]]);for(let k=j+1;k<uncertain.length;k++)test([uncertain[i],uncertain[j],uncertain[k]]);}}out.sort((a,b)=>a.cost-b.cost);let seen=new Set();return out.filter(o=>{let key=JSON.stringify(o.h);if(seen.has(key))return false;seen.add(key);return true;}).slice(0,12).map(o=>o.h);}
function decodeClass(cls){let last;for(let header of cls.headers||[cls.header]){if(performance.now()>decodeDeadline)throw stageError('budget','Image needs a clearer view. Processing limit reached.');for(let variant of [0,1]){let stream=cls.stream;if(variant){let random=rng(0xC0DE);stream=Float32Array.from(cls.stream,v=>random()<.5?-v:v);}try{let decoded=decodeStream(header,stream);trace('ECC and payload CRC passed',{header,variant:variant?'generator-whitened':'original',corrected:decoded.corrected,erasures:decoded.erasures},null,'pass');return {...decoded,variant:variant?'generator-whitened':'original'};}catch(e){trace('ECC or CRC rejected',{header,variant:variant?'generator-whitened':'original',stage:e.stage,message:e.message},null,'fail');last=e;}}}throw last||stageError('header','Header checksum did not pass');}
function classify(f,h,l,mode,white,mesh){let cal=calibrate(f,h,l,mode,white,mesh),hb=new Float32Array(24);for(let c of l.headers){let v=sample(f,h,c,white,mesh),corrected=cal.correction(v,c),glare=v.every(x=>x>CFG.glareThreshold);/* Paper is a valid header value; never erase it merely for being white. */hb[c.header%24]+=llr(corrected,1,cal.sigma,false)[0];}let headers=headerCandidates(hb,l.size,mode).filter(header=>{if(header.length!==0)return true;try{let direct=parseHeader(hb);return JSON.stringify(direct)===JSON.stringify(header);}catch(e){return false;}}),header=headers[0];trace('Header candidates',{size:l.size,mode,candidates:headers,softBits:Array.from(hb)},null,header?'pass':'fail');if(!header)throw stageError('header','Header checksum did not pass');if(header.size!==l.size||header.mode!==mode)throw stageError('header','Header conflicts with geometry');let stream=new Float32Array(l.data.length*(mode?1:3)),points=[],at=0;for(let c of l.data){let v=sample(f,h,c,white,mesh),cv=cal.correction(v,c),glare=!mode&&v.every(x=>x>CFG.glareThreshold),soft=llr(cv,mode,cal.sigma,glare);for(let q of soft)stream[at++]=q;points.push({x:c.x,y:c.y,confidence:Math.min(...soft.map(Math.abs))/12});}let matched=0;for(let v of cal.refs)if(nearest(cal.correction(v.o,v.c),mode).symbol===knownSymbol(v.c,mode))matched++;if(globalThis.PrismTrace?.active){let shown=l.cells.filter((_,i)=>i%Math.max(1,Math.ceil(l.cells.length/1800))===0).map(c=>{let v=sample(f,h,c,white,mesh),rgb=cal.correction(v,c).map(x=>Math.round(255*clamp(srgb(x)))),pt=map(h,c.x,c.y),of=meshAt(mesh,c.x,c.y);return {x:pt[0]+of[0],y:pt[1]+of[1],rgb,rawRgb:v.map(x=>Math.round(255*clamp(srgb(x)))),role:c.role,expected:c.role==='pilot'||c.role==='ring'?knownSymbol(c,mode):null};});trace('Sampled cells and color calibration',{size:l.size,mode,sigma:cal.sigma,whiteBalance:white,knownMatch:matched/cal.refs.length,meshPoints:mesh?.length||0,totalCells:l.cells.length,shownCells:shown.length,legend:'Dots show calibrated sampled RGB. White outlines mark existing ring/pilot cells. Tap a dot for raw and calibrated RGB and role. Large layouts are subsampled for this view only.',header},{image:globalThis.PrismTrace.sampleImage||0,cells:shown,h:Array.from(h)});}return {header,headers,stream,hb,sigma:cal.sigma,points,knownMatch:matched/cal.refs.length};}
function PADK(o){let x=Math.imul(o+0x9E3779B9|0,0x85EBCA6B);x^=x>>>13;x=Math.imul(x,0xC2B2AE35);x^=x>>>16;return x&255}function padVote(h,st){if(!(h.length>0))return true;let c=capacity(h.size,h.ecc,h.mode),by=new Uint8Array(c.n),bl=c.blocks,offs=[],a=0,at=0,z=0,q=0;for(let i=0;i<c.n;i++){let v=0;for(let k=0;k<8;k++)v=(v<<1)|(st[8*i+k]<0?1:0);by[i]=v;}for(let b of bl){offs.push(a);a+=b.k;}for(let p=0;p<Math.max(...bl.map(x=>x.n));p++)for(let j=0;j<bl.length;j++){let b=bl[j];if(p<b.n){if(p<b.k&&offs[j]+p>=h.length+4){let v=by[at];if(v===0)z++;if(v===PADK(offs[j]+p))q++;}at++;}}return q>=z;}function PLcd(l){if(l.cd)return l.cd;let cx=l.W/2,cy=l.H/2,a=l.data.map((c,k)=>{let dx=c.x-cx,dy=c.y-cy;return{c:c,k:k,b:Math.floor(Math.sqrt(dx*dx+dy*dy)/3)}});a.sort((p,q)=>q.b-p.b||p.k-q.k);return l.cd=a.map(o=>o.c)}function PLfb(h,st,DEC,LAY){let l=LAY(h.size),cd=PLcd(l),N=l.data.length,m=h.mode?1:3;if(st.length<N*m)throw new Error();if(!l.pos){l.pos=new Map();l.data.forEach((c,k)=>l.pos.set(c.index,k))}let s2=new Float32Array(N*m);for(let k=0;k<N;k++){let p=l.pos.get(cd[k].index);for(let j=0;j<m;j++)s2[k*m+j]=st[p*m+j]}let n1=Math.floor(N*.12),ga=0,gb=0,gc=0,gd=0;for(let k=0;k<N;k++){let v=0;for(let j=0;j<m;j++)v+=Math.abs(s2[k*m+j]);if(k>=N-n1){ga+=v;gb++}else if(k<N/2){gc+=v;gd++}}if(ga/gb>0.9*gc/gd)throw new Error();let err;for(let f of [.1,.18,.26,.34]){let s3=Float32Array.from(s2);for(let k=Math.floor(N*(1-f));k<N;k++)for(let j=0;j<m;j++)s3[k*m+j]=0;try{return DEC(h,s3)}catch(e){err=e}}throw err}function decodeStream(h,st){try{return decodeStream0(h,st)}catch(e){if(!globalThis.PRISM_NOLOGO){try{return PLfb(h,st,decodeStream0,layout)}catch(e2){}}throw e}}function decodeStream0(header,stream){let t=padVote(header,stream);try{return decodeStreamP(header,stream,t);}catch(e){try{return decodeStreamP(header,stream,!t);}catch(e2){throw e;}}}function decodeStreamP(header,stream,PK){
let cap=capacity(header.size,header.ecc,header.mode),bytes=new Uint8Array(cap.n),conf=new Float32Array(cap.n);
for(let i=0;i<cap.n;i++){let v=0,q=12;for(let k=0;k<8;k++){let s=stream[8*i+k];v=(v<<1)|(s<0?1:0);q=Math.min(q,Math.abs(s));}bytes[i]=v;conf[i]=q;}
let blocks=cap.blocks.map(b=>({bytes:new Uint8Array(b.n),conf:new Float32Array(b.n),candidates:[],tried:new Set(),...b})),at=0;
for(let p=0;p<Math.max(...blocks.map(x=>x.n));p++)for(let b of blocks)if(p<b.n){b.bytes[p]=bytes[at];b.conf[p]=conf[at++];}
let rsAttempts=0,rsValid=0;let messageOffset=0;for(let b of blocks){b.offset=messageOffset;for(let p=0;p<b.k;p++)if(header.length>0&&messageOffset+p>=header.length+4){b.bytes[p]=PK?PADK(messageOffset+p):0;b.conf[p]=12;}messageOffset+=b.k;b.order=Array.from({length:b.n},(_,i)=>i).sort((i,j)=>b.conf[i]-b.conf[j]);}
function attempt(b,m){if(b.tried.has(m))return;rsAttempts++;b.tried.add(m);try{let ok=rsDecode(b.bytes,b.nsym,b.order.slice(0,m));for(let p=0;p<b.k;p++)if(b.offset+p>=header.length+4&&ok.bytes[p]!==(PK?PADK(b.offset+p):0))return;rsValid++;let data=ok.bytes.slice(0,b.k);if(b.candidates.some(v=>v.data.every((x,i)=>x===data[i])))return;trace('RS block corrected',{block:blocks.indexOf(b),blockLength:b.n,parity:b.nsym,erasures:m,corrected:ok.corrected,changedPositions:Array.from(ok.bytes,(_,i)=>i).filter(i=>ok.bytes[i]!==b.bytes[i])},null,'pass');let score=0;for(let p=0;p<b.n;p++)if(ok.bytes[p]!==b.bytes[p])score+=.02+b.conf[p];b.candidates.push({data,corrected:ok.corrected,erasures:m,score});b.candidates.sort((a,b)=>a.score-b.score);b.candidates.length=Math.min(8,b.candidates.length);}catch(e){}}
function assemble(){let combinations=0,found=null;function visit(i,msg,corrected,erasures){if(found||combinations>=1024)return;if(i===blocks.length){combinations++;let payload=Uint8Array.from(msg.slice(0,header.length)),crc=0;for(let v of msg.slice(header.length,header.length+4))crc=(crc<<8)|v;if(crc32(payload)===(crc>>>0)){let text=null;if(!header.type)try{text=new TextDecoder('utf-8',{fatal:true}).decode(payload);}catch(e){return;}found={bytes:payload,text,header,corrected,erasures};}return;}for(let c of blocks[i].candidates)visit(i+1,msg.concat(Array.from(c.data)),corrected+c.corrected,erasures+c.erasures);}visit(0,[],0,0);trace('RS erasure ladder',{header,blocks:blocks.map(b=>({length:b.n,parity:b.nsym,triedErasures:Array.from(b.tried),validCandidates:b.candidates.length})),attempts:rsAttempts,validCodewords:rsValid,crcCombinations:combinations,crcPassed:!!found},null,found?'pass':'info');return found;}
for(let b of blocks)for(let m of [...new Set([0,.25,.5,.75,1].map(q=>Math.round(b.nsym*q)))]){attempt(b,m);if(b.candidates.length)break;}
let result=assemble();if(result)return result;
/* CRC can reject a valid but wrong RS codeword. Densify the erasure ladder
and check bounded combinations rather than returning unverified bytes. */
for(let b of blocks)for(let m=0;m<=b.nsym;m+=2)attempt(b,m);
result=assemble();if(result)return result;
if(blocks.some(b=>!b.candidates.length))throw stageError('RS','Error correction could not recover this image');
throw stageError('CRC','Payload checksum did not pass');
}
function readNormal(image,{known=null,mesh=true,onStage=null,fusion=null,debug=false}={}){let start=performance.now(),f=frame(image);onStage?.('detect');let hyps=[];if(known){let l=layout(known.size),h=homography(corners(l),known.quad),white=whiteBalance(f,h,l);hyps=[{h,l,mode:known.mode,quad:known.quad,white,...hypothesisScore(f,h,l,known.mode,white)}];}else{let quads=detect(f);onStage?.('hypothesis');for(let quad of quads)for(let size=0;size<6;size++){let l=layout(size);for(let rot=0;rot<4;rot++){let q=quad.map((_,i)=>quad[(i+rot)%4]),h;try{h=homography(corners(l),q);}catch(e){continue;}let white=whiteBalance(f,h,l);for(let mode=0;mode<2;mode++){let sc=hypothesisScore(f,h,l,mode,white,true);hyps.push({h,l,mode,quad:q,white,rot,...sc});trace('Legacy hypothesis',{size,mode,rotation:rot*90,...sc},{quad:q,image:0});}}}hyps.sort((a,b)=>b.score-a.score||a.cost-b.cost);hyps=hyps.slice(0,4);}trace('Ranked legacy shortlist',{candidates:hyps.map(v=>({size:v.l.size,mode:v.mode,score:v.score,cost:v.cost,rotation:(v.rot||0)*90}))});let attempts=[],bestError=null;const stageRank={detect:0,hypothesis:1,'too small':1,header:2,RS:3,CRC:4};let last=stageError('hypothesis','Code pattern not recognized. Try better light or a closer photo.');for(let hyp of hyps){try{let {h,l,mode,quad,white}=hyp;if(!known){onStage?.('refine');let refined=refine(f,h,l,mode,quad,white);h=refined.h;quad=refined.quad;white=whiteBalance(f,h,l);}let quality=hypothesisScore(f,h,l,mode,white,false).score;trace('Legacy geometry refined',{size:l.size,mode,quality,orientation:'Known-cell ring and header validate notch orientation'},{quad,h:Array.from(h),warp:h.warp||null,W:l.W,H:l.H,image:0});if(quality<(mode?.75:CFG.minScore))throw stageError('hypothesis','Known cells do not match');let radius=Math.min(Math.hypot(...mapDelta(h,l.W/2,l.H/2,1,0)),Math.hypot(...mapDelta(h,l.W/2,l.H/2,0,1)));if(radius<CFG.minRadius)throw stageError('too small','Too small. Move closer or use a larger image.');onStage?.('calibrate');let m=null,cls;try{cls=classify(f,h,l,mode,white,null);}catch(e){if(!mesh)throw e;last=e;}let result=null;try{if(cls)result=decodeClass(cls);}catch(e){last=e;}if(!result&&mesh){onStage?.('mesh');m=buildMesh(f,h,l,mode,white,null);m=buildMesh(f,h,l,mode,white,m);cls=classify(f,h,l,mode,white,m);try{result=decodeClass(cls);}catch(e){last=e;}}if(fusion&&cls){let merged=fusion.add(cls.header,cls.stream,quality);if(!result)try{result=decodeClass({...cls,stream:merged});}catch(e){last=e;}}if(result)return {...result,quality,radius,quad,h,layout:l,points:debug?cls.points:null,sigma:cls.sigma,ms:performance.now()-start};if(debug){last.debug={quad,h,layout:l,points:cls?.points};}throw last;}catch(e){if(!bestError||(stageRank[e.stage]||0)>(stageRank[bestError.stage]||0))bestError=e;trace('Legacy attempt rejected',{size:hyp.l.size,mode:hyp.mode,stage:e.stage,message:e.message},null,'fail');attempts.push({size:hyp.l.size,mode:hyp.mode,score:hyp.score,cost:hyp.cost,stage:e.stage,message:e.message});if(!last||['RS','CRC'].includes(e.stage)||!['RS','CRC'].includes(last.stage))last=e;}}last=bestError||last;last.attempts=attempts;throw last;}
/* Compatibility fallback for full-canvas exports from the supplied generator.
Geometry is inferred from the bitmap aspect and known-cell consistency.
No payload, expected text, filename, or effect-slider values are supplied. */
function readGeneratorExport(image,debug=false){let f=frame(image),candidates=[];
for(let size=0;size<6;size++){let l=layout(size),r=(f.w/(l.W+2*Q)+f.h/(l.H+2*Q))/2;if(r<CFG.minRadius||Math.abs((l.W+2*Q)*r-f.w)>2||Math.abs((l.H+2*Q)*r-f.h)>2)continue;let known=l.known.filter(c=>c.role==='ring'||c.role==='pilot'),stride=Math.max(1,Math.floor(known.length/180));known=known.filter((_,i)=>i%stride===0);const h=[r,0,Q*r,0,r,Q*r,0,0];
function cost(skew,curve){let buckets=Array.from({length:9},()=>[]),t=Math.tan(skew*Math.PI/180);for(let c of known){let y=(c.y+Q)*r,dx=t*(y/f.h-.5)*y+Math.sin(y/f.h*Math.PI)*curve*f.w*.08,v=pixel(f,(c.x+Q)*r+dx,y).map(srgb);buckets[c.symbol].push(v);}let centers=buckets.map(a=>a.length?[0,1,2].map(k=>a.reduce((s,v)=>s+v[k],0)/a.length):[0,0,0]),within=0,between=0,mean=[0,0,0],classes=0;for(let i=0;i<9;i++)if(buckets[i].length){classes++;for(let k=0;k<3;k++)mean[k]+=centers[i][k];}mean=mean.map(x=>x/classes);for(let i=0;i<9;i++)if(buckets[i].length){between+=centers[i].reduce((s,x,k)=>s+(x-mean[k])**2,0);for(let v of buckets[i])within+=v.reduce((s,x,k)=>s+(x-centers[i][k])**2,0);}if(between<.02)return 1e6;return within/known.length/(between/classes);}
let best={loss:Infinity,skew:0,curve:0};for(let skew=-18;skew<=18;skew+=3)for(let curve=0;curve<=1.001;curve+=.1){let loss=cost(skew,curve);if(loss<best.loss)best={loss,skew,curve};}let base=best;for(let ds=-3;ds<=3.001;ds+=.3)for(let dc=-.1;dc<=.1001;dc+=.01){let skew=base.skew+ds,curve=base.curve+dc,loss=cost(skew,curve);if(loss<best.loss)best={loss,skew,curve};}candidates.push({size,l,r,h,...best});}
trace('Full-canvas curve fit candidates',{candidates:candidates.map(({size,r,skew,curve,loss})=>({size,r,skew,curve,loss}))});candidates.sort((a,b)=>a.loss-b.loss);let last=stageError('hypothesis','Full-canvas export geometry did not match');for(let candidate of candidates.slice(0,2)){if(performance.now()>decodeDeadline)throw stageError('budget','Processing limit reached');if(candidate.loss>.45)continue;let {l,r,h,skew,curve}=candidate,rect=new ImageData(f.w,f.h),t=Math.tan(skew*Math.PI/180);for(let y=0;y<f.h;y++)for(let x=0;x<f.w;x++){let dx=t*(y/f.h-.5)*y+Math.sin(y/f.h*Math.PI)*curve*f.w*.08,v=pixel(f,x+dx,y),at=(y*f.w+x)*4;for(let k=0;k<3;k++)rect.data[at+k]=clamp(srgb(v[k]))*255;rect.data[at+3]=255;}globalThis.PrismTrace?.image('Full-canvas rectified pixels',rect);if(globalThis.PrismTrace?.active)globalThis.PrismTrace.sampleImage=globalThis.PrismTrace.currentImage;let ff=frame(rect),white=whiteBalance(ff,h,l);try{let cls=classify(ff,h,l,0,white,null),res=decodeClass(cls);if(!res.bytes.length)throw stageError('header','Empty payload needs a direct high-confidence header');return {...res,quality:cls.knownMatch,radius:r,quad:corners(l).map(([x,y])=>map(h,x,y)),h,layout:l,points:debug?cls.points:null,sigma:cls.sigma,fallback:'full-canvas generator curve model',fitted:{skew,curve,loss:candidate.loss},rectified:debug?rect:null};}catch(e){last=e;}}throw last;}
function readImage(image,options={}){let start=performance.now(),error;decodeDeadline=start+2500;try{let result=readNormal(image,options);if(!result.bytes.length&&result.quality<.8)throw stageError('hypothesis','Empty result lacks a strong code-pattern match');return result;}catch(e){error=e;}if(!options.known&&options.exportFallback!==false)try{let result=readGeneratorExport(image,options.debug);return {...result,ms:performance.now()-start};}catch(e){}throw error;}
class Fusion{constructor(){this.reset();}reset(){this.key=null;this.stream=null;this.time=0;this.frames=0;}add(header,s,quality){let key=JSON.stringify(header),now=performance.now();if(key!==this.key||now-this.time>3000||s.length!==this.stream?.length){this.key=key;this.stream=new Float32Array(s.length);this.frames=0;}let w=quality**2;for(let i=0;i<s.length;i++)this.stream[i]+=s[i]*w;this.time=now;this.frames++;return this.stream;}}
return {beginDecode:ms=>decodeDeadline=performance.now()+ms,CFG,SIZES,HEX,PAL,LAB,S3,Q,rng,layout,capacity,encode,render,rsEncode,rsDecode,syndromes,crc32,crc4,headerBits,frame,homography,map,corners,readImage,decodeStream,parseHeader,lab,lin,srgb,Fusion,detect,detectCurved,refine,knownSymbol,hypothesisScore,whiteBalance,classify,buildMesh,buildDenseMesh,readGeneratorExport,decodeClass,sample,calibrate,llr,nearest};
})();
</script><script>
/*!
* hash-wasm (https://www.npmjs.com/package/hash-wasm)
* (c) Dani Biro
* @license MIT
*/
!function(A,I){"object"==typeof exports&&"undefined"!=typeof module?I(exports):"function"==typeof define&&define.amd?define(["exports"],I):I((A="undefined"!=typeof globalThis?globalThis:A||self).hashwasm=A.hashwasm||{})}(this,function(A){"use strict";function I(A,I,i,g){return new(i||(i=Promise))(function(C,B){function Q(A){try{h(g.next(A))}catch(A){B(A)}}function E(A){try{h(g.throw(A))}catch(A){B(A)}}function h(A){var I;A.done?C(A.value):(I=A.value,I instanceof i?I:new i(function(A){A(I)})).then(Q,E)}h((g=g.apply(A,I||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;var i,g={name:"argon2",data:"AGFzbQEAAAABKQVgAX8Bf2AAAX9gEH9/f39/f39/f39/f39/f38AYAR/f39/AGACf38AAwYFAAECAwQFBgEBAoCAAgYIAX8BQYCABAsHUwUGbWVtb3J5AgAPX19zdGFja19wb2ludGVyAwASSGFzaF9TZXRNZW1vcnlTaXplAAAOSGFzaF9HZXRCdWZmZXIAAQ5IYXNoX0NhbGN1bGF0ZQAECsc2BV0DAX8BfgF/QQAhAQJAIABBACkDiIAEIgKnIgNGDQBBACEBAkAgACADayIAQRB2IABB//8DcUEAR2oiAEAAQX9HDQBB/wHADwtBACACIABBEHStfDcDiIAECyABwAt0AwJ/AX4BfwJAQQAoAoCABCIADQBBAD8AQRB0IgE2AoCABAJAQQApA4iABCICpyIDQYCAIEYNAEEAIQBBgIAgIANrIgNBEHYgA0H//wNxQQBHaiIDQABBf0YNAUEAIAIgA0EQdK18NwOIgAQLIAEhAAsgAAvcDgECfiAAIAQpAwAiECAAKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAMIBAgDCkDAIVCIIkiEDcDACAIIBAgCCkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgBCAQIAQpAwCFQiiJIhA3AwAgACAQIAApAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAwgECAMKQMAhUIwiSIQNwMAIAggECAIKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAEIBAgBCkDAIVCAYk3AwAgASAFKQMAIhAgASkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDSAQIA0pAwCFQiCJIhA3AwAgCSAQIAkpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAUgECAFKQMAhUIoiSIQNwMAIAEgECABKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACANIBAgDSkDAIVCMIkiEDcDACAJIBAgCSkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBSAQIAUpAwCFQgGJNwMAIAIgBikDACIQIAIpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIA4gECAOKQMAhUIgiSIQNwMAIAogECAKKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAGIBAgBikDAIVCKIkiEDcDACACIBAgAikDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgDiAQIA4pAwCFQjCJIhA3AwAgCiAQIAopAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAYgECAGKQMAhUIBiTcDACADIAcpAwAiECADKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAPIBAgDykDAIVCIIkiEDcDACALIBAgCykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgByAQIAcpAwCFQiiJIhA3AwAgAyAQIAMpAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIA8gECAPKQMAhUIwiSIQNwMAIAsgECALKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgACAFKQMAIhAgACkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDyAQIA8pAwCFQiCJIhA3AwAgCiAQIAopAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAUgECAFKQMAhUIoiSIQNwMAIAAgECAAKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAPIBAgDykDAIVCMIkiEDcDACAKIBAgCikDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBSAQIAUpAwCFQgGJNwMAIAEgBikDACIQIAEpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAwgECAMKQMAhUIgiSIQNwMAIAsgECALKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAGIBAgBikDAIVCKIkiEDcDACABIBAgASkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgDCAQIAwpAwCFQjCJIhA3AwAgCyAQIAspAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAYgECAGKQMAhUIBiTcDACACIAcpAwAiECACKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACANIBAgDSkDAIVCIIkiEDcDACAIIBAgCCkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgByAQIAcpAwCFQiiJIhA3AwAgAiAQIAIpAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIA0gECANKQMAhUIwiSIQNwMAIAggECAIKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgAyAEKQMAIhAgAykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDiAQIA4pAwCFQiCJIhA3AwAgCSA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AWoiA0EIaiAcIAFqIgRBCGopAwA3AwAgBEEQaikDACEfIARBGGopAwAhGyADQSBqIARBIGopAwA3AwAgA0EYaiAbNwMAIANBEGogHzcDACABQSBqIgFB+AdJDQALCws=",hash:"2b50b0d6"};class C{constructor(){this.mutex=Promise.resolve()}lock(){let A=()=>{};return this.mutex=this.mutex.then(()=>new Promise(A)),new Promise(I=>{A=I})}dispatch(A){return I(this,void 0,void 0,function*(){const I=yield this.lock();try{return yield Promise.resolve(A())}finally{I()}})}}const B="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Q=null!==(i=B.Buffer)&&void 0!==i?i:null,E=B.TextEncoder?new B.TextEncoder:null;function h(A,I){return(15&A)+(A>>6|A>>3&8)<<4|(15&I)+(I>>6|I>>3&8)}function w(A,I){const i=I.length>>1;for(let g=0;g<i;g++){const i=g<<1;A[g]=h(I.charCodeAt(i),I.charCodeAt(i+1))}}const e="a".charCodeAt(0)-10,t="0".charCodeAt(0);function o(A,I,i){let g=0;for(let C=0;C<i;C++){let i=I[C]>>>4;A[g++]=i>9?i+e:i+t,i=15&I[C],A[g++]=i>9?i+e:i+t}return String.fromCharCode.apply(null,A)}const n=null!==Q?A=>{if("string"==typeof A){const I=Q.from(A,"utf8");return new Uint8Array(I.buffer,I.byteOffset,I.length)}if(Q.isBuffer(A))return new Uint8Array(A.buffer,A.byteOffset,A.length);if(ArrayBuffer.isView(A))return new Uint8Array(A.buffer,A.byteOffset,A.byteLength);throw new Error("Invalid data type!")}:A=>{if("string"==typeof A)return E.encode(A);if(ArrayBuffer.isView(A))return new Uint8Array(A.buffer,A.byteOffset,A.byteLength);throw new Error("Invalid data type!")},f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=new Uint8Array(256);for(let A=0;A<64;A++)r[f.charCodeAt(A)]=A;function F(A,I=!0){const i=A.length,g=i%3,C=[],B=i-g;for(let I=0;I<B;I+=3){const i=(A[I]<<16&16711680)+(A[I+1]<<8&65280)+(255&A[I+2]),g=f.charAt(i>>18&63)+f.charAt(i>>12&63)+f.charAt(i>>6&63)+f.charAt(63&i);C.push(g)}if(1===g){const g=A[i-1],B=f.charAt(g>>2),Q=f.charAt(g<<4&63);C.push(`${B}${Q}`),I&&C.push("==")}else if(2===g){const g=(A[i-2]<<8)+A[i-1],B=f.charAt(g>>10),Q=f.charAt(g>>4&63),E=f.charAt(g<<2&63);C.push(`${B}${Q}${E}`),I&&C.push("=")}return C.join("")}function D(A){let I=Math.floor(.75*A.length);const i=A.length;return"="===A[i-1]&&(I-=1,"="===A[i-2]&&(I-=1)),I}function a(A){const I=D(A),i=A.length,g=new Uint8Array(I);let C=0;for(let I=0;I<i;I+=4){const i=r[A.charCodeAt(I)],B=r[A.charCodeAt(I+1)],Q=r[A.charCodeAt(I+2)],E=r[A.charCodeAt(I+3)];g[C]=i<<2|B>>4,C+=1,g[C]=(15&B)<<4|Q>>2,C+=1,g[C]=(3&Q)<<6|63&E,C+=1}return g}const s=16384,U=new C,S=new Map;function c(A,i){return I(this,void 0,void 0,function*(){let g=null,C=null,B=!1;if("undefined"==typeof WebAssembly)throw new Error("WebAssembly is not supported in this environment!");const Q=()=>new DataView(g.exports.memory.buffer).getUint32(g.exports.STATE_SIZE,!0),E=U.dispatch(()=>I(this,void 0,void 0,function*(){if(!S.has(A.name)){const I=a(A.data),i=WebAssembly.compile(I.buffer);S.set(A.name,i)}const I=yield S.get(A.name);g=yield WebAssembly.instantiate(I,{})})),e=(A=null)=>{B=!0,g.exports.Hash_Init(A)},t=A=>{if(!B)throw new Error("update() called before init()");(A=>{let I=0;for(;I<A.length;){const i=A.subarray(I,I+s);I+=i.length,C.set(i),g.exports.Hash_Update(i.length)}})(n(A))},f=new Uint8Array(2*i),r=(A,I=null)=>{if(!B)throw new Error("digest() called before init()");return B=!1,g.exports.Hash_Final(I),"binary"===A?C.slice(0,i):o(f,C,i)},F=A=>"string"==typeof A?A.length<4096:A.byteLength<s;let D=F;switch(A.name){case"argon2":case"scrypt":D=()=>!0;break;case"blake2b":case"blake2s":D=(A,I)=>I<=512&&F(A);break;case"blake3":D=(A,I)=>0===I&&F(A);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":D=()=>!1}return yield(()=>I(this,void 0,void 0,function*(){g||(yield E);const A=g.exports.Hash_GetBuffer(),I=g.exports.memory.buffer;C=new Uint8Array(I,A,s)}))(),{getMemory:()=>C,writeMemory:(A,I=0)=>{C.set(A,I)},getExports:()=>g.exports,setMemorySize:A=>{g.exports.Hash_SetMemorySize(A);const I=g.exports.Hash_GetBuffer(),i=g.exports.memory.buffer;C=new Uint8Array(i,I,A)},init:e,update:t,digest:r,save:()=>{if(!B)throw new Error("save() can only be called after init() and before digest()");const I=g.exports.Hash_GetState(),i=Q(),C=g.exports.memory.buffer,E=new Uint8Array(C,I,i),h=new Uint8Array(4+i);return w(h,A.hash),h.set(E,4),h},load:I=>{if(!(I instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const i=g.exports.Hash_GetState(),C=Q(),E=4+C,w=g.exports.memory.buffer;if(I.length!==E)throw new Error(`Bad state length (expected ${E} bytes, got ${I.length})`);if(!function(A,I){if(A.length!==2*I.length)return!1;for(let i=0;i<I.length;i++){const g=i<<1;if(I[i]!==h(A.charCodeAt(g),A.charCodeAt(g+1)))return!1}return!0}(A.hash,I.subarray(0,4)))throw new Error("This state was written by an incompatible hash implementation");const e=I.subarray(4);new Uint8Array(w,i,C).set(e),B=!0},calculate:(A,I=null,B=null)=>{if(!D(A,I))return e(I),t(A),r("hex",B);const Q=n(A);return C.set(Q),g.exports.Hash_Calculate(Q.length,I,B),o(f,C,i)},hashLength:i}})}var k={name:"blake2b",data:"AGFzbQEAAAABEQRgAAF/YAJ/fwBgAX8AYAAAAwoJAAECAwECAgABBQQBAQICBg8CfwFBgIAEC38AQYCABAsHggEJBm1lbW9yeQIAD19fc3RhY2tfcG9pbnRlcgMADkhhc2hfR2V0Qn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ACQgA3AzAgAkIANwMoIAJCADcDICACQgA3AxggAkIANwMQIAJCADcDCCACQgA3AwBBACEAA0AgAiAAaiAAQYCBBGotAAA6AAAgAEEBaiEAIAEgA0EBaiIDQf8BcUsNAAsgAkGAARABCyACQYABaiQACxIAIABBA3ZB/z9xIABBEHYQBAsKAEGAgQQgABABCwYAQYCBBQscACABQQN2Qf8/cSABQRB2EARBgIEEIAAQARADCwsMAQBBgIAECwTwAAAA",hash:"22cf500a"};function G(A){return!Number.isInteger(A)||A<8||A>512||A%8!=0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function p(A=512,I=null){if(G(A))return Promise.reject(G(A));let i=null,g=A;if(null!==I){if(i=n(I),i.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));C=A,B=i.length,g=C|B<<16}var C,B;const Q=A/8;return c(k,Q).then(A=>{g>512&&A.writeMemory(i),A.init(g);const I={init:g>512?()=>(A.writeMemory(i),A.init(g),I):()=>(A.init(g),I),update:i=>(A.update(i),I),digest:I=>A.digest(I),save:()=>A.save(),load:i=>(A.load(i),I),blockSize:128,digestSize:Q};return I})}new C;const y=new DataView(new ArrayBuffer(4));function H(A){return y.setInt32(0,A,!0),new Uint8Array(y.buffer)}function u(A,i,g){return I(this,void 0,void 0,function*(){if(g<=64){const A=yield p(8*g);return A.update(H(g)),A.update(i),A.digest("binary")}const I=Math.ceil(g/32)-2,C=new Uint8Array(g);A.init(),A.update(H(g)),A.update(i);let B=A.digest("binary");C.set(B.subarray(0,32),0);for(let i=1;i<I;i++)A.init(),A.update(B),B=A.digest("binary"),C.set(B.subarray(0,32),32*i);const Q=g-32*I;let E;return 64===Q?(E=A,E.init()):E=yield p(8*Q),E.update(B),B=E.digest("binary"),C.set(B.subarray(0,Q),32*I),C})}function Y(A){return I(this,void 0,void 0,function*(){var I;const{parallelism:i,iterations:C,hashLength:B}=A,Q=n(A.password),E=n(A.salt),h=function(A){switch(A){case"d":return 0;case"i":return 1;default:return 2}}(A.hashType),{memorySize:e}=A,t=n(null!==(I=A.secret)&&void 0!==I?I:""),[f,r]=yield Promise.all([c(g,1024),p(512)]);f.setMemorySize(1024*e+1024);const D=new Uint8Array(24),a=new DataView(D.buffer);a.setInt32(0,i,!0),a.setInt32(4,B,!0),a.setInt32(8,e,!0),a.setInt32(12,C,!0),a.setInt32(16,19,!0),a.setInt32(20,h,!0),f.writeMemory(D,1024*e),r.init(),r.update(D),r.update(H(Q.length)),r.update(Q),r.update(H(E.length)),r.update(E),r.update(H(t.length)),r.update(t),r.update(H(0));const s=4*Math.floor(e/(4*i)),U=new Uint8Array(72),S=r.digest("binary");U.set(S);for(let A=0;A<i;A++){U.set(H(0),64),U.set(H(A),68);let I=A*s,i=yield u(r,U,1024);f.writeMemory(i,1024*I),I+=1,U.set(H(1),64),i=yield u(r,U,1024),f.writeMemory(i,1024*I)}const k=new Uint8Array(1024);w(k,f.calculate(new Uint8Array([]),e));const G=yield u(r,k,B);if("hex"===A.outputType){return o(new Uint8Array(2*B),G,B)}return"encoded"===A.outputType?function(A,I,i){const g=[`m=${I.memorySize}`,`t=${I.iterations}`,`p=${I.parallelism}`].join(",");return`$argon2${I.hashType}$v=19$${g}$${F(A,!1)}$${F(i,!1)}`}(E,A,G):G})}const V=A=>{var I;if(!A||"object"!=typeof A)throw new Error("Invalid options parameter. It requires an object.");if(!A.password)throw new Error("Password must be specified");if(A.password=n(A.password),A.password.length<1)throw new Error("Password must be specified");if(!A.salt)throw new Error("Salt must be specified");if(A.salt=n(A.salt),A.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(A.secret=n(null!==(I=A.secret)&&void 0!==I?I:""),!Number.isInteger(A.iterations)||A.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(A.parallelism)||A.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(A.hashLength)||A.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(A.memorySize))throw new Error("Memory size should be specified.");if(A.memorySize<8*A.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(void 0===A.outputType&&(A.outputType="hex"),!["hex","binary","encoded"].includes(A.outputType))throw new Error(`Insupported output type ${A.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};A.argon2Verify=function(A){return I(this,void 0,void 0,function*(){(A=>{if(!A||"object"!=typeof A)throw new Error("Invalid options parameter. It requires an object.");if(void 0===A.hash||"string"!=typeof A.hash)throw new Error("Hash should be specified")})(A);const I=((A,I,i)=>{const g=I.match(/^\$argon2(id|i|d)\$v=([0-9]+)\$((?:[mtp]=[0-9]+,){2}[mtp]=[0-9]+)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/);if(!g)throw new Error("Invalid hash");const[,C,B,Q,E,h]=g;if("19"!==B)throw new Error(`Unsupported version: ${B}`);const w={},e={m:"memorySize",p:"parallelism",t:"iterations"};for(const A of Q.split(",")){const[I,i]=A.split("=");w[e[I]]=Number(i)}return Object.assign(Object.assign({},w),{password:A,secret:i,hashType:C,salt:a(E),hashLength:D(h),outputType:"encoded"})})(A.password,A.hash,A.secret);V(I);const i=A.hash.lastIndexOf("$")+1;return(yield Y(I)).substring(i)===A.hash.substring(i)})},A.argon2d=function(A){return I(this,void 0,void 0,function*(){return V(A),Y(Object.assign(Object.assign({},A),{hashType:"d"}))})},A.argon2i=function(A){return I(this,void 0,void 0,function*(){return V(A),Y(Object.assign(Object.assign({},A),{hashType:"i"}))})},A.argon2id=function(A){return I(this,void 0,void 0,function*(){return V(A),Y(Object.assign(Object.assign({},A),{hashType:"id"}))})}});
</script><script>
/* Comb Code Secure: optional encryption and signing layer for Comb Code payloads.
Separate from the reader. It only transforms the bytes put into a code and the
bytes read back out. Offline, no network.
Envelope v2 (bytes): "PSC" 0x02 | flags | body
flags bit0 = encrypted, bit1 = signed
encrypted body: kdf(1) kdfParams(6) salt(16) iv(12) ciphertext+tag(16)
kdf 2 = Argon2id: memKiB(4, BE) passes(1) lanes(1) (default 128 MiB, 3 passes)
kdf 1 = PBKDF2-SHA256: iterations(4, BE) + 2 unused (fallback, 600,000 rounds)
signed: appended pubkey(65, P-256 raw) + signature(64) over everything before it
Encryption: AES-256-GCM, fresh random salt (16 bytes) and nonce (12 bytes) per code;
the whole header is authenticated as additional data. v1 codes (PBKDF2 only) still open.
Signing: ECDSA P-256 / SHA-256. Proves the code is unchanged and made by the holder of
that key; who owns the key is only known if the reader already trusts its fingerprint.
Argon2id comes from hash-wasm (MIT), loaded as global `hashwasm` (argon2.umd.min.js). */
(function (root) {
const C = root.crypto || require('node:crypto').webcrypto, subtle = C.subtle;
const rnd = n => C.getRandomValues(new Uint8Array(n));
const MAGIC = [0x50, 0x53, 0x43], F_ENC = 1, F_SIG = 2;
const PBKDF2_ITER = 600000, A2 = { mem: 131072, t: 3, p: 1 }, MAX_MEM = 262144, MAX_T = 12;
const HEAD2 = 4 + 1 + 1 + 6 + 16 + 12, HEAD1 = 4 + 1 + 16 + 12 + 4;
const enc = s => new TextEncoder().encode(s);
const cat = (...a) => { let o = new Uint8Array(a.reduce((n, x) => n + x.length, 0)), p = 0; for (const x of a) { o.set(x, p); p += x.length; } return o; };
const hex = b => [...b].map(x => x.toString(16).padStart(2, '0')).join('');
const be32 = n => new Uint8Array([n >>> 24, n >>> 16 & 255, n >>> 8 & 255, n & 255]);
const rd32 = (b, i) => ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0;
const wipe = b => { if (b && b.fill) b.fill(0); };
/* Compare without stopping at the first difference. */
function ctEqual(a, b) { if (typeof a === 'string') a = enc(a); if (typeof b === 'string') b = enc(b); let d = a.length ^ b.length; const n = Math.max(a.length, b.length); for (let i = 0; i < n; i++) d |= (a[i] || 0) ^ (b[i] || 0); return d === 0; }
const inList = (list, v) => { let f = false; for (const x of list) if (ctEqual(x, v)) f = true; return f; };
const argon = () => root.hashwasm && root.hashwasm.argon2id;
const hasArgon2 = () => !!argon();
async function deriveKey(pass, salt, kdf, p) {
const pw = enc(pass.normalize('NFKC'));
try {
if (kdf === 2) {
if (!argon()) throw Error('This code needs Argon2id, which is not loaded');
const raw = await argon()({ password: pw, salt, parallelism: p.p, iterations: p.t, memorySize: p.mem, hashLength: 32, outputType: 'binary' });
const k = await subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt']); wipe(raw); return k;
}
const base = await subtle.importKey('raw', pw, 'PBKDF2', false, ['deriveKey']);
return await subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: p.iter }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
} finally { wipe(pw); }
}
async function generateSigningKey() {
const k = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
return { publicKey: new Uint8Array(await subtle.exportKey('raw', k.publicKey)), privateJwk: await subtle.exportKey('jwk', k.privateKey) };
}
async function fingerprint(pub) { const h = new Uint8Array(await subtle.digest('SHA-256', pub)); return hex(h.slice(0, 8)).replace(/(....)(?=.)/g, '$1-').toUpperCase(); }
/* Random passphrase: 7 groups of 4 from a 32-symbol alphabet = 140 bits of entropy
(32 symbols = exactly 5 bits each, so no modulo bias). */
const ALPHA = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
function generatePassphrase() { const out = [], r = rnd(28); for (let g = 0; g < 7; g++) { let s = ''; for (let i = 0; i < 4; i++) s += ALPHA[r[g * 4 + i] & 31]; out.push(s); } wipe(r); return out.join('-'); }
/* Strength estimate, in bits. An attacker who photographs a code can guess offline,
so this is the number that matters. Heuristic, deliberately on the cautious side. */
const COMMON = ['password', 'passw0rd', 'qwerty', 'letmein', 'welcome', 'admin', 'iloveyou', 'monkey', 'dragon', 'football', 'baseball', 'shalom', 'israel', 'master', 'login', 'abc123', 'prism', 'secret', 'hello', 'test', 'summer', 'winter', 'sunshine', 'princess', 'trustno1', 'whatever', 'google', 'avi', '1234', 'asdf', 'zxcv', 'love', 'god', 'cohen', 'levi'];
function strength(pw) {
const warnings = []; if (!pw) return { bits: 0, label: 'none', level: 0, warnings: ['Enter a password'] };
const body = pw.replace(/-/g, '');
{ const gs = pw.split('-'); if (gs.length >= 6 && /^[A-HJ-NP-Z2-9-]+$/.test(pw) && body.length >= 24 && new Set(gs).size === gs.length && new Set(body).size >= 12) return { bits: Math.floor(body.length * 5), label: 'excellent (random)', level: 4, warnings: [] }; }
let pool = 0; if (/[a-z]/.test(pw)) pool += 26; if (/[A-Z]/.test(pw)) pool += 26; if (/[0-9]/.test(pw)) pool += 10; if (/[^A-Za-z0-9]/.test(pw)) pool += 33;
const uniq = new Set(pw).size; let bits = Math.min(pw.length, uniq * 2) * Math.log2(Math.max(pool, 2));
const low = pw.toLowerCase();
if (/^[a-z ]+$/i.test(pw)) { const w = pw.trim().split(/\s+/).filter(x => x.length > 2).length; bits = Math.min(bits, w > 1 ? w * 12 : pw.length * 2.5); if (w <= 1) warnings.push('A single word is easy to guess'); }
if (/(.)\1\1/.test(pw)) { bits *= 0.7; warnings.push('Repeated characters'); }
if (/(012|123|234|345|456|567|678|789|abc|bcd|cde|def|qwe|wer|asd|sdf|zxc)/i.test(pw)) { bits *= 0.7; warnings.push('Keyboard or number sequence'); }
if (/^[a-z]+$/i.test(pw) || /^[0-9]+$/.test(pw)) { bits *= 0.8; warnings.push('Only one kind of character'); }
if (/(19|20)\d\d\b/.test(pw)) { bits -= 8; warnings.push('Contains a year'); }
for (const w of COMMON) if (low.includes(w)) { bits = Math.min(bits, 28) - (low === w ? 8 : 0); warnings.push('Contains a common word or pattern'); break; }
if (pw.length < 12) warnings.push('Shorter than 12 characters');
bits = Math.max(0, Math.floor(bits));
const level = bits < 40 ? 0 : bits < 60 ? 1 : bits < 80 ? 2 : bits < 100 ? 3 : 4;
if (bits < 80) warnings.push('Someone with a photo of the code can guess offline. Use Random for a code that matters.');
return { bits, level, label: ['weak', 'weak', 'fair', 'good', 'strong'][level], warnings: [...new Set(warnings)] };
}
/* options: { password, signWith: {publicKey, privateJwk}, kdf: 'argon2id' | 'pbkdf2' } */
async function seal(bytes, { password, signWith, kdf } = {}) {
bytes = Uint8Array.from(bytes);
if (!password && !signWith) throw Error('Give a password, a signing key, or both');
const flags = (password ? F_ENC : 0) | (signWith ? F_SIG : 0), M = Uint8Array.from([...MAGIC, 2]);
let body;
if (password) {
const useA = kdf ? kdf === 'argon2id' : hasArgon2();
if (useA && !hasArgon2()) throw Error('Argon2id is not loaded');
const salt = rnd(16), iv = rnd(12);
const params = useA ? cat(be32(A2.mem), Uint8Array.of(A2.t, A2.p)) : cat(be32(PBKDF2_ITER), Uint8Array.of(0, 0));
const head = cat(M, Uint8Array.of(flags), Uint8Array.of(useA ? 2 : 1), params, salt, iv);
const key = await deriveKey(password, salt, useA ? 2 : 1, useA ? A2 : { iter: PBKDF2_ITER });
const ct = new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: head }, key, bytes));
wipe(bytes); body = cat(head, ct);
} else body = cat(M, Uint8Array.of(flags), bytes);
if (!signWith) return body;
const pk = signWith.privateKey || await subtle.importKey('jwk', signWith.privateJwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
const sig = new Uint8Array(await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, pk, body));
return cat(body, signWith.publicKey, sig);
}
const isSecure = b => b.length >= 5 && MAGIC.every((m, i) => b[i] === m) && (b[3] === 1 || b[3] === 2) && b.length >= 6 && (b[4] & ~3) === 0;
function inspect(b) { if (!isSecure(b)) return { secure: false }; return { secure: true, version: b[3], encrypted: !!(b[4] & F_ENC), signed: !!(b[4] & F_SIG) }; }
/* Returns { secure, encrypted, signed, signatureValid, signerFingerprint, trusted, bytes, error, needsPassword }.
Plain payloads come back unchanged with secure:false. Wrong password, damage or
tampering give bytes:null plus an error. Caller should call PrismSecure.wipe(result.bytes) when done. */
async function open(bytes, { password, trustedFingerprints = [] } = {}) {
if (!isSecure(bytes)) return { secure: false, bytes };
const ver = bytes[3], flags = bytes[4], encrypted = !!(flags & F_ENC), signed = !!(flags & F_SIG);
let end = bytes.length; const out = { secure: true, version: ver, encrypted, signed, signatureValid: null };
if (signed) {
if (bytes.length < 5 + 65 + 64) throw Error('Code is damaged');
const pub = bytes.slice(end - 129, end - 64), sig = bytes.slice(end - 64), body = bytes.slice(0, end - 129);
try { const k = await subtle.importKey('raw', pub, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']); out.signatureValid = await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, k, sig, body); } catch (e) { out.signatureValid = false; }
out.signerPublicKey = pub; out.signerFingerprint = await fingerprint(pub);
out.trusted = out.signatureValid && inList(trustedFingerprints, out.signerFingerprint);
end -= 129;
if (!out.signatureValid) { out.bytes = null; out.error = 'Signature is not valid. This code was changed or forged.'; return out; }
}
if (!encrypted) { out.bytes = bytes.slice(5, end); return out; }
let head, salt, iv, kdf, p, hl;
if (ver === 1) { hl = HEAD1; if (end < hl + 16) throw Error('Code is damaged'); salt = bytes.slice(5, 21); iv = bytes.slice(21, 33); kdf = 1; p = { iter: rd32(bytes, 33) }; }
else { hl = HEAD2; if (end < hl + 16) throw Error('Code is damaged'); kdf = bytes[5]; salt = bytes.slice(12, 28); iv = bytes.slice(28, 40); p = kdf === 2 ? { mem: rd32(bytes, 6), t: bytes[10], p: bytes[11] } : { iter: rd32(bytes, 6) }; }
head = bytes.slice(0, hl);
if (kdf === 1 ? (p.iter < 100000 || p.iter > 5000000) : kdf === 2 ? (p.mem < 8192 || p.mem > MAX_MEM || p.t < 1 || p.t > MAX_T || p.p < 1 || p.p > 4) : true) throw Error('Code is damaged or unsupported');
if (!password) { out.bytes = null; out.needsPassword = true; return out; }
try {
const key = await deriveKey(password, salt, kdf, p);
out.bytes = new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv, additionalData: head }, key, bytes.slice(hl, end)));
} catch (e) { out.bytes = null; out.error = /Argon2id/.test(e.message) ? e.message : 'Wrong password, or the code was changed.'; }
return out;
}
const api = { seal, open, inspect, isSecure, generateSigningKey, fingerprint, generatePassphrase, strength, ctEqual, wipe, hasArgon2,
params: { argon2id: A2, pbkdf2Iterations: PBKDF2_ITER, passphraseBits: 140 },
overhead: { encrypted: HEAD2 + 16, signed: 129 } };
root.PrismSecure = api; if (typeof module !== 'undefined') module.exports = api;
})(typeof globalThis !== 'undefined' ? globalThis : this);
</script><script>
const $=id=>document.getElementById(id);let key=null,lastCode=null,lastPw='';
const esc=s=>s.replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]));
const badge=(t,c)=>`<span class="chip ${c}">${esc(t)}</span>`;
const trustedList=()=>{try{return JSON.parse(localStorage.getItem('prismSecureTrusted')||'[]')}catch(e){return[]}};
const idb=(mode,fn)=>new Promise((res,rej)=>{const q=indexedDB.open('comb-secure',1);q.onupgradeneeded=()=>q.result.createObjectStore('keys');q.onerror=()=>rej(q.error);q.onsuccess=()=>{const d=q.result,t=d.transaction('keys',mode),r=fn(t.objectStore('keys'));t.oncomplete=()=>{d.close();res(r.result)};t.onerror=()=>{d.close();rej(t.error)}}});
const sealOnly=jwk=>crypto.subtle.importKey('jwk',jwk,{name:'ECDSA',namedCurve:'P-256'},false,['sign']);
const saveKey=async k=>{await idb('readwrite',s=>s.put({pub:k.publicKey,priv:k.privateKey},'signing'));try{localStorage.removeItem('prismSecureKey')}catch(e){}};
window.clearSavedKey=async()=>{await idb('readwrite',s=>s.delete('signing'));try{localStorage.removeItem('prismSecureKey')}catch(e){}};
async function getKey(){if(key)return key;const rec=await idb('readonly',s=>s.get('signing')).catch(()=>null);if(rec&&rec.priv&&rec.pub){key={publicKey:rec.pub,privateKey:rec.priv};}else{const legacy=localStorage.getItem('prismSecureKey');if(legacy){const o=JSON.parse(legacy);key={publicKey:Uint8Array.from(o.pub),privateJwk:o.jwk,privateKey:await sealOnly(o.jwk)};await saveKey(key);}else{key=await PrismSecure.generateSigningKey();key.privateKey=await sealOnly(key.privateJwk);await saveKey(key);}}
$('fp').textContent=await PrismSecure.fingerprint(key.publicKey);return key;}
async function myTrusted(){return key?[await PrismSecure.fingerprint(key.publicKey),...trustedList()]:trustedList();}
function tab(m){$('paneMake').hidden=!m;$('paneOpen').hidden=m;$('tabMake').classList.toggle('on',m);$('tabOpen').classList.toggle('on',!m);}
$('tabMake').onclick=()=>tab(true);$('tabOpen').onclick=()=>tab(false);$('goopen').onclick=()=>{$('pw2').value=lastPw;tab(false);window.scrollTo(0,0)};
$('msg').addEventListener('input',()=>$('count').textContent=$('msg').value.length);$('count').textContent=$('msg').value.length;
function syncOpts(){$('optLock').classList.toggle('on',$('dolock').checked);$('optSign').classList.toggle('on',$('dosign').checked);$('pwbox').hidden=!$('dolock').checked;$('keybox').hidden=!$('dosign').checked;}
$('dolock').onchange=syncOpts;$('dosign').onchange=()=>{syncOpts();if($('dosign').checked)getKey()};syncOpts();
const COLS=['#D7263D','#F77F00','#F5C518','#2DB35A','#2DB35A'];
function meter(){const v=$('pw').value,s=PrismSecure.strength(v),bars=$('bars').children;
for(let i=0;i<4;i++)bars[i].style.background=v&&i<Math.max(1,s.level)?COLS[s.level]:'';
$('meter').innerHTML=v?`<span class="mtext" style="color:${s.level<2?'#9b1226':s.level==2?'#A65200':'#17663a'}">Password strength: ${s.label} (about ${s.bits} bits)</span>`+s.warnings.slice(0,2).map(w=>`<div class="mw">${esc(w)}</div>`).join(''):'';}
$('pw').addEventListener('input',meter);
$('genpw').onclick=()=>{$('pw').value=PrismSecure.generatePassphrase();$('pw2').value=$('pw').value;meter()};
$('cpw').onclick=async()=>{try{await navigator.clipboard.writeText(lastPw);$('cpw').textContent='Copied'}catch(e){$('cpw').textContent='Copy failed'}setTimeout(()=>$('cpw').textContent='Copy password',1500)};
$('make').onclick=async()=>{const btn=$('make');try{
const bytes=new TextEncoder().encode($('msg').value);if(!bytes.length)throw Error('Type something to put in the code');
const lock=$('dolock').checked,pw=lock?$('pw').value:'';if(lock&&!pw)throw Error('Enter a password, or tap Random. Or untick the lock.');if(lock&&pw.length<8)throw Error('Use at least 8 characters, or tap Random.');
if(!lock&&!$('dosign').checked)throw Error('Turn on the lock, the signature, or both.');
btn.disabled=true;btn.innerHTML='<span class="spin"></span>'+(lock?'Locking (a few seconds)':'Signing');await new Promise(r=>setTimeout(r,40));
const sign=$('dosign').checked?await getKey():undefined;
const env=await PrismSecure.seal(bytes,{password:pw||undefined,signWith:sign});
const code=Prism.encode(env,{ecc:1,mode:0,type:1});lastCode=code;lastPw=pw;
const c=$('code');Prism.render(code,8,c);c.hidden=false;$('resultbox').hidden=false;$('cpw').hidden=!pw;$('savewarn').hidden=!pw;
const mode=pw&&sign?'Locked and signed':pw?'Locked with password':'Signed';
$('info').innerHTML=badge(mode+(pw?(PrismSecure.hasArgon2()?' (AES-256, Argon2id)':' (AES-256, PBKDF2)'):''),'ok')+badge(env.length+' of '+code.capacity.payload+' bytes','info');
PrismSecure.wipe(bytes);
}catch(e){$('info').innerHTML=badge(e.message,'bad')}finally{btn.disabled=false;btn.textContent='Create secure code'}};
$('dlpng').onclick=()=>{const a=document.createElement('a');a.href=$('code').toDataURL('image/png');a.download='prism-secure-code.png';a.click()};
function verdict(c,ic,t,s){return `<div class="verdict ${c}"><div class="ic">${ic}</div><div><b>${esc(t)}</b><span>${s||''}</span></div></div>`}
const PrismRetry={};PrismRetry.crplain=function(img){const w=img.width,h=img.height,d=img.data;
const N=w*h,lum=new Float32Array(N),amp=new Float32Array(N);
for(let i=0,p=0;i<N;i++,p+=4){const r=d[p],g=d[p+1],b=d[p+2];lum[i]=(r+g+b)/3;amp[i]=Math.max(r,g,b)-Math.min(r,g,b);}
const R=Math.max(4,Math.round(Math.min(w,h)/12));
const tmp=new Float32Array(N),bl=new Float32Array(N);
for(let y=0;y<h;y++){let s=0;for(let x=0;x<w;x++){if(x+R<w)s+=amp[y*w+x+R];if(x-R-1>=0)s-=amp[y*w+x-R-1];bl[y*w+x]=s/(Math.min(w-1,x+R)-Math.max(0,x-R-1));}}
for(let x=0;x<w;x++){let s=0;for(let y=0;y<h;y++){if(y+R<h)s+=bl[(y+R)*w+x];if(y-R-1>=0)s-=bl[(y-R-1)*w+x];tmp[y*w+x]=s/(Math.min(h-1,y+R)-Math.max(0,y-R-1));}}
const o=new Uint8ClampedArray(d.length);
for(let i=0,p=0;i<N;i++,p+=4){let k=Math.min(6,Math.max(1,90/Math.max(18,tmp[i])));
const l=lum[i];if(l<190)k=1;let r=l+(d[p]-l)*k,g=l+(d[p+1]-l)*k,b=l+(d[p+2]-l)*k;
const m2=Math.max(r,g,b);if(m2>255){const s=255/m2;r*=s;g*=s;b*=s;}
o[p]=r;o[p+1]=g;o[p+2]=b;o[p+3]=255;}
return new ImageData(o,w,h);};
async function scanCanvas(c,pw,trusted){const id=c.getContext('2d').getImageData(0,0,c.width,c.height);let res;try{res=Prism.readImage(id)}catch(e0){let im2=null;try{im2=PrismRetry.crplain(id)}catch(x){}if(!im2)throw e0;try{res=Prism.readImage(im2)}catch(e1){throw e0}}return show(res.bytes,pw,trusted);}
async function show(bytes,pw,trusted){const o=await PrismSecure.open(bytes,{password:pw,trustedFingerprints:trusted||[]});let h='';
if(!o.secure)h=verdict('warn','!','Plain code, not secured','Anyone can read this one.')+'<div class="msgbox">'+esc(new TextDecoder().decode(o.bytes))+'</div>';
else{
if(!o.signed&&!o.encrypted)h+=verdict('warn','!','Not signed','Anyone could have made this one.');
if(o.signed){if(!o.signatureValid)h+=verdict('bad','✕','Signature invalid','This code was changed or forged. Do not trust it.');
else if(o.trusted)h+=verdict('ok','✓','Signature valid, signer trusted','Made by <span class="fp">'+o.signerFingerprint+'</span>, a key you trust.');
else h+=verdict('warn','?','Signature valid, signer not trusted yet','Unchanged, made by key <span class="fp">'+o.signerFingerprint+'</span>. Only trust it if you know this is their key.<div class="actions" style="justify-content:flex-start"><button class="btn small" id="trustbtn" data-fp="'+o.signerFingerprint+'">Trust this signer</button></div>');}
if(o.encrypted){if(o.bytes)h+=verdict('ok','🔓','Unlocked','');else if(o.needsPassword)h+=verdict('warn','🔒','Locked','Enter the password above.');else if(o.signatureValid!==false)h+=verdict('bad','✕','Could not unlock',esc(o.error||'Wrong password, or the code was changed.'));}
if(o.bytes)h+='<div class="msgbox">'+esc(new TextDecoder().decode(o.bytes))+'</div>';}
$('out').innerHTML=h;if(window.PrismIssuers)PrismIssuers.onBytes(bytes,$('out'));const tb=$('trustbtn');if(tb)tb.onclick=()=>{const l=trustedList();l.push(tb.dataset.fp);localStorage.setItem('prismSecureTrusted',JSON.stringify(l));tb.textContent='Trusted';tb.disabled=true};return o;}
$('scan').onclick=async()=>{try{if(!lastCode)throw Error('Create a code first');if(window.pcSetText)pcSetText($('picked'),'Using the code you just made.');else $('picked').textContent='Using the code you just made.';await scanCanvas($('code'),$('pw2').value||undefined,await myTrusted())}catch(e){$('out').innerHTML=verdict('bad','✕','Could not read',esc(e.message))}};
$('pick').onclick=()=>$('codefile').click();
$('codefile').onchange=async e=>{const f=e.target.files[0];if(!f)return;if(window.pcSetText)pcSetText($('picked'),f.name);else $('picked').textContent=f.name;try{const bm=await createImageBitmap(f),c=document.createElement('canvas');c.width=bm.width;c.height=bm.height;{const g=c.getContext('2d');g.fillStyle='#fff';g.fillRect(0,0,c.width,c.height);g.drawImage(bm,0,0)}await scanCanvas(c,$('pw2').value||undefined,await myTrusted())}catch(x){$('out').innerHTML=verdict('bad','✕','Could not read this image',esc(x.message))}};
$('pw2').addEventListener('change',()=>{if(lastCode&&$('picked').textContent.startsWith('Using'))$('scan').onclick()});
window.exportKeyText=async()=>{const k=await getKey();if(!k.privateJwk)throw Error('This key is stored on this device and cannot be exported. Export is offered right after a key is created or imported.');return JSON.stringify({type:'prism-secure-key',v:1,pub:[...k.publicKey],jwk:k.privateJwk,fingerprint:await PrismSecure.fingerprint(k.publicKey)})};
window.importKeyText=async t=>{const o=JSON.parse(t);if(o.type!=='prism-secure-key'||!o.jwk||!o.pub)throw Error('Not a Comb key file');const pub=Uint8Array.from(o.pub);
const probe=await PrismSecure.seal(new Uint8Array([1,2,3]),{signWith:{publicKey:pub,privateJwk:o.jwk}});const r=await PrismSecure.open(probe,{});if(!r.signatureValid||r.signerFingerprint!==await PrismSecure.fingerprint(pub))throw Error('Key file is damaged or does not match');
key={publicKey:pub,privateJwk:o.jwk,privateKey:await sealOnly(o.jwk)};await saveKey(key);$('fp').textContent=await PrismSecure.fingerprint(pub);return $('fp').textContent};
$('expkey').onclick=async()=>{let t;try{t=await exportKeyText()}catch(x){$('info').innerHTML=badge(x.message,'bad');return}const b=new Blob([t],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='prism-secure-key.json';a.click();};
$('impkey').onclick=()=>$('impfile').click();
$('impfile').onchange=async e=>{try{const fp=await importKeyText(await e.target.files[0].text());$('info').innerHTML=badge('Key imported: '+fp,'ok')}catch(x){$('info').innerHTML=badge(x.message,'bad')}};
/* self test used by headless runs */
window.selfTest=async function(){const L=[];const ok=(n,v)=>L.push((v?'PASS ':'FAIL ')+n);
try{
const msg='https://example.com/ticket/8812?token=abc';$('msg').value=msg;$('pw').value='W3F2-R2G5-HAV3';$('pw2').value='W3F2-R2G5-HAV3';
for(const [n,sg] of [['locked',false],['locked+signed',true]]){$('dolock').checked=true;$('dosign').checked=sg;if(sg)await getKey();await $('make').onclick();
const c=$('code'),o=await scanCanvas(c,'W3F2-R2G5-HAV3',await myTrusted());
ok(n+' round trip through Comb render+read',o.bytes&&new TextDecoder().decode(o.bytes)===msg&&(!sg||o.trusted));
const o2=await scanCanvas(c,undefined,[]);ok(n+' no password gives no text',!o2.bytes&&o2.needsPassword);
const o3=await scanCanvas(c,'wrong',[]);ok(n+' wrong password gives no text',!o3.bytes);}
$('dolock').checked=false;$('dosign').checked=true;await $('make').onclick();const o4=await scanCanvas($('code'),undefined,await myTrusted());ok('signed only',o4.trusted&&new TextDecoder().decode(o4.bytes)===msg);
const o4b=await scanCanvas($('code'),undefined,[]);ok('untrusted signer offers trust button',!o4b.trusted&&!!$('trustbtn'));
$('dolock').checked=false;$('dosign').checked=false;await $('make').onclick();ok('nothing selected is refused',$('info').innerText.includes('Turn on'));
const env=await PrismSecure.seal(new TextEncoder().encode(msg),{signWith:key});env[10]^=1;const fc=Prism.encode(env,{ecc:1,mode:0,type:1});const cv=document.createElement('canvas');Prism.render(fc,8,cv);
const o5=await scanCanvas(cv,undefined,[]);ok('tampered signed code rejected',o5.signatureValid===false&&!o5.bytes&&$('out').innerText.includes('invalid'));
ok('meter flags weak password',PrismSecure.strength('password').level===0&&PrismSecure.strength(PrismSecure.generatePassphrase()).level===4);$('pw').value='password';meter();ok('meter shows warning in page',$('meter').innerText.includes('weak'));
ok('argon2id active in page',PrismSecure.hasArgon2());ok('private key is not kept in localStorage',localStorage.getItem('prismSecureKey')===null&&!JSON.stringify(Object.assign({},localStorage)).includes('"d"'));
const fp0=await PrismSecure.fingerprint(key.publicKey),txt=await exportKeyText();localStorage.clear();await clearSavedKey();key=null;$('fp').textContent='none yet';const fp1=await importKeyText(txt);ok('key export then import restores same key',fp0===fp1);
$('dolock').checked=false;$('dosign').checked=true;await $('make').onclick();const o6=await scanCanvas($('code'),undefined,[fp0]);ok('imported key signs trusted code',o6.trusted);
let bad=false;try{const j=JSON.parse(txt);j.jwk.d=j.jwk.d.slice(0,-2)+'AA';await importKeyText(JSON.stringify(j))}catch(e){bad=true}ok('mismatched key file rejected',bad);
}catch(e){L.push('FAIL exception '+e.message)}
$('log').textContent=L.join('\n');return L;};
</script><script src="comb-issuers.js"></script><script src="comb-pwa.js"></script><style>.pcredit{text-align:center;padding:18px 16px 26px;font:400 14px/1.6 Poppins,system-ui,sans-serif;color:#585254}.pcredit a{color:#1b1b1b;font-weight:600;text-decoration:underline}@media print{.pcredit{display:none}}</style><div class="pcredit">Comb Code by <a href="https://getcombcode.github.io/">Avi Shor</a> · <a href="license.html">License</a></div><script>
(function(){var nav=document.querySelector('.tabs');if(!nav)return;
var p=document.createElement('i');p.className='segpill';p.setAttribute('aria-hidden','true');nav.insertBefore(p,nav.firstChild);
function mv(){var b=nav.querySelector('button.on');if(!b)return;p.style.width=b.offsetWidth+'px';p.style.height=b.offsetHeight+'px';p.style.transform='translate('+b.offsetLeft+'px,'+b.offsetTop+'px)';}
nav.classList.add('seg-on');p.style.transition='none';mv();requestAnimationFrame(function(){requestAnimationFrame(function(){p.style.transition='';});});
new MutationObserver(mv).observe(nav,{attributes:true,subtree:true,attributeFilter:['class']});
addEventListener('resize',mv);if(document.fonts&&document.fonts.ready)document.fonts.ready.then(mv);setTimeout(mv,250);})();
</script>
<script src="motion.js"></script></body></html>