qr-payload-parser 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -2
  3. package/index.d.ts +120 -0
  4. package/index.js +479 -0
  5. package/package.json +46 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sunasty (https://sunasty.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # qr-payload-parser
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-dependency JavaScript and TypeScript parser for structured QR code payloads (`WIFI:`, `otpauth://totp/`, `BEGIN:VCARD`, `mailto:`, `MATMSG:`, `smsto:`, `sms:`, `tel:`, and HTTP/HTTPS URLs with security inspection) paired with a Web Crypto `SubtleCrypto` RFC 6238 TOTP generator and RFC 4180 CSV/JSON serializers.
4
+
5
+ Extracted from the core engine powering the [Sunasty QR Scanner](https://sunasty.com/qr-scan/) and [Sunasty QR Code Generator](https://sunasty.com/qr-code/).
6
+
7
+ ## Features
8
+
9
+ - **Structured QR Payload Parser**: `parseQrPayload` normalizes raw QR strings into a strongly typed discriminated union (`wifi`, `totp`, `vcard`, `email`, `sms`, `phone`, `url`, `text`).
10
+ - **RFC 6238 TOTP Generator**: `generateTotpCode` computes 6-digit (or N-digit) HMAC-SHA1 time-based one-time passwords using the standard Web Crypto `SubtleCrypto` API in Node.js (>= 18), browsers, and Service Workers.
11
+ - **URL Security Inspection**: `analyzeUrlSecurity` detects unencrypted `http://` links and raw IPv4/IPv6 hostnames before navigation.
12
+ - **Low-Contrast Image Preprocessors**: `applyHighContrastThreshold` and `normalizeAndBinarizeLowContrast` prepare RGBA buffers for QR matrix detection.
13
+ - **Batch History Export**: `serializeScanHistoryToCsv` (RFC 4180 compliant) and `serializeScanHistoryToJson`.
14
+
15
+ ## Installation
16
+
17
+ Via npm or JSR:
18
+
19
+ ```bash
20
+ npm install qr-payload-parser
21
+ # or via JSR
22
+ npx jsr add @sunasty/qr-payload
23
+ ```
24
+
25
+ Or import directly in browsers and Deno via ESM CDN (jsDelivr):
26
+
27
+ ```js
28
+ import {
29
+ parseQrPayload,
30
+ generateTotpCode,
31
+ analyzeUrlSecurity,
32
+ } from 'https://cdn.jsdelivr.net/npm/qr-payload-parser@1.0.0/+esm';
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ### Parsing Structured QR Payloads
38
+
39
+ ```js
40
+ import { parseQrPayload } from 'qr-payload-parser';
41
+
42
+ const wifi = parseQrPayload('WIFI:S:ProdNetwork;T:WPA2;P:SecretKey2026;H:false;;');
43
+ // { kind: 'wifi', ssid: 'ProdNetwork', encryption: 'WPA2', password: 'SecretKey2026', hidden: false }
44
+
45
+ const vcard = parseQrPayload(
46
+ 'BEGIN:VCARD\nVERSION:3.0\nFN:Alex Martin\nORG:Sunasty\nTEL:+33123456789\nEMAIL:alex@sunasty.com\nEND:VCARD'
47
+ );
48
+ // { kind: 'vcard', fullName: 'Alex Martin', org: 'Sunasty', phone: '+33123456789', email: 'alex@sunasty.com', ... }
49
+
50
+ const urlInfo = parseQrPayload('http://192.168.1.1/login');
51
+ // { kind: 'url', domain: '192.168.1.1', isInsecureHttp: true, isRawIp: true, hasSecurityWarning: true, ... }
52
+ ```
53
+
54
+ ### Generating RFC 6238 2FA TOTP Codes
55
+
56
+ ```js
57
+ import { parseQrPayload, generateTotpCode } from 'qr-payload-parser';
58
+
59
+ const parsed = parseQrPayload(
60
+ 'otpauth://totp/Sunasty:ops@sunasty.com?secret=JBSWY3DPEHPK3PXP&issuer=Sunasty'
61
+ );
62
+
63
+ if (parsed.kind === 'totp') {
64
+ const { code, remainingSeconds } = await generateTotpCode(
65
+ parsed.secret,
66
+ Date.now(),
67
+ parsed.period,
68
+ parsed.digits
69
+ );
70
+ console.log(`Current 2FA code: ${code} (valid for ${remainingSeconds}s)`);
71
+ }
72
+ ```
73
+
74
+ ### Exporting Scan History to RFC 4180 CSV
75
+
76
+ ```js
77
+ import { serializeScanHistoryToCsv } from 'qr-payload-parser';
78
+
79
+ const csv = serializeScanHistoryToCsv([
80
+ {
81
+ timestamp: '2026-10-22T12:00:00.000Z',
82
+ source: 'camera',
83
+ type: 'url',
84
+ isUrl: true,
85
+ data: 'https://sunasty.com/qr-scan/',
86
+ },
87
+ ]);
88
+ ```
89
+
90
+ ## Web Utilities
91
+
92
+ - Client-side QR code scanner from image or webcam: [https://sunasty.com/qr-scan/](https://sunasty.com/qr-scan/)
93
+ - Custom SVG and PNG QR code generator: [https://sunasty.com/qr-code/](https://sunasty.com/qr-code/)
94
+ - Chrome/Chromium MV3 extension repository: [https://github.com/bsulyan/sunasty-qr-scanner](https://github.com/bsulyan/sunasty-qr-scanner)
95
+
96
+ ## License
97
+
98
+ MIT
package/index.d.ts ADDED
@@ -0,0 +1,120 @@
1
+ export declare const SCAN_ACCEPTED_MIME: string[];
2
+ export declare const SCAN_MAX_BYTES: number;
3
+
4
+ export interface UrlSecurityAnalysis {
5
+ valid: boolean;
6
+ href: string;
7
+ protocol: string;
8
+ domain: string;
9
+ pathAndQuery: string;
10
+ isInsecureHttp: boolean;
11
+ isRawIp: boolean;
12
+ hasSecurityWarning: boolean;
13
+ }
14
+
15
+ export interface WifiPayload {
16
+ kind: 'wifi';
17
+ ssid: string;
18
+ encryption: string;
19
+ password: string;
20
+ hidden: boolean;
21
+ }
22
+
23
+ export interface VcardPayload {
24
+ kind: 'vcard';
25
+ fullName: string;
26
+ phone: string;
27
+ email: string;
28
+ org: string;
29
+ rawVcard: string;
30
+ }
31
+
32
+ export interface EmailPayload {
33
+ kind: 'email';
34
+ to: string;
35
+ subject: string;
36
+ body: string;
37
+ mailtoHref: string;
38
+ }
39
+
40
+ export interface SmsPayload {
41
+ kind: 'sms';
42
+ number: string;
43
+ message: string;
44
+ smsHref: string;
45
+ }
46
+
47
+ export interface PhonePayload {
48
+ kind: 'phone';
49
+ number: string;
50
+ telHref: string;
51
+ }
52
+
53
+ export interface TotpPayload {
54
+ kind: 'totp';
55
+ label: string;
56
+ account: string;
57
+ issuer: string;
58
+ secret: string;
59
+ digits: number;
60
+ period: number;
61
+ }
62
+
63
+ export interface UrlPayload extends UrlSecurityAnalysis {
64
+ kind: 'url';
65
+ text: string;
66
+ }
67
+
68
+ export interface TextPayload {
69
+ kind: 'text';
70
+ text: string;
71
+ }
72
+
73
+ export type ParsedQrPayload =
74
+ | WifiPayload
75
+ | VcardPayload
76
+ | EmailPayload
77
+ | SmsPayload
78
+ | PhonePayload
79
+ | TotpPayload
80
+ | UrlPayload
81
+ | TextPayload;
82
+
83
+ export interface TotpResult {
84
+ code: string;
85
+ remainingSeconds: number;
86
+ period: number;
87
+ counter: number;
88
+ }
89
+
90
+ export interface ScanRecord {
91
+ timestamp?: string;
92
+ source?: string;
93
+ type?: string;
94
+ isUrl?: boolean;
95
+ data: string;
96
+ [key: string]: unknown;
97
+ }
98
+
99
+ export declare function isAcceptedScanMime(mime: string): boolean;
100
+ export declare function looksLikeUrl(data: string): boolean;
101
+ export declare function analyzeUrlSecurity(rawUrl: string): UrlSecurityAnalysis;
102
+ export declare function parseQrPayload(data: string): ParsedQrPayload;
103
+ export declare function decodeBase32(base32: string): Uint8Array;
104
+ export declare function generateTotpCode(
105
+ secretBase32: string,
106
+ timestampMs?: number,
107
+ period?: number,
108
+ digits?: number
109
+ ): Promise<TotpResult>;
110
+ export declare function applyHighContrastThreshold(
111
+ data: Uint8ClampedArray,
112
+ threshold?: number,
113
+ invert?: boolean
114
+ ): Uint8ClampedArray;
115
+ export declare function normalizeAndBinarizeLowContrast(
116
+ data: Uint8ClampedArray
117
+ ): Uint8ClampedArray;
118
+ export declare function serializeScanHistoryToCsv(results: ScanRecord[]): string;
119
+ export declare function serializeScanHistoryToJson(results: Array<Record<string, unknown>>): string;
120
+ export declare function truncateForDisplay(data: string, maxLen?: number): string;
package/index.js ADDED
@@ -0,0 +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
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "qr-payload-parser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Zero-dependency structured QR payload parser (Wi-Fi, 2FA TOTP otpauth://, vCard, mailto, MATMSG, SMS, tel, URL security analyzer) and RFC 6238 TOTP generator via Web Crypto SubtleCrypto.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "index.d.ts",
17
+ "LICENSE",
18
+ "README.md"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test test.js"
22
+ },
23
+ "keywords": [
24
+ "qr",
25
+ "qrcode",
26
+ "totp",
27
+ "otpauth",
28
+ "rfc6238",
29
+ "wifi",
30
+ "vcard",
31
+ "matmsg",
32
+ "parser",
33
+ "webcrypto"
34
+ ],
35
+ "author": "Sunasty <https://sunasty.com>",
36
+ "license": "MIT",
37
+ "homepage": "https://sunasty.com/qr-scan/",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/bsulyan/sunasty-qr-payload.git"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/bsulyan/sunasty-qr-payload/issues"
44
+ },
45
+ "engines": {
46
+ "node": ">=18.0.0"
47
+ }
48
+ }