qr-payload-parser 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +104 -98
  3. package/index.d.ts +120 -120
  4. package/index.js +479 -479
  5. package/package.json +5 -4
package/index.js CHANGED
@@ -1,479 +1,479 @@
1
- /* @ts-self-types="./index.d.ts" */
2
- /**
3
- * sunasty-qr-payload
4
- *
5
- * Pure structured QR payload parser (WIFI:, otpauth://totp/, BEGIN:VCARD,
6
- * mailto:, MATMSG:, tel:, smsto:, sms:, URL security analyzer), RFC 6238
7
- * TOTP 6-digit HMAC-SHA1 generator via Web Crypto SubtleCrypto, and
8
- * RFC 4180 CSV / JSON scan history serializers.
9
- *
10
- * Zero runtime dependencies. Compatible with Node.js (>= 18), Web Workers, and browsers.
11
- */
12
-
13
- export const SCAN_ACCEPTED_MIME = [
14
- 'image/jpeg',
15
- 'image/png',
16
- 'image/webp',
17
- 'image/gif',
18
- 'image/bmp',
19
- 'image/svg+xml',
20
- ];
21
-
22
- export const SCAN_MAX_BYTES = 20 * 1024 * 1024;
23
-
24
- /**
25
- * Returns true if the given MIME string is accepted for image scanning.
26
- * @param {string} mime
27
- * @returns {boolean}
28
- */
29
- export function isAcceptedScanMime(mime) {
30
- return SCAN_ACCEPTED_MIME.includes(mime);
31
- }
32
-
33
- /**
34
- * Returns true if the string starts with http:// or https://.
35
- * @param {string} data
36
- * @returns {boolean}
37
- */
38
- export function looksLikeUrl(data) {
39
- return /^https?:\/\//i.test(String(data ?? '').trim());
40
- }
41
-
42
- /**
43
- * Analyzes an HTTP/HTTPS URL for security preview before navigation.
44
- * Extracts domain, protocol, whether it uses unencrypted HTTP, or a raw IPv4/IPv6 host.
45
- *
46
- * @param {string} rawUrl
47
- */
48
- export function analyzeUrlSecurity(rawUrl) {
49
- const trimmed = String(rawUrl ?? '').trim();
50
- try {
51
- const parsed = new URL(trimmed);
52
- const protocol = parsed.protocol.toLowerCase();
53
- const hostname = parsed.hostname;
54
- const isInsecureHttp = protocol === 'http:';
55
- const isRawIp =
56
- /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) ||
57
- hostname.startsWith('[') ||
58
- /^[0-9a-f:]+$/i.test(hostname);
59
- const pathAndQuery =
60
- parsed.pathname === '/' && !parsed.search && !parsed.hash
61
- ? ''
62
- : `${parsed.pathname}${parsed.search}${parsed.hash}`;
63
- return {
64
- valid: true,
65
- href: parsed.href,
66
- protocol,
67
- domain: hostname,
68
- pathAndQuery,
69
- isInsecureHttp,
70
- isRawIp,
71
- hasSecurityWarning: isInsecureHttp || isRawIp,
72
- };
73
- } catch {
74
- return {
75
- valid: false,
76
- href: trimmed,
77
- protocol: '',
78
- domain: trimmed,
79
- pathAndQuery: '',
80
- isInsecureHttp: /^http:\/\//i.test(trimmed),
81
- isRawIp: false,
82
- hasSecurityWarning: true,
83
- };
84
- }
85
- }
86
-
87
- function unescapeWifiField(val) {
88
- return val.replace(/\\([\\;,:"])/g, '$1');
89
- }
90
-
91
- function matchWifiField(body, key) {
92
- const regex = new RegExp(`(?:^|;)${key}:((?:\\\\.|[^;])*)`, 'i');
93
- const match = regex.exec(body);
94
- return match && match[1] ? unescapeWifiField(match[1]) : '';
95
- }
96
-
97
- function matchVcardLine(raw, prop) {
98
- const regex = new RegExp(`^${prop}(?:;[^:]*)?:(.*)$`, 'im');
99
- const match = regex.exec(raw);
100
- return match && match[1] ? match[1].trim() : '';
101
- }
102
-
103
- /**
104
- * Parses raw QR code text into a discriminated union payload:
105
- * wifi | vcard | email | sms | phone | totp | url | text
106
- *
107
- * @param {string} data
108
- */
109
- export function parseQrPayload(data) {
110
- const raw = String(data ?? '');
111
- const trimmed = raw.trim();
112
-
113
- // 1. Wi-Fi: WIFI:S:MySSID;T:WPA;P:secret;H:true;;
114
- if (/^WIFI:/i.test(trimmed)) {
115
- const body = trimmed.slice(5);
116
- const ssid = matchWifiField(body, 'S');
117
- const encryption = matchWifiField(body, 'T') || 'nopass';
118
- const password = matchWifiField(body, 'P');
119
- const hiddenRaw = matchWifiField(body, 'H');
120
- const hidden = /^true$/i.test(hiddenRaw);
121
- return {
122
- kind: 'wifi',
123
- ssid,
124
- encryption,
125
- password,
126
- hidden,
127
- };
128
- }
129
-
130
- // 2. vCard: BEGIN:VCARD ... END:VCARD
131
- if (/^BEGIN:VCARD/i.test(trimmed)) {
132
- const fullName = matchVcardLine(trimmed, 'FN') || matchVcardLine(trimmed, 'N');
133
- const phone = matchVcardLine(trimmed, 'TEL');
134
- const email = matchVcardLine(trimmed, 'EMAIL');
135
- const org = matchVcardLine(trimmed, 'ORG');
136
- return {
137
- kind: 'vcard',
138
- fullName,
139
- phone,
140
- email,
141
- org,
142
- rawVcard: trimmed,
143
- };
144
- }
145
-
146
- // 3a. MATMSG:TO:user@example.com;SUB:Hi;BODY:Hello;;
147
- if (/^MATMSG:/i.test(trimmed)) {
148
- const body = trimmed.slice(7);
149
- const to = matchWifiField(body, 'TO');
150
- const subject = matchWifiField(body, 'SUB');
151
- const msgBody = matchWifiField(body, 'BODY');
152
- const params = [];
153
- if (subject) params.push(`subject=${encodeURIComponent(subject)}`);
154
- if (msgBody) params.push(`body=${encodeURIComponent(msgBody)}`);
155
- const query = params.length > 0 ? `?${params.join('&')}` : '';
156
- return {
157
- kind: 'email',
158
- to,
159
- subject,
160
- body: msgBody,
161
- mailtoHref: `mailto:${to}${query}`,
162
- };
163
- }
164
-
165
- // 3b. mailto:user@example.com?subject=Hi&body=Hello
166
- if (/^mailto:/i.test(trimmed)) {
167
- const withoutScheme = trimmed.slice(7);
168
- const qIndex = withoutScheme.indexOf('?');
169
- const to =
170
- qIndex >= 0
171
- ? decodeURIComponent(withoutScheme.slice(0, qIndex))
172
- : decodeURIComponent(withoutScheme);
173
- const queryStr = qIndex >= 0 ? withoutScheme.slice(qIndex + 1) : '';
174
- const searchParams = new URLSearchParams(queryStr);
175
- const subject = searchParams.get('subject') ?? '';
176
- const msgBody = searchParams.get('body') ?? '';
177
- return {
178
- kind: 'email',
179
- to,
180
- subject,
181
- body: msgBody,
182
- mailtoHref: trimmed,
183
- };
184
- }
185
-
186
- // 4. SMS: smsto:123456:Hello or sms:123456?body=Hello
187
- if (/^smsto:/i.test(trimmed)) {
188
- const rest = trimmed.slice(6);
189
- const colonIdx = rest.indexOf(':');
190
- const number = colonIdx >= 0 ? rest.slice(0, colonIdx).trim() : rest.trim();
191
- const message = colonIdx >= 0 ? rest.slice(colonIdx + 1).trim() : '';
192
- const smsHref = message
193
- ? `sms:${number}?body=${encodeURIComponent(message)}`
194
- : `sms:${number}`;
195
- return {
196
- kind: 'sms',
197
- number,
198
- message,
199
- smsHref,
200
- };
201
- }
202
-
203
- if (/^sms:/i.test(trimmed)) {
204
- const rest = trimmed.slice(4);
205
- const qIdx = rest.indexOf('?');
206
- const number = qIdx >= 0 ? rest.slice(0, qIdx).trim() : rest.trim();
207
- const queryStr = qIdx >= 0 ? rest.slice(qIdx + 1) : '';
208
- const searchParams = new URLSearchParams(queryStr);
209
- const message = searchParams.get('body') ?? '';
210
- return {
211
- kind: 'sms',
212
- number,
213
- message,
214
- smsHref: trimmed,
215
- };
216
- }
217
-
218
- // 5. Phone: tel:+123456789
219
- if (/^tel:/i.test(trimmed)) {
220
- const number = trimmed.slice(4).trim();
221
- return {
222
- kind: 'phone',
223
- number,
224
- telHref: `tel:${number}`,
225
- };
226
- }
227
-
228
- // 6. TOTP: otpauth://totp/Issuer:Account?secret=XYZ&issuer=Issuer
229
- if (/^otpauth:\/\//i.test(trimmed)) {
230
- const withoutScheme = trimmed.replace(/^otpauth:\/\/[^/]+\/?/i, '');
231
- const qIdx = withoutScheme.indexOf('?');
232
- const rawLabel = qIdx >= 0 ? withoutScheme.slice(0, qIdx) : withoutScheme;
233
- let label = rawLabel;
234
- try {
235
- label = decodeURIComponent(rawLabel);
236
- } catch {
237
- label = rawLabel;
238
- }
239
- const queryStr = qIdx >= 0 ? withoutScheme.slice(qIdx + 1) : '';
240
- const searchParams = new URLSearchParams(queryStr);
241
- const secret = (searchParams.get('secret') ?? '').replace(/\s+/g, '').toUpperCase();
242
- let issuer = searchParams.get('issuer') ?? '';
243
- let account = label;
244
- if (label.includes(':')) {
245
- const [labelIssuer, ...restAccount] = label.split(':');
246
- if (!issuer) issuer = labelIssuer.trim();
247
- account = restAccount.join(':').trim();
248
- }
249
- const digits = Number.parseInt(searchParams.get('digits') ?? '6', 10) || 6;
250
- const period = Number.parseInt(searchParams.get('period') ?? '30', 10) || 30;
251
- return {
252
- kind: 'totp',
253
- label,
254
- account,
255
- issuer,
256
- secret,
257
- digits,
258
- period,
259
- };
260
- }
261
-
262
- // 7. URL or plain text
263
- if (looksLikeUrl(trimmed)) {
264
- const security = analyzeUrlSecurity(trimmed);
265
- return {
266
- kind: 'url',
267
- text: trimmed,
268
- ...security,
269
- };
270
- }
271
-
272
- return { kind: 'text', text: raw };
273
- }
274
-
275
- /**
276
- * Decodes an RFC 4648 Base32 secret string into a Uint8Array.
277
- *
278
- * @param {string} base32
279
- * @returns {Uint8Array}
280
- */
281
- export function decodeBase32(base32) {
282
- const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
283
- const cleaned = String(base32 ?? '')
284
- .toUpperCase()
285
- .replace(/[\s=-]+/g, '');
286
- if (!cleaned) return new Uint8Array(0);
287
-
288
- let bits = 0;
289
- let value = 0;
290
- const bytes = [];
291
-
292
- for (let i = 0; i < cleaned.length; i++) {
293
- const idx = alphabet.indexOf(cleaned[i]);
294
- if (idx === -1) {
295
- throw new Error(`Invalid Base32 character: ${cleaned[i]}`);
296
- }
297
- value = (value << 5) | idx;
298
- bits += 5;
299
- if (bits >= 8) {
300
- bytes.push((value >>> (bits - 8)) & 0xff);
301
- bits -= 8;
302
- }
303
- }
304
-
305
- return new Uint8Array(bytes);
306
- }
307
-
308
- /**
309
- * Computes a live 6-digit (or N-digit) TOTP code using Web Crypto API HMAC-SHA1 (RFC 6238).
310
- *
311
- * @param {string} secretBase32 - Base32-encoded TOTP secret key
312
- * @param {number} [timestampMs] - Current timestamp in milliseconds (defaults to Date.now())
313
- * @param {number} [period=30] - Time step in seconds (default 30)
314
- * @param {number} [digits=6] - Number of digits (default 6)
315
- * @returns {Promise<{ code: string; remainingSeconds: number; period: number; counter: number }>}
316
- */
317
- export async function generateTotpCode(
318
- secretBase32,
319
- timestampMs = Date.now(),
320
- period = 30,
321
- digits = 6
322
- ) {
323
- const keyBytes = decodeBase32(secretBase32);
324
- if (keyBytes.length === 0) {
325
- throw new Error('Empty TOTP secret');
326
- }
327
-
328
- const epochSeconds = Math.floor(timestampMs / 1000);
329
- const counter = Math.floor(epochSeconds / period);
330
- const remainingSeconds = period - (epochSeconds % period);
331
-
332
- const counterBytes = new Uint8Array(8);
333
- let temp = counter;
334
- for (let i = 7; i >= 0; i--) {
335
- counterBytes[i] = temp & 0xff;
336
- temp = Math.floor(temp / 256);
337
- }
338
-
339
- const subtle = globalThis.crypto?.subtle;
340
- if (!subtle) {
341
- throw new Error('Web Crypto API subtle is not available');
342
- }
343
-
344
- const cryptoKey = await subtle.importKey(
345
- 'raw',
346
- keyBytes,
347
- { name: 'HMAC', hash: { name: 'SHA-1' } },
348
- false,
349
- ['sign']
350
- );
351
-
352
- const signature = await subtle.sign('HMAC', cryptoKey, counterBytes);
353
- const hmac = new Uint8Array(signature);
354
- const offset = hmac[hmac.length - 1] & 0x0f;
355
- const binary =
356
- ((hmac[offset] & 0x7f) << 24) |
357
- ((hmac[offset + 1] & 0xff) << 16) |
358
- ((hmac[offset + 2] & 0xff) << 8) |
359
- (hmac[offset + 3] & 0xff);
360
-
361
- const modulo = 10 ** digits;
362
- const code = String(binary % modulo).padStart(digits, '0');
363
-
364
- return {
365
- code,
366
- remainingSeconds,
367
- period,
368
- counter,
369
- };
370
- }
371
-
372
- /**
373
- * Applies a high-contrast grayscale luminance threshold (and optional inversion)
374
- * to RGBA pixel data. Returns a new Uint8ClampedArray.
375
- *
376
- * @param {Uint8ClampedArray} data
377
- * @param {number} [threshold=128]
378
- * @param {boolean} [invert=false]
379
- * @returns {Uint8ClampedArray}
380
- */
381
- export function applyHighContrastThreshold(data, threshold = 128, invert = false) {
382
- const out = new Uint8ClampedArray(data.length);
383
- for (let i = 0; i + 3 < data.length; i += 4) {
384
- const r = data[i];
385
- const g = data[i + 1];
386
- const b = data[i + 2];
387
- const a = data[i + 3];
388
- const lum = a < 128 ? 255 : 0.299 * r + 0.587 * g + 0.114 * b;
389
- let bw = lum >= threshold ? 255 : 0;
390
- if (invert) bw = 255 - bw;
391
- out[i] = bw;
392
- out[i + 1] = bw;
393
- out[i + 2] = bw;
394
- out[i + 3] = 255;
395
- }
396
- return out;
397
- }
398
-
399
- /**
400
- * Normalizes low-contrast RGBA buffers by stretching luminance between min and max
401
- * and applying a binary threshold at the midpoint.
402
- *
403
- * @param {Uint8ClampedArray} data
404
- * @returns {Uint8ClampedArray}
405
- */
406
- export function normalizeAndBinarizeLowContrast(data) {
407
- const out = new Uint8ClampedArray(data.length);
408
- let minLum = 255;
409
- let maxLum = 0;
410
-
411
- for (let i = 0; i + 3 < data.length; i += 4) {
412
- const a = data[i + 3];
413
- const lum = a < 128 ? 255 : 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
414
- if (lum < minLum) minLum = lum;
415
- if (lum > maxLum) maxLum = lum;
416
- }
417
-
418
- const mid = (minLum + maxLum) / 2;
419
- for (let i = 0; i + 3 < data.length; i += 4) {
420
- const a = data[i + 3];
421
- const lum = a < 128 ? 255 : 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
422
- const bw = lum >= mid ? 255 : 0;
423
- out[i] = bw;
424
- out[i + 1] = bw;
425
- out[i + 2] = bw;
426
- out[i + 3] = 255;
427
- }
428
- return out;
429
- }
430
-
431
- function escapeCsvCell(value) {
432
- const str = String(value ?? '');
433
- if (/[",\r\n]/.test(str)) {
434
- return `"${str.replace(/"/g, '""')}"`;
435
- }
436
- return str;
437
- }
438
-
439
- /**
440
- * Serializes an array of QR scan results to an RFC 4180 CSV string.
441
- *
442
- * @param {Array<{ timestamp?: string; source?: string; type?: string; isUrl?: boolean; data: string }>} results
443
- * @returns {string}
444
- */
445
- export function serializeScanHistoryToCsv(results) {
446
- const header = 'timestamp,source,type,isUrl,data';
447
- const rows = (results ?? []).map((r) => {
448
- const ts = escapeCsvCell(r.timestamp ?? '');
449
- const src = escapeCsvCell(r.source ?? 'file');
450
- const kind = escapeCsvCell(r.type ?? (r.isUrl ? 'url' : 'text'));
451
- const urlFlag = r.isUrl ? 'true' : 'false';
452
- const dataCell = escapeCsvCell(r.data ?? '');
453
- return `${ts},${src},${kind},${urlFlag},${dataCell}`;
454
- });
455
- return [header, ...rows].join('\n');
456
- }
457
-
458
- /**
459
- * Serializes an array of QR scan results to a formatted JSON string.
460
- *
461
- * @param {Array<Record<string, unknown>>} results
462
- * @returns {string}
463
- */
464
- export function serializeScanHistoryToJson(results) {
465
- return JSON.stringify(results ?? [], null, 2);
466
- }
467
-
468
- /**
469
- * Truncates decoded data for compact UI display.
470
- *
471
- * @param {string} data
472
- * @param {number} [maxLen=200]
473
- * @returns {string}
474
- */
475
- export function truncateForDisplay(data, maxLen = 200) {
476
- const str = String(data ?? '');
477
- if (str.length <= maxLen) return str;
478
- return str.slice(0, maxLen) + '…';
479
- }
1
+ /* @ts-self-types="./index.d.ts" */
2
+ /**
3
+ * sunasty-qr-payload
4
+ *
5
+ * Pure structured QR payload parser (WIFI:, otpauth://totp/, BEGIN:VCARD,
6
+ * mailto:, MATMSG:, tel:, smsto:, sms:, URL security analyzer), RFC 6238
7
+ * TOTP 6-digit HMAC-SHA1 generator via Web Crypto SubtleCrypto, and
8
+ * RFC 4180 CSV / JSON scan history serializers.
9
+ *
10
+ * Zero runtime dependencies. Compatible with Node.js (>= 18), Web Workers, and browsers.
11
+ */
12
+
13
+ export const SCAN_ACCEPTED_MIME = [
14
+ 'image/jpeg',
15
+ 'image/png',
16
+ 'image/webp',
17
+ 'image/gif',
18
+ 'image/bmp',
19
+ 'image/svg+xml',
20
+ ];
21
+
22
+ export const SCAN_MAX_BYTES = 20 * 1024 * 1024;
23
+
24
+ /**
25
+ * Returns true if the given MIME string is accepted for image scanning.
26
+ * @param {string} mime
27
+ * @returns {boolean}
28
+ */
29
+ export function isAcceptedScanMime(mime) {
30
+ return SCAN_ACCEPTED_MIME.includes(mime);
31
+ }
32
+
33
+ /**
34
+ * Returns true if the string starts with http:// or https://.
35
+ * @param {string} data
36
+ * @returns {boolean}
37
+ */
38
+ export function looksLikeUrl(data) {
39
+ return /^https?:\/\//i.test(String(data ?? '').trim());
40
+ }
41
+
42
+ /**
43
+ * Analyzes an HTTP/HTTPS URL for security preview before navigation.
44
+ * Extracts domain, protocol, whether it uses unencrypted HTTP, or a raw IPv4/IPv6 host.
45
+ *
46
+ * @param {string} rawUrl
47
+ */
48
+ export function analyzeUrlSecurity(rawUrl) {
49
+ const trimmed = String(rawUrl ?? '').trim();
50
+ try {
51
+ const parsed = new URL(trimmed);
52
+ const protocol = parsed.protocol.toLowerCase();
53
+ const hostname = parsed.hostname;
54
+ const isInsecureHttp = protocol === 'http:';
55
+ const isRawIp =
56
+ /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) ||
57
+ hostname.startsWith('[') ||
58
+ /^[0-9a-f:]+$/i.test(hostname);
59
+ const pathAndQuery =
60
+ parsed.pathname === '/' && !parsed.search && !parsed.hash
61
+ ? ''
62
+ : `${parsed.pathname}${parsed.search}${parsed.hash}`;
63
+ return {
64
+ valid: true,
65
+ href: parsed.href,
66
+ protocol,
67
+ domain: hostname,
68
+ pathAndQuery,
69
+ isInsecureHttp,
70
+ isRawIp,
71
+ hasSecurityWarning: isInsecureHttp || isRawIp,
72
+ };
73
+ } catch {
74
+ return {
75
+ valid: false,
76
+ href: trimmed,
77
+ protocol: '',
78
+ domain: trimmed,
79
+ pathAndQuery: '',
80
+ isInsecureHttp: /^http:\/\//i.test(trimmed),
81
+ isRawIp: false,
82
+ hasSecurityWarning: true,
83
+ };
84
+ }
85
+ }
86
+
87
+ function unescapeWifiField(val) {
88
+ return val.replace(/\\([\\;,:"])/g, '$1');
89
+ }
90
+
91
+ function matchWifiField(body, key) {
92
+ const regex = new RegExp(`(?:^|;)${key}:((?:\\\\.|[^;])*)`, 'i');
93
+ const match = regex.exec(body);
94
+ return match && match[1] ? unescapeWifiField(match[1]) : '';
95
+ }
96
+
97
+ function matchVcardLine(raw, prop) {
98
+ const regex = new RegExp(`^${prop}(?:;[^:]*)?:(.*)$`, 'im');
99
+ const match = regex.exec(raw);
100
+ return match && match[1] ? match[1].trim() : '';
101
+ }
102
+
103
+ /**
104
+ * Parses raw QR code text into a discriminated union payload:
105
+ * wifi | vcard | email | sms | phone | totp | url | text
106
+ *
107
+ * @param {string} data
108
+ */
109
+ export function parseQrPayload(data) {
110
+ const raw = String(data ?? '');
111
+ const trimmed = raw.trim();
112
+
113
+ // 1. Wi-Fi: WIFI:S:MySSID;T:WPA;P:secret;H:true;;
114
+ if (/^WIFI:/i.test(trimmed)) {
115
+ const body = trimmed.slice(5);
116
+ const ssid = matchWifiField(body, 'S');
117
+ const encryption = matchWifiField(body, 'T') || 'nopass';
118
+ const password = matchWifiField(body, 'P');
119
+ const hiddenRaw = matchWifiField(body, 'H');
120
+ const hidden = /^true$/i.test(hiddenRaw);
121
+ return {
122
+ kind: 'wifi',
123
+ ssid,
124
+ encryption,
125
+ password,
126
+ hidden,
127
+ };
128
+ }
129
+
130
+ // 2. vCard: BEGIN:VCARD ... END:VCARD
131
+ if (/^BEGIN:VCARD/i.test(trimmed)) {
132
+ const fullName = matchVcardLine(trimmed, 'FN') || matchVcardLine(trimmed, 'N');
133
+ const phone = matchVcardLine(trimmed, 'TEL');
134
+ const email = matchVcardLine(trimmed, 'EMAIL');
135
+ const org = matchVcardLine(trimmed, 'ORG');
136
+ return {
137
+ kind: 'vcard',
138
+ fullName,
139
+ phone,
140
+ email,
141
+ org,
142
+ rawVcard: trimmed,
143
+ };
144
+ }
145
+
146
+ // 3a. MATMSG:TO:user@example.com;SUB:Hi;BODY:Hello;;
147
+ if (/^MATMSG:/i.test(trimmed)) {
148
+ const body = trimmed.slice(7);
149
+ const to = matchWifiField(body, 'TO');
150
+ const subject = matchWifiField(body, 'SUB');
151
+ const msgBody = matchWifiField(body, 'BODY');
152
+ const params = [];
153
+ if (subject) params.push(`subject=${encodeURIComponent(subject)}`);
154
+ if (msgBody) params.push(`body=${encodeURIComponent(msgBody)}`);
155
+ const query = params.length > 0 ? `?${params.join('&')}` : '';
156
+ return {
157
+ kind: 'email',
158
+ to,
159
+ subject,
160
+ body: msgBody,
161
+ mailtoHref: `mailto:${to}${query}`,
162
+ };
163
+ }
164
+
165
+ // 3b. mailto:user@example.com?subject=Hi&body=Hello
166
+ if (/^mailto:/i.test(trimmed)) {
167
+ const withoutScheme = trimmed.slice(7);
168
+ const qIndex = withoutScheme.indexOf('?');
169
+ const to =
170
+ qIndex >= 0
171
+ ? decodeURIComponent(withoutScheme.slice(0, qIndex))
172
+ : decodeURIComponent(withoutScheme);
173
+ const queryStr = qIndex >= 0 ? withoutScheme.slice(qIndex + 1) : '';
174
+ const searchParams = new URLSearchParams(queryStr);
175
+ const subject = searchParams.get('subject') ?? '';
176
+ const msgBody = searchParams.get('body') ?? '';
177
+ return {
178
+ kind: 'email',
179
+ to,
180
+ subject,
181
+ body: msgBody,
182
+ mailtoHref: trimmed,
183
+ };
184
+ }
185
+
186
+ // 4. SMS: smsto:123456:Hello or sms:123456?body=Hello
187
+ if (/^smsto:/i.test(trimmed)) {
188
+ const rest = trimmed.slice(6);
189
+ const colonIdx = rest.indexOf(':');
190
+ const number = colonIdx >= 0 ? rest.slice(0, colonIdx).trim() : rest.trim();
191
+ const message = colonIdx >= 0 ? rest.slice(colonIdx + 1).trim() : '';
192
+ const smsHref = message
193
+ ? `sms:${number}?body=${encodeURIComponent(message)}`
194
+ : `sms:${number}`;
195
+ return {
196
+ kind: 'sms',
197
+ number,
198
+ message,
199
+ smsHref,
200
+ };
201
+ }
202
+
203
+ if (/^sms:/i.test(trimmed)) {
204
+ const rest = trimmed.slice(4);
205
+ const qIdx = rest.indexOf('?');
206
+ const number = qIdx >= 0 ? rest.slice(0, qIdx).trim() : rest.trim();
207
+ const queryStr = qIdx >= 0 ? rest.slice(qIdx + 1) : '';
208
+ const searchParams = new URLSearchParams(queryStr);
209
+ const message = searchParams.get('body') ?? '';
210
+ return {
211
+ kind: 'sms',
212
+ number,
213
+ message,
214
+ smsHref: trimmed,
215
+ };
216
+ }
217
+
218
+ // 5. Phone: tel:+123456789
219
+ if (/^tel:/i.test(trimmed)) {
220
+ const number = trimmed.slice(4).trim();
221
+ return {
222
+ kind: 'phone',
223
+ number,
224
+ telHref: `tel:${number}`,
225
+ };
226
+ }
227
+
228
+ // 6. TOTP: otpauth://totp/Issuer:Account?secret=XYZ&issuer=Issuer
229
+ if (/^otpauth:\/\//i.test(trimmed)) {
230
+ const withoutScheme = trimmed.replace(/^otpauth:\/\/[^/]+\/?/i, '');
231
+ const qIdx = withoutScheme.indexOf('?');
232
+ const rawLabel = qIdx >= 0 ? withoutScheme.slice(0, qIdx) : withoutScheme;
233
+ let label = rawLabel;
234
+ try {
235
+ label = decodeURIComponent(rawLabel);
236
+ } catch {
237
+ label = rawLabel;
238
+ }
239
+ const queryStr = qIdx >= 0 ? withoutScheme.slice(qIdx + 1) : '';
240
+ const searchParams = new URLSearchParams(queryStr);
241
+ const secret = (searchParams.get('secret') ?? '').replace(/\s+/g, '').toUpperCase();
242
+ let issuer = searchParams.get('issuer') ?? '';
243
+ let account = label;
244
+ if (label.includes(':')) {
245
+ const [labelIssuer, ...restAccount] = label.split(':');
246
+ if (!issuer) issuer = labelIssuer.trim();
247
+ account = restAccount.join(':').trim();
248
+ }
249
+ const digits = Number.parseInt(searchParams.get('digits') ?? '6', 10) || 6;
250
+ const period = Number.parseInt(searchParams.get('period') ?? '30', 10) || 30;
251
+ return {
252
+ kind: 'totp',
253
+ label,
254
+ account,
255
+ issuer,
256
+ secret,
257
+ digits,
258
+ period,
259
+ };
260
+ }
261
+
262
+ // 7. URL or plain text
263
+ if (looksLikeUrl(trimmed)) {
264
+ const security = analyzeUrlSecurity(trimmed);
265
+ return {
266
+ kind: 'url',
267
+ text: trimmed,
268
+ ...security,
269
+ };
270
+ }
271
+
272
+ return { kind: 'text', text: raw };
273
+ }
274
+
275
+ /**
276
+ * Decodes an RFC 4648 Base32 secret string into a Uint8Array.
277
+ *
278
+ * @param {string} base32
279
+ * @returns {Uint8Array}
280
+ */
281
+ export function decodeBase32(base32) {
282
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
283
+ const cleaned = String(base32 ?? '')
284
+ .toUpperCase()
285
+ .replace(/[\s=-]+/g, '');
286
+ if (!cleaned) return new Uint8Array(0);
287
+
288
+ let bits = 0;
289
+ let value = 0;
290
+ const bytes = [];
291
+
292
+ for (let i = 0; i < cleaned.length; i++) {
293
+ const idx = alphabet.indexOf(cleaned[i]);
294
+ if (idx === -1) {
295
+ throw new Error(`Invalid Base32 character: ${cleaned[i]}`);
296
+ }
297
+ value = (value << 5) | idx;
298
+ bits += 5;
299
+ if (bits >= 8) {
300
+ bytes.push((value >>> (bits - 8)) & 0xff);
301
+ bits -= 8;
302
+ }
303
+ }
304
+
305
+ return new Uint8Array(bytes);
306
+ }
307
+
308
+ /**
309
+ * Computes a live 6-digit (or N-digit) TOTP code using Web Crypto API HMAC-SHA1 (RFC 6238).
310
+ *
311
+ * @param {string} secretBase32 - Base32-encoded TOTP secret key
312
+ * @param {number} [timestampMs] - Current timestamp in milliseconds (defaults to Date.now())
313
+ * @param {number} [period=30] - Time step in seconds (default 30)
314
+ * @param {number} [digits=6] - Number of digits (default 6)
315
+ * @returns {Promise<{ code: string; remainingSeconds: number; period: number; counter: number }>}
316
+ */
317
+ export async function generateTotpCode(
318
+ secretBase32,
319
+ timestampMs = Date.now(),
320
+ period = 30,
321
+ digits = 6
322
+ ) {
323
+ const keyBytes = decodeBase32(secretBase32);
324
+ if (keyBytes.length === 0) {
325
+ throw new Error('Empty TOTP secret');
326
+ }
327
+
328
+ const epochSeconds = Math.floor(timestampMs / 1000);
329
+ const counter = Math.floor(epochSeconds / period);
330
+ const remainingSeconds = period - (epochSeconds % period);
331
+
332
+ const counterBytes = new Uint8Array(8);
333
+ let temp = counter;
334
+ for (let i = 7; i >= 0; i--) {
335
+ counterBytes[i] = temp & 0xff;
336
+ temp = Math.floor(temp / 256);
337
+ }
338
+
339
+ const subtle = globalThis.crypto?.subtle;
340
+ if (!subtle) {
341
+ throw new Error('Web Crypto API subtle is not available');
342
+ }
343
+
344
+ const cryptoKey = await subtle.importKey(
345
+ 'raw',
346
+ keyBytes,
347
+ { name: 'HMAC', hash: { name: 'SHA-1' } },
348
+ false,
349
+ ['sign']
350
+ );
351
+
352
+ const signature = await subtle.sign('HMAC', cryptoKey, counterBytes);
353
+ const hmac = new Uint8Array(signature);
354
+ const offset = hmac[hmac.length - 1] & 0x0f;
355
+ const binary =
356
+ ((hmac[offset] & 0x7f) << 24) |
357
+ ((hmac[offset + 1] & 0xff) << 16) |
358
+ ((hmac[offset + 2] & 0xff) << 8) |
359
+ (hmac[offset + 3] & 0xff);
360
+
361
+ const modulo = 10 ** digits;
362
+ const code = String(binary % modulo).padStart(digits, '0');
363
+
364
+ return {
365
+ code,
366
+ remainingSeconds,
367
+ period,
368
+ counter,
369
+ };
370
+ }
371
+
372
+ /**
373
+ * Applies a high-contrast grayscale luminance threshold (and optional inversion)
374
+ * to RGBA pixel data. Returns a new Uint8ClampedArray.
375
+ *
376
+ * @param {Uint8ClampedArray} data
377
+ * @param {number} [threshold=128]
378
+ * @param {boolean} [invert=false]
379
+ * @returns {Uint8ClampedArray}
380
+ */
381
+ export function applyHighContrastThreshold(data, threshold = 128, invert = false) {
382
+ const out = new Uint8ClampedArray(data.length);
383
+ for (let i = 0; i + 3 < data.length; i += 4) {
384
+ const r = data[i];
385
+ const g = data[i + 1];
386
+ const b = data[i + 2];
387
+ const a = data[i + 3];
388
+ const lum = a < 128 ? 255 : 0.299 * r + 0.587 * g + 0.114 * b;
389
+ let bw = lum >= threshold ? 255 : 0;
390
+ if (invert) bw = 255 - bw;
391
+ out[i] = bw;
392
+ out[i + 1] = bw;
393
+ out[i + 2] = bw;
394
+ out[i + 3] = 255;
395
+ }
396
+ return out;
397
+ }
398
+
399
+ /**
400
+ * Normalizes low-contrast RGBA buffers by stretching luminance between min and max
401
+ * and applying a binary threshold at the midpoint.
402
+ *
403
+ * @param {Uint8ClampedArray} data
404
+ * @returns {Uint8ClampedArray}
405
+ */
406
+ export function normalizeAndBinarizeLowContrast(data) {
407
+ const out = new Uint8ClampedArray(data.length);
408
+ let minLum = 255;
409
+ let maxLum = 0;
410
+
411
+ for (let i = 0; i + 3 < data.length; i += 4) {
412
+ const a = data[i + 3];
413
+ const lum = a < 128 ? 255 : 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
414
+ if (lum < minLum) minLum = lum;
415
+ if (lum > maxLum) maxLum = lum;
416
+ }
417
+
418
+ const mid = (minLum + maxLum) / 2;
419
+ for (let i = 0; i + 3 < data.length; i += 4) {
420
+ const a = data[i + 3];
421
+ const lum = a < 128 ? 255 : 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
422
+ const bw = lum >= mid ? 255 : 0;
423
+ out[i] = bw;
424
+ out[i + 1] = bw;
425
+ out[i + 2] = bw;
426
+ out[i + 3] = 255;
427
+ }
428
+ return out;
429
+ }
430
+
431
+ function escapeCsvCell(value) {
432
+ const str = String(value ?? '');
433
+ if (/[",\r\n]/.test(str)) {
434
+ return `"${str.replace(/"/g, '""')}"`;
435
+ }
436
+ return str;
437
+ }
438
+
439
+ /**
440
+ * Serializes an array of QR scan results to an RFC 4180 CSV string.
441
+ *
442
+ * @param {Array<{ timestamp?: string; source?: string; type?: string; isUrl?: boolean; data: string }>} results
443
+ * @returns {string}
444
+ */
445
+ export function serializeScanHistoryToCsv(results) {
446
+ const header = 'timestamp,source,type,isUrl,data';
447
+ const rows = (results ?? []).map((r) => {
448
+ const ts = escapeCsvCell(r.timestamp ?? '');
449
+ const src = escapeCsvCell(r.source ?? 'file');
450
+ const kind = escapeCsvCell(r.type ?? (r.isUrl ? 'url' : 'text'));
451
+ const urlFlag = r.isUrl ? 'true' : 'false';
452
+ const dataCell = escapeCsvCell(r.data ?? '');
453
+ return `${ts},${src},${kind},${urlFlag},${dataCell}`;
454
+ });
455
+ return [header, ...rows].join('\n');
456
+ }
457
+
458
+ /**
459
+ * Serializes an array of QR scan results to a formatted JSON string.
460
+ *
461
+ * @param {Array<Record<string, unknown>>} results
462
+ * @returns {string}
463
+ */
464
+ export function serializeScanHistoryToJson(results) {
465
+ return JSON.stringify(results ?? [], null, 2);
466
+ }
467
+
468
+ /**
469
+ * Truncates decoded data for compact UI display.
470
+ *
471
+ * @param {string} data
472
+ * @param {number} [maxLen=200]
473
+ * @returns {string}
474
+ */
475
+ export function truncateForDisplay(data, maxLen = 200) {
476
+ const str = String(data ?? '');
477
+ if (str.length <= maxLen) return str;
478
+ return str.slice(0, maxLen) + '…';
479
+ }