@zaeniahmad/kpwgen
Version:
Deterministic password generation core logic
83 lines (82 loc) • 2.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase32 = toBase32;
exports.normalizePlatform = normalizePlatform;
exports.genPassword = genPassword;
const js_sha256_1 = require("js-sha256");
function toBase32(a) {
const b = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let c = "";
for (const d of a)
c += d.toString(2).padStart(8, "0");
const e = c.match(/.{1,5}/g) ?? [];
return e.map(f => b[parseInt(f.padEnd(5, "0"), 2)]).join("");
}
function normalizePlatform(a) {
let b = a.trim().toLowerCase();
try {
if (/^https?:\/\//.test(b)) {
const c = new URL(b);
b = c.hostname;
}
const d = b.split(".").filter(Boolean);
if (d.length >= 3 && d[d.length - 2].length <= 3) {
b = d[d.length - 3];
}
else if (d.length >= 2) {
b = d[d.length - 2];
}
}
catch { }
return b.replace(/[^a-z0-9]/g, "");
}
function u16le(a, b) {
const c = new DataView(a.buffer, a.byteOffset, a.byteLength);
return c.getUint16(b, true);
}
function u32le(a, b) {
const c = new DataView(a.buffer, a.byteOffset, a.byteLength);
return c.getUint32(b, true);
}
const hmacSha256 = (a, b) => {
const c = js_sha256_1.sha256.hmac.arrayBuffer(a, b);
return new Uint8Array(c);
};
function genPassword(g) {
const { masterSecret: a, account: b, version: c = 1, prefix: d = "Qx9", suffix: e = "K7", lengthTarget: f = 18, normalize: h = true, } = g;
if (!a || a.length < 8) {
throw new Error("400");
}
if (!b || !b.trim()) {
throw new Error("401");
}
let i = g.platform;
if (!i)
throw new Error("402");
i = h ? normalizePlatform(i) : i.trim().toLowerCase();
if (!i)
throw new Error("403");
const j = b ? b.trim().toLowerCase() : "";
const k = j ? `${i}|${j}|${c}` : `${i}|${c}`;
const l = hmacSha256(a, k);
const w = l[31];
const m = toBase32(l);
const n = f;
let o = m;
const p = (u32le(l, 0) % 10000).toString().padStart(4, "0");
const q = m.slice(8, 10);
const r = q + p;
const s = ['!', '@', '#', '$', '%', '&', '*', '+', '='];
const t = s[l[6] % s.length];
const u = u16le(l, 4) % (o.length + 1);
const v = u16le(l, 7) % (o.length + 1);
o = o.slice(0, u) + r + o.slice(u);
o = o.slice(0, v) + t + o.slice(v);
o = o
.split("")
.map((x, y) => (/[A-Z]/.test(x) && ((w >> (y % 8)) & 1) === 1) ? x.toLowerCase() : x)
.join("");
const z = o.slice(0, n);
const A = `${d}${z}${e}`;
return A;
}