Repository navigation
Expand file tree
/
Copy pathcodec.js
More file actions
611 lines (554 loc) ยท 23.9 KB
/
Copy pathcodec.js
File metadata and controls
611 lines (554 loc) ยท 23.9 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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
* TextMark codec โ text watermarking core.
* Two layers:
* 1) Invisible layer: variation-selector encoding (1 byte per invisible char),
* framed with MAGIC/VERSION/FLAGS/LEN/CRC32, optionally deflate-compressed,
* optionally AES-GCM encrypted, wrapped in Reed-Solomon(223+32) ECC.
* 2) AI-readable emoji layer: ๐ + one emoji per byte (public 256-emoji table),
* lightweight frame EMAGIC/ELEN/SUM8 designed so any LLM can decode by hand.
*
* UMD: browser (window.TextMarkCodec) and Node (module.exports).
*/
(function (global, factory) {
const api = factory();
if (typeof module !== 'undefined' && module.exports) module.exports = api;
global.TextMarkCodec = api;
})(typeof self !== 'undefined' ? self : globalThis, function () {
'use strict';
// ---------------------------------------------------------------- utils
const te = new TextEncoder();
const td = new TextDecoder('utf-8', { fatal: false });
function utf8(s) { return te.encode(s); }
function fromUtf8(b) { return td.decode(b); }
function concatBytes() {
let total = 0;
for (const a of arguments) total += a.length;
const out = new Uint8Array(total);
let off = 0;
for (const a of arguments) { out.set(a, off); off += a.length; }
return out;
}
function u32be(n) {
return new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
}
function readU32be(b, o) {
return ((b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
}
function randomBytes(n) {
const b = new Uint8Array(n);
crypto.getRandomValues(b);
return b;
}
// ---------------------------------------------------------------- CRC32 (IEEE)
const CRC_TABLE = (function () {
const t = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
t[i] = c >>> 0;
}
return t;
})();
function crc32(bytes) {
let c = 0xFFFFFFFF;
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ (c >>> 8);
return (c ^ 0xFFFFFFFF) >>> 0;
}
// ---------------------------------------------------------------- GF(2^8), poly 0x11D
const GF_EXP = new Uint8Array(512);
const GF_LOG = new Uint8Array(256);
(function initGF() {
let x = 1;
for (let i = 0; i < 255; i++) {
GF_EXP[i] = x;
GF_LOG[x] = i;
x <<= 1;
if (x & 0x100) x ^= 0x11D;
}
for (let i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255];
})();
function gfMul(a, b) { return (a === 0 || b === 0) ? 0 : GF_EXP[GF_LOG[a] + GF_LOG[b]]; }
function gfDiv(a, b) {
if (b === 0) throw new Error('GF division by zero');
if (a === 0) return 0;
return GF_EXP[(GF_LOG[a] + 255 - GF_LOG[b]) % 255];
}
function gfPow2(n) { return GF_EXP[((n % 255) + 255) % 255]; } // 2^n in GF
// polynomials over GF, coefficients in ASCENDING power order: p[0] + p[1]x + ...
function polyAdd(a, b) {
const n = Math.max(a.length, b.length);
const out = new Array(n).fill(0);
for (let i = 0; i < n; i++) out[i] = (a[i] || 0) ^ (b[i] || 0);
return out;
}
function polyMul(a, b) {
const out = new Array(a.length + b.length - 1).fill(0);
for (let i = 0; i < a.length; i++)
for (let j = 0; j < b.length; j++)
out[i + j] ^= gfMul(a[i], b[j]);
return out;
}
function polyScale(p, s) { return p.map(c => gfMul(c, s)); }
function polyEvalAsc(p, x) { // ascending coeffs
let y = 0;
for (let i = p.length - 1; i >= 0; i--) y = gfMul(y, x) ^ p[i];
return y;
}
// ---------------------------------------------------------------- Reed-Solomon, nsym=32, FCR=0
const RS_NSYM = 32;
const RS_K = 223; // data bytes per block (block = 255)
// generator polynomial g(x) = prod_{i=0}^{nsym-1} (x - 2^i), ascending coeffs
const RS_GEN = (function () {
let g = [1];
for (let i = 0; i < RS_NSYM; i++) g = polyMul(g, [GF_EXP[i], 1]); // (2^i + x)
return g;
})();
function rsEncodeBlock(data) { // data: Uint8Array (<=223) -> Uint8Array (data+32)
const n = data.length, nsym = RS_NSYM;
const work = new Array(n + nsym).fill(0);
for (let i = 0; i < n; i++) work[i] = data[i];
// synthetic division by generator (gen has degree nsym, leading coeff 1).
// work[] is in DESCENDING power order, so position i+j pairs with coeff of x^(nsym-j).
for (let i = 0; i < n; i++) {
const coef = work[i];
if (coef !== 0) {
for (let j = 0; j <= nsym; j++) work[i + j] ^= gfMul(RS_GEN[nsym - j], coef);
}
}
const out = new Uint8Array(n + nsym);
out.set(data, 0);
for (let j = 0; j < nsym; j++) out[n + j] = work[n + j];
return out;
}
function rsCalcSyndromes(block) { // block: Uint8Array (received, data+parity)
// S_i = r(2^i), i = 0..nsym-1 ; r treated as descending-power poly with r[0] first byte
const n = block.length;
const synd = new Array(RS_NSYM);
for (let i = 0; i < RS_NSYM; i++) {
const x = GF_EXP[i];
let y = block[0];
for (let j = 1; j < n; j++) y = gfMul(y, x) ^ block[j];
synd[i] = y;
}
return synd;
}
function rsBerlekampMassey(synd) { // returns error locator Lambda, ascending coeffs
let C = [1], B = [1], L = 0, m = 1, b = 1;
for (let n = 0; n < synd.length; n++) {
let d = synd[n];
for (let i = 1; i <= Math.min(L, C.length - 1); i++) d ^= gfMul(C[i], synd[n - i]);
if (d === 0) { m++; continue; }
const T = C.slice();
const factor = gfDiv(d, b);
const shifted = new Array(m).fill(0).concat(polyScale(B, factor));
C = polyAdd(C, shifted);
if (2 * L <= n) { L = n + 1 - L; B = T; b = d; m = 1; } else { m++; }
}
// trim trailing zeros (high-degree)
while (C.length > 1 && C[C.length - 1] === 0) C.pop();
return { lambda: C, L };
}
function rsCorrectBlock(block) { // returns corrected Uint8Array or throws
const n = block.length;
const synd = rsCalcSyndromes(block);
if (Math.max.apply(null, synd) === 0) return block.slice(); // clean
const bm = rsBerlekampMassey(synd);
const lambda = bm.lambda, L = bm.L;
if (L === 0 || 2 * L > RS_NSYM) throw new Error('RS: uncorrectable (too many errors)');
// Chien search: error at byte position p iff Lambda(2^-(n-1-p)) == 0
const errPos = [];
for (let p = 0; p < n; p++) {
const xInv = gfPow2(-(n - 1 - p)); // 2^{-(n-1-p)}
if (polyEvalAsc(lambda, xInv) === 0) errPos.push(p);
}
if (errPos.length !== L) throw new Error('RS: uncorrectable (locator roots mismatch)');
// Omega(x) = (S(x) * Lambda(x)) mod x^nsym (ascending)
let omega = polyMul(synd, lambda);
omega = omega.slice(0, RS_NSYM);
// formal derivative Lambda'(x): coeff of x^i in Lambda contributes i*c*x^(i-1); in GF(2) only odd i survive
const lambdaPrime = [];
for (let i = 1; i < lambda.length; i += 2) lambdaPrime[i - 1] = lambda[i];
const out = block.slice();
for (const p of errPos) {
const Xl = gfPow2(n - 1 - p); // X_l = 2^{n-1-p}
const XlInv = gfDiv(1, Xl);
const num = gfMul(Xl, polyEvalAsc(omega, XlInv)); // FCR=0 -> factor X_l^{1-0}
const den = polyEvalAsc(lambdaPrime, XlInv);
if (den === 0) throw new Error('RS: uncorrectable (zero derivative)');
out[p] ^= gfDiv(num, den);
}
// verify
const synd2 = rsCalcSyndromes(out);
if (Math.max.apply(null, synd2) !== 0) throw new Error('RS: correction failed check');
return out;
}
function rsEncode(data) { // Uint8Array -> Uint8Array (with parity, blocked)
const nBlocks = Math.max(1, Math.ceil(data.length / RS_K));
const parts = [];
for (let i = 0; i < nBlocks; i++) {
parts.push(rsEncodeBlock(data.slice(i * RS_K, (i + 1) * RS_K)));
}
return concatBytes.apply(null, parts);
}
function rsEncodedLength(frameLen) {
const nBlocks = Math.max(1, Math.ceil(frameLen / RS_K));
return frameLen + nBlocks * RS_NSYM;
}
function rsDecode(data) { // inverse of rsEncode; throws on uncorrectable
if (data.length === 0) throw new Error('RS: bad length');
const parts = [];
let off = 0;
while (off < data.length) {
const remaining = data.length - off;
const blockLen = Math.min(remaining, RS_K + RS_NSYM); // last block may be short
if (blockLen <= RS_NSYM) throw new Error('RS: bad trailing block');
const corrected = rsCorrectBlock(data.slice(off, off + blockLen));
parts.push(corrected.slice(0, blockLen - RS_NSYM));
off += blockLen;
}
return concatBytes.apply(null, parts);
}
// ---------------------------------------------------------------- compression (deflate-raw)
async function deflate(bytes) {
const cs = new CompressionStream('deflate-raw');
const stream = new Blob([bytes]).stream().pipeThrough(cs);
return new Uint8Array(await new Response(stream).arrayBuffer());
}
async function inflate(bytes) {
const ds = new DecompressionStream('deflate-raw');
const stream = new Blob([bytes]).stream().pipeThrough(ds);
return new Uint8Array(await new Response(stream).arrayBuffer());
}
// ---------------------------------------------------------------- encryption (PBKDF2 + AES-GCM)
async function deriveKey(password, salt) {
const base = await crypto.subtle.importKey('raw', utf8(password), 'PBKDF2', false, ['deriveKey']);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
}
async function encryptPayload(password, payload) {
const salt = randomBytes(16), iv = randomBytes(12);
const key = await deriveKey(password, salt);
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, payload));
return { salt, iv, ct };
}
async function decryptPayload(password, salt, iv, ct) {
const key = await deriveKey(password, salt);
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ct); // throws on wrong password
return new Uint8Array(pt);
}
// ---------------------------------------------------------------- frame (invisible layer)
const MAGIC0 = 0x54, MAGIC1 = 0x4D; // 'TM'
const VERSION = 1;
const MAX_PAYLOAD = 16 * 1024 * 1024;
async function buildFrame(message, opts) {
opts = opts || {};
const password = opts.password || null;
let payload = utf8(message);
let flags = 0;
const compressed = await deflate(payload);
if (compressed.length < payload.length) { payload = compressed; flags |= 1; }
let extra = new Uint8Array(0);
if (password) {
const enc = await encryptPayload(password, payload);
extra = concatBytes(enc.salt, enc.iv);
payload = enc.ct;
flags |= 2;
}
const head = concatBytes(
new Uint8Array([MAGIC0, MAGIC1, VERSION, flags]), extra, u32be(payload.length));
const frame = concatBytes(head, payload);
const crc = u32be(crc32(frame));
return concatBytes(frame, crc);
}
function frameLengthFromHeader(bytes, off) {
// returns {frameLen, encrypted} or null if header invalid
if (bytes.length - off < 8) return null;
if (bytes[off] !== MAGIC0 || bytes[off + 1] !== MAGIC1) return null;
if (bytes[off + 2] !== VERSION) return null;
const flags = bytes[off + 3];
if (flags & ~3) return null;
const encrypted = (flags & 2) !== 0;
const lenOff = off + 4 + (encrypted ? 28 : 0);
if (bytes.length - lenOff < 4) return null;
const payloadLen = readU32be(bytes, lenOff);
if (payloadLen > MAX_PAYLOAD) return null;
const frameLen = (lenOff - off) + 4 + payloadLen + 4;
return { frameLen, encrypted, flags };
}
async function parseFrame(frame, opts) {
opts = opts || {};
const password = opts.password || null;
const h = frameLengthFromHeader(frame, 0);
if (!h) throw new Error('bad frame header');
if (frame.length !== h.frameLen) throw new Error('frame length mismatch');
const crcExpected = readU32be(frame, frame.length - 4);
const crcActual = crc32(frame.slice(0, frame.length - 4));
if (crcActual !== crcExpected) throw new Error('CRC32 mismatch');
const flags = frame[3];
const encrypted = (flags & 2) !== 0;
const compressed = (flags & 1) !== 0;
const lenOff = 4 + (encrypted ? 28 : 0);
const payloadLen = readU32be(frame, lenOff);
let payload = frame.slice(lenOff + 4, lenOff + 4 + payloadLen);
if (encrypted) {
if (!password) { const e = new Error('password required'); e.code = 'NEED_PASSWORD'; throw e; }
const salt = frame.slice(4, 20), iv = frame.slice(20, 32);
try {
payload = await decryptPayload(password, salt, iv, payload);
} catch (err) {
const e = new Error('wrong password'); e.code = 'BAD_PASSWORD'; throw e;
}
}
if (compressed) payload = await inflate(payload);
return { message: fromUtf8(payload), encrypted, compressed };
}
// ---------------------------------------------------------------- variation-selector layer
function byteToVS(b) {
return (b < 16) ? String.fromCodePoint(0xFE00 + b) : String.fromCodePoint(0xE0100 + (b - 16));
}
function vsToByte(cp) {
if (cp >= 0xFE00 && cp <= 0xFE0F) return cp - 0xFE00;
if (cp >= 0xE0100 && cp <= 0xE01EF) return cp - 0xE0100 + 16;
return -1;
}
function bytesToVSString(bytes) {
let s = '';
for (let i = 0; i < bytes.length; i++) s += byteToVS(bytes[i]);
return s;
}
// find maximal runs of VS chars; returns array of Uint8Array byte-runs
function findVSRuns(text) {
return scanVSRuns(Array.from(text)).map(r => r.bytes);
}
// same, but over a code-point array and keeping positions: [{ start, bytes }]
function scanVSRuns(cps) {
const runs = [];
let cur = [], start = 0;
for (let i = 0; i < cps.length; i++) {
const b = vsToByte(cps[i].codePointAt(0));
if (b >= 0) { if (!cur.length) start = i; cur.push(b); }
else if (cur.length) { runs.push({ start, bytes: new Uint8Array(cur) }); cur = []; }
}
if (cur.length) runs.push({ start, bytes: new Uint8Array(cur) });
return runs;
}
const MAX_REPLICAS = 20;
// Returns { text, replicas }.
// 'paragraphs' mode puts one full replica at the END of every paragraph (just
// before its newline), so any single paragraph copied on its own still carries
// a complete watermark. Blank lines are never touched, so '\n\n' boundaries and
// Markdown structure stay intact.
function embedInvisible(text, rsBytes, mode) {
const payload = bytesToVSString(rsBytes);
if (mode !== 'paragraphs' || text.length === 0) {
return { text: text + payload, replicas: 1 };
}
const points = [];
for (let i = 0; i < text.length; i++) {
if (text[i] === '\n' && (i === 0 || text[i - 1] !== '\n')) points.push(i); // first \n of a run
}
if (text[text.length - 1] !== '\n') points.push(text.length); // last paragraph
if (!points.length) return { text: text + payload, replicas: 1 };
let chosen = points;
if (points.length > MAX_REPLICAS) { // thin out evenly, always keeping first and last
const step = (points.length - 1) / (MAX_REPLICAS - 1);
chosen = [];
for (let i = 0; i < MAX_REPLICAS; i++) {
const p = points[Math.round(i * step)];
if (chosen[chosen.length - 1] !== p) chosen.push(p);
}
}
let out = '', prev = 0;
for (const pos of chosen) { out += text.slice(prev, pos) + payload; prev = pos; }
out += text.slice(prev);
return { text: out, replicas: chosen.length };
}
// Locate every plausible RS-encoded frame inside the variation-selector runs.
// Scans all offsets (not just the first few) so that stray leading VS chars,
// concatenated documents and back-to-back replicas are all found.
// Returns [{ start, end, data }] with start/end as code-point indices.
const MAX_CANDIDATES = 64;
function scanInvisibleFrames(cps) {
const frames = [];
for (const run of scanVSRuns(cps)) {
const bytes = run.bytes;
let off = 0;
while (off + 8 <= bytes.length && frames.length < MAX_CANDIDATES) {
const h = frameLengthFromHeader(bytes, off);
if (h) {
const total = rsEncodedLength(h.frameLen);
if (off + total <= bytes.length) {
frames.push({ start: run.start + off, end: run.start + off + total, data: bytes.slice(off, off + total) });
off += total;
continue;
}
}
off++;
}
}
return frames;
}
// returns array of candidate RS-encoded buffers located by MAGIC
function extractInvisibleCandidates(text) {
return scanInvisibleFrames(Array.from(text)).map(f => f.data);
}
// ---------------------------------------------------------------- emoji layer (AI-readable)
// byte b -> codepoint: 0..79 => U+1F600+b ; 80..207 => U+1F300+(b-80) ; 208..255 => U+1F380+(b-208)
const EMOJI_TABLE = '๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐ป๐ผ๐ฝ๐พ๐ฟ๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐ป๐ผ๐ฝ๐พ๐ฟ๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐ป๐ผ๐ฝ๐พ๐ฟ๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ';
const EMOJI_CHARS = Array.from(EMOJI_TABLE); // 256 single-codepoint emoji
const EMOJI_INDEX = new Map(EMOJI_CHARS.map((ch, i) => [ch, i]));
const EMOJI_MARKER = '๐'; // U+1F4DC, not in table
const EMAGIC0 = 0x54, EMAGIC1 = 0x65; // 'Te'
const EMOJI_MAX = 65535;
function sum8(bytes) { let s = 0; for (const b of bytes) s = (s + b) & 255; return s; }
function encodeEmojiLayer(message) {
const msg = utf8(message);
if (msg.length > EMOJI_MAX) {
const e = new Error('message too long for emoji layer');
e.code = 'EMOJI_TOO_LONG';
throw e;
}
const frame = concatBytes(new Uint8Array([EMAGIC0, EMAGIC1]), u32be(msg.length).slice(2), msg, new Uint8Array([sum8(msg)]));
let s = EMOJI_MARKER;
for (const b of frame) s += EMOJI_CHARS[b];
return s;
}
// Locate every valid emoji strip. Returns [{ start, end, message }] with
// start = index of the ๐ marker and end = index just past the checksum,
// both as code-point indices.
function scanEmojiFrames(cps) {
const frames = [];
for (let i = 0; i < cps.length; i++) {
if (cps[i] !== EMOJI_MARKER) continue;
const bytes = [];
let j = i + 1;
while (j < cps.length && EMOJI_INDEX.has(cps[j])) { bytes.push(EMOJI_INDEX.get(cps[j])); j++; }
if (bytes.length < 5) continue;
if (bytes[0] !== EMAGIC0 || bytes[1] !== EMAGIC1) continue;
const len = (bytes[2] << 8) | bytes[3];
if (bytes.length < 4 + len + 1) continue;
const msg = new Uint8Array(bytes.slice(4, 4 + len));
if (sum8(msg) !== bytes[4 + len]) continue;
const end = i + 1 + 4 + len + 1;
frames.push({ start: i, end, message: fromUtf8(msg) });
i = end - 1;
}
return frames;
}
function decodeEmojiLayer(text) {
return scanEmojiFrames(Array.from(text)).map(f => ({ message: f.message, layer: 'emoji' }));
}
// ---------------------------------------------------------------- high-level API
async function encode(text, message, opts) {
opts = opts || {};
const password = opts.password || null;
const mode = opts.mode || 'end';
// secrecy: encrypted watermarks never get a visible emoji layer
const emojiLayer = password ? false : (opts.emojiLayer !== false);
const frame = await buildFrame(message, { password });
const rsBytes = rsEncode(frame);
const inv = embedInvisible(text, rsBytes, mode);
let out = inv.text;
let emojiStr = '';
if (emojiLayer) {
emojiStr = encodeEmojiLayer(message);
out += (out.endsWith('\n') || out.length === 0 ? '' : '\n') + emojiStr;
}
return {
text: out,
stats: {
frameBytes: frame.length,
invisibleCharsPerCopy: rsBytes.length,
invisibleCharsTotal: rsBytes.length * inv.replicas,
replicas: inv.replicas,
emojiChars: emojiStr ? Array.from(emojiStr).length : 0,
encrypted: !!password,
compressed: (frame[3] & 1) !== 0,
emojiLayer
}
};
}
async function decode(text, opts) {
opts = opts || {};
const password = opts.password || null;
const errors = [];
const seenErrors = new Set();
let needsPassword = false;
// one result per (layer, message); repeated replicas only bump `copies`
const byKey = new Map();
const order = [];
function add(layer, res) {
const key = layer + '\u0000' + res.message;
const prev = byKey.get(key);
if (prev) { prev.copies++; return; }
const entry = Object.assign({ layer: layer, copies: 1 }, res);
byKey.set(key, entry);
order.push(entry);
}
function addError(layer, error) {
const key = layer + ': ' + error;
if (seenErrors.has(key)) return;
seenErrors.add(key);
errors.push({ layer, error });
}
for (const cand of extractInvisibleCandidates(text)) {
let frame;
try {
frame = rsDecode(cand);
} catch (e) {
addError('invisible', 'corrupted: ' + e.message);
continue;
}
try {
const r = await parseFrame(frame, { password });
add('invisible', r);
} catch (e) {
if (e.code === 'NEED_PASSWORD') needsPassword = true;
else if (e.code === 'BAD_PASSWORD') addError('invisible', 'wrong password');
else addError('invisible', e.message);
}
}
for (const r of decodeEmojiLayer(text)) add('emoji', { message: r.message });
return { found: order.length > 0, results: order, errors, needsPassword };
}
// Remove every TextMark watermark from `text`, leaving the rest byte-identical โ
// legitimate variation selectors (e.g. the VS16 in โค๏ธ) and plain emoji survive
// because only bytes belonging to a fully validated frame are dropped.
function strip(text) {
const cps = Array.from(text);
const drop = new Uint8Array(cps.length);
const invFrames = scanInvisibleFrames(cps);
const emoFrames = scanEmojiFrames(cps);
for (const f of invFrames) for (let i = f.start; i < f.end; i++) drop[i] = 1;
for (const f of emoFrames) {
for (let i = f.start; i < f.end; i++) drop[i] = 1;
// a strip appended by encode() is preceded by a newline we also inserted:
// remove it when nothing but whitespace follows the strip
let onlyWs = true;
for (let i = f.end; i < cps.length; i++) if (!/\s/.test(cps[i])) { onlyWs = false; break; }
if (onlyWs && f.start > 0 && cps[f.start - 1] === '\n') drop[f.start - 1] = 1;
}
let out = '';
for (let i = 0; i < cps.length; i++) if (!drop[i]) out += cps[i];
return {
text: out,
removed: {
invisible: invFrames.length,
invisibleChars: invFrames.reduce((s, f) => s + (f.end - f.start), 0),
emoji: emoFrames.length,
emojiChars: emoFrames.reduce((s, f) => s + (f.end - f.start), 0)
}
};
}
return {
encode, decode, strip,
// exposed for tests / spec
crc32, rsEncode, rsDecode, rsEncodeBlock, rsCorrectBlock, RS_NSYM, RS_K,
buildFrame, parseFrame,
bytesToVSString, findVSRuns, embedInvisible, extractInvisibleCandidates,
scanInvisibleFrames, scanEmojiFrames, vsToByte, byteToVS,
encodeEmojiLayer, decodeEmojiLayer, EMOJI_TABLE, EMOJI_CHARS, EMOJI_MARKER, EMOJI_MAX,
MAX_REPLICAS, deflate, inflate, utf8, fromUtf8
};
});