shivay00001's picture
NFC Tag-Write Toolkit: static web UI (ndef.js byte-identical to tested Python builder)
7207e78 verified
Raw History Blame Contribute Delete
14.8 kB
/* NDEF builder for NTAG215 tags — faithful JavaScript port of ndef_builder.py
* (Python, standard library only) from Shivay00001/nfc-write-toolkit.
*
* Byte-for-byte identical output to the Python builder (verified by an
* automated harness comparing hex dumps for every usage + edge cases).
* No dependencies, no network calls, no data leaves the browser.
*
* HONESTY RULE: the Google-review card carries ONLY the shop's genuine
* review link. No prefilled review text, no pre-selected stars, no
* star-gating, no direct-submit tricks. This builder cannot express any
* of those — a review link is just a URL record.
*/
(function (root) {
"use strict";
var NTAG215_CAPACITY = 504;
var TNF_WELL_KNOWN = 0x01;
var TNF_MIME_MEDIA = 0x02;
var FLAG_MB = 0x80, FLAG_ME = 0x40, FLAG_SR = 0x10;
/* NFC Forum URI RTD identifier codes, same order as the Python builder
* (longest prefix first for matching). */
var URI_PREFIXES = [
[0x02, "https://www."], [0x01, "http://www."],
[0x04, "https://"], [0x03, "http://"],
[0x05, "tel:"], [0x06, "mailto:"],
[0x07, "ftp://anonymous:anonymous@"], [0x08, "ftp://ftp."],
[0x09, "ftps://"], [0x0A, "sftp://"], [0x0B, "smb://"],
[0x0C, "nfs://"], [0x0D, "ftp://"], [0x0E, "dav://"],
[0x0F, "news:"], [0x10, "telnet://"], [0x11, "imap:"],
[0x12, "rtsp://"], [0x13, "urn:"], [0x14, "pop:"],
[0x15, "sip:"], [0x16, "sips:"], [0x17, "tftp:"],
[0x18, "btspp://"], [0x19, "btl2cap://"], [0x1A, "btgoep://"],
[0x1B, "tcpobex://"], [0x1C, "irdaobex://"], [0x1D, "file://"],
[0x1E, "urn:epc:id:"], [0x1F, "urn:epc:tag:"],
[0x20, "urn:epc:pat:"], [0x21, "urn:epc:raw:"],
[0x22, "urn:epc:"], [0x23, "urn:nfc:"],
[0x00, ""]
];
function CapacityError(message) {
this.name = "CapacityError";
this.message = message || "";
}
CapacityError.prototype = Object.create(Error.prototype);
function NdefError(message) {
this.name = "NdefError";
this.message = message || "";
}
NdefError.prototype = Object.create(Error.prototype);
var encoder = new TextEncoder();
var decoder = new TextDecoder("utf-8");
function utf8(str) { return encoder.encode(str); }
function concat() {
var total = 0, i, out, pos = 0;
for (i = 0; i < arguments.length; i++) total += arguments[i].length;
out = new Uint8Array(total);
for (i = 0; i < arguments.length; i++) {
out.set(arguments[i], pos);
pos += arguments[i].length;
}
return out;
}
/* Python urllib.parse.quote(value, safe=""): percent-encode everything
* except A-Z a-z 0-9 _ . - ~ (UTF-8 for non-ASCII). encodeURIComponent
* additionally leaves ! ' ( ) * unescaped, so escape those too. */
function quote(value) {
return encodeURIComponent(value).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0");
});
}
/* --- Low-level records --- */
function encodeRecord(rec, first, last) {
var header = 0;
if (first) header |= FLAG_MB;
if (last) header |= FLAG_ME;
header |= rec.tnf & 0x07;
var short = rec.payload.length < 256;
if (short) header |= FLAG_SR;
var head;
if (short) {
head = new Uint8Array([header, rec.type.length, rec.payload.length]);
} else {
head = new Uint8Array([
header, rec.type.length,
(rec.payload.length >>> 24) & 0xff, (rec.payload.length >>> 16) & 0xff,
(rec.payload.length >>> 8) & 0xff, rec.payload.length & 0xff
]);
}
return concat(head, rec.type, rec.payload);
}
function buildMessage(records) {
if (!records.length) throw new NdefError("cannot build an empty NDEF message");
var parts = records.map(function (rec, i) {
return encodeRecord(rec, i === 0, i === records.length - 1);
});
return concat.apply(null, parts);
}
function parseMessage(data) {
var records = [], pos = 0;
while (pos < data.length) {
if (pos + 2 > data.length) throw new NdefError("truncated record header at offset " + pos);
var header = data[pos++];
var me = !!(header & FLAG_ME), sr = !!(header & FLAG_SR), il = !!(header & 0x08);
if (header & 0x20) throw new NdefError("chunked records are not supported");
var tnf = header & 0x07;
var typeLen = data[pos++];
var payloadLen;
if (sr) {
payloadLen = data[pos++];
} else {
if (pos + 4 > data.length) throw new NdefError("truncated long-form payload length");
payloadLen = ((data[pos] << 24) | (data[pos + 1] << 16) | (data[pos + 2] << 8) | data[pos + 3]) >>> 0;
pos += 4;
}
var idLen = 0;
if (il) idLen = data[pos++];
if (pos + typeLen + idLen + payloadLen > data.length)
throw new NdefError("truncated record body at offset " + pos);
var typeBytes = data.slice(pos, pos + typeLen);
pos += typeLen + idLen;
var payload = data.slice(pos, pos + payloadLen);
pos += payloadLen;
records.push({ tnf: tnf, type: typeBytes, payload: payload });
if (me) break;
}
if (pos !== data.length) throw new NdefError("trailing bytes after ME record");
return records;
}
/* --- TLV framing --- */
function wrapTlv(message, capacity) {
capacity = (capacity === undefined) ? NTAG215_CAPACITY : capacity;
var tlv;
if (message.length < 255) {
tlv = concat(new Uint8Array([0x03, message.length]), message, new Uint8Array([0xFE]));
} else {
tlv = concat(
new Uint8Array([0x03, 0xFF, (message.length >>> 8) & 0xff, message.length & 0xff]),
message, new Uint8Array([0xFE]));
}
if (tlv.length > capacity) {
throw new CapacityError(
"framed payload is " + tlv.length + " bytes, exceeding the NTAG215 capacity of " +
capacity + " bytes by " + (tlv.length - capacity) + " bytes; shorten the content");
}
return tlv;
}
function unwrapTlv(tlv) {
if (tlv.length < 3 || tlv[0] !== 0x03)
throw new NdefError("data does not start with an NDEF Message TLV (0x03)");
var length, message, end;
if (tlv[1] === 0xFF) {
if (tlv.length < 4) throw new NdefError("truncated long-form TLV length");
length = (tlv[2] << 8) | tlv[3];
message = tlv.slice(4, 4 + length);
end = 4 + length;
} else {
length = tlv[1];
message = tlv.slice(2, 2 + length);
end = 2 + length;
}
if (message.length !== length) throw new NdefError("TLV length does not match available data");
if (end >= tlv.length || tlv[end] !== 0xFE)
throw new NdefError("missing terminator TLV (0xFE) after NDEF message");
return message;
}
function frame(records) { return wrapTlv(buildMessage(records)); }
function uriRecord(uri) {
for (var i = 0; i < URI_PREFIXES.length; i++) {
var code = URI_PREFIXES[i][0], prefix = URI_PREFIXES[i][1];
if (prefix && uri.indexOf(prefix) === 0) {
return { tnf: TNF_WELL_KNOWN, type: utf8("U"),
payload: concat(new Uint8Array([code]), utf8(uri.slice(prefix.length))) };
}
}
return { tnf: TNF_WELL_KNOWN, type: utf8("U"),
payload: concat(new Uint8Array([0x00]), utf8(uri)) };
}
/* --- Usage builders (each returns framed bytes) --- */
function buildUrl(url) {
if (url.indexOf("http://") !== 0 && url.indexOf("https://") !== 0)
throw new NdefError("URL must start with http:// or https://, got '" + url + "'");
return frame([uriRecord(url)]);
}
function buildGmbReview(reviewUrl) {
if (reviewUrl.indexOf("https://") !== 0 && reviewUrl.indexOf("http://") !== 0)
throw new NdefError("review link must be a full http(s) URL, got '" + reviewUrl + "'");
return frame([uriRecord(reviewUrl)]);
}
function buildUpi(pa, pn, am, cu, tn) {
pn = pn || ""; cu = cu || "INR"; tn = tn || "";
if (pa.indexOf("@") === -1 || !pa.trim())
throw new NdefError("UPI ID (pa) must look like name@bank, got '" + pa + "'");
var params = [["pa", pa]];
if (pn) params.push(["pn", pn]);
if (am !== undefined && am !== null && am !== "") {
var value = Number(am);
if (isNaN(value)) throw new NdefError("amount must be a number, got '" + am + "'");
if (value <= 0) throw new NdefError("amount must be positive, got '" + am + "'");
params.push(["am", String(am)]);
}
params.push(["cu", cu]);
if (tn) params.push(["tn", tn]);
var query = params.map(function (kv) { return kv[0] + "=" + quote(kv[1]); }).join("&");
return frame([uriRecord("upi://pay?" + query)]);
}
function cleanNumber(number) {
return number.split("").filter(function (ch) {
return (ch >= "0" && ch <= "9") || ch === "+";
}).join("");
}
function buildTel(number) {
var cleaned = cleanNumber(number);
if (!cleaned || cleaned === "+")
throw new NdefError("phone number must contain digits, got '" + number + "'");
return frame([uriRecord("tel:" + cleaned)]);
}
function buildSms(number, body) {
var cleaned = cleanNumber(number);
if (!cleaned || cleaned === "+")
throw new NdefError("phone number must contain digits, got '" + number + "'");
var uri = "sms:" + cleaned;
if (body) uri += "?body=" + quote(body);
return frame([uriRecord(uri)]);
}
function buildText(text, lang) {
lang = lang || "en";
var langBytes = utf8(lang);
if (langBytes.length > 63) throw new NdefError("language code too long: '" + lang + "'");
var payload = concat(new Uint8Array([langBytes.length]), langBytes, utf8(text));
return frame([{ tnf: TNF_WELL_KNOWN, type: utf8("T"), payload: payload }]);
}
function escapeVcard(value) {
return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;")
.replace(/,/g, "\\,").replace(/\n/g, "\\n");
}
function buildVcard(name, phone, email, org, url) {
phone = phone || ""; email = email || ""; org = org || ""; url = url || "";
if (!name.trim()) throw new NdefError("vCard requires a name");
var lines = ["BEGIN:VCARD", "VERSION:3.0", "FN:" + escapeVcard(name)];
if (org) lines.push("ORG:" + escapeVcard(org));
if (phone) lines.push("TEL:" + escapeVcard(phone));
if (email) lines.push("EMAIL:" + escapeVcard(email));
if (url) lines.push("URL:" + escapeVcard(url));
lines.push("END:VCARD");
var payload = utf8(lines.join("\r\n"));
return frame([{ tnf: TNF_MIME_MEDIA, type: utf8("text/vcard"), payload: payload }]);
}
var WPS_CREDENTIAL = 0x100E, WPS_SSID = 0x1045, WPS_AUTH_TYPE = 0x1003,
WPS_ENC_TYPE = 0x100F, WPS_NETWORK_KEY = 0x1027;
var WPS_AUTH = {
"open": [0x0001, 0x0001],
"WPA-PSK": [0x0002, 0x0004],
"WPA2-PSK": [0x0020, 0x0008]
};
function wpsField(type, value) {
return concat(new Uint8Array([
(type >>> 8) & 0xff, type & 0xff,
(value.length >>> 8) & 0xff, value.length & 0xff
]), value);
}
function wpsU16(v) { return new Uint8Array([(v >>> 8) & 0xff, v & 0xff]); }
function buildWifi(ssid, password, auth) {
password = password || ""; auth = auth || "WPA2-PSK";
if (!(auth in WPS_AUTH))
throw new NdefError("auth must be one of ['WPA-PSK', 'WPA2-PSK', 'open'], got '" + auth + "'");
var ssidBytes = utf8(ssid);
if (!ssidBytes.length || ssidBytes.length > 32)
throw new NdefError("SSID must be 1-32 bytes, got '" + ssid + "'");
var authValue = WPS_AUTH[auth][0], encValue = WPS_AUTH[auth][1];
var inner = concat(
wpsField(WPS_SSID, ssidBytes),
wpsField(WPS_AUTH_TYPE, wpsU16(authValue)),
wpsField(WPS_ENC_TYPE, wpsU16(encValue))
);
if (auth !== "open") {
if (!(password.length >= 8 && password.length <= 63))
throw new NdefError("Wi-Fi password must be 8-63 characters for " + auth);
inner = concat(inner, wpsField(WPS_NETWORK_KEY, utf8(password)));
}
var payload = wpsField(WPS_CREDENTIAL, inner);
return frame([{ tnf: TNF_MIME_MEDIA, type: utf8("application/vnd.wfa.wsc"), payload: payload }]);
}
/* --- Decoders (display + round-trip checks) --- */
function decodeUri(record) {
if (decoder.decode(record.type) !== "U" || !record.payload.length)
throw new NdefError("not a URI record");
var code = record.payload[0];
var rest = decoder.decode(record.payload.slice(1));
for (var i = 0; i < URI_PREFIXES.length; i++)
if (URI_PREFIXES[i][0] === code) return URI_PREFIXES[i][1] + rest;
throw new NdefError("unknown URI identifier code 0x" + code.toString(16));
}
function decodeText(record) {
if (decoder.decode(record.type) !== "T" || !record.payload.length)
throw new NdefError("not a Text record");
var status = record.payload[0];
var langLen = status & 0x3f;
return decoder.decode(record.payload.slice(1 + langLen));
}
function decodeWifi(record) {
if (decoder.decode(record.type) !== "application/vnd.wfa.wsc")
throw new NdefError("not a Wi-Fi record");
var payload = record.payload;
if (payload.length < 4) throw new NdefError("Wi-Fi payload too short");
var ftype = (payload[0] << 8) | payload[1];
var flen = (payload[2] << 8) | payload[3];
if (ftype !== WPS_CREDENTIAL) throw new NdefError("Wi-Fi payload does not start with a Credential TLV");
var inner = payload.slice(4, 4 + flen);
var ssid = null, password = null, authValue = null, pos = 0;
while (pos + 4 <= inner.length) {
var t = (inner[pos] << 8) | inner[pos + 1];
var ln = (inner[pos + 2] << 8) | inner[pos + 3];
var value = inner.slice(pos + 4, pos + 4 + ln);
if (t === WPS_SSID) ssid = decoder.decode(value);
else if (t === WPS_NETWORK_KEY) password = decoder.decode(value);
else if (t === WPS_AUTH_TYPE) authValue = (value[0] << 8) | value[1];
pos += 4 + ln;
}
var authName = "unknown(" + authValue + ")";
for (var k in WPS_AUTH) if (WPS_AUTH[k][0] === authValue) authName = k;
return { ssid: ssid, password: password, auth: authName };
}
function firstRecord(framed) { return parseMessage(unwrapTlv(framed))[0]; }
var api = {
NTAG215_CAPACITY: NTAG215_CAPACITY,
CapacityError: CapacityError, NdefError: NdefError,
buildUrl: buildUrl, buildGmbReview: buildGmbReview, buildUpi: buildUpi,
buildTel: buildTel, buildSms: buildSms, buildText: buildText,
buildVcard: buildVcard, buildWifi: buildWifi,
buildMessage: buildMessage, parseMessage: parseMessage,
wrapTlv: wrapTlv, unwrapTlv: unwrapTlv,
decodeUri: decodeUri, decodeText: decodeText, decodeWifi: decodeWifi,
firstRecord: firstRecord
};
if (typeof module !== "undefined" && module.exports) module.exports = api;
root.NDEF = api;
})(typeof window !== "undefined" ? window : globalThis);