Home

js-spectre @main - refs - log -
-
https://git.jolheiser.com/js-spectre.git
JS implementation for spectre/masterpassword
js-spectre / lib / spectre.js
- raw
 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
export * from './template.js';
export * from './scope.js';
import { scrypt } from "@noble/hashes/scrypt";
import { defaultScoper, defaultTemplate, Scope } from "./scope.js";
import { HMAC } from "@noble/hashes/hmac";
import { sha256 } from "@noble/hashes/sha256";
import { characters, templates } from "./template.js";
export class Spectre {
    name;
    secret;
    scoper;
    key;
    constructor(name, secret, scoper = defaultScoper) {
        this.name = name;
        this.secret = secret;
        this.scoper = scoper;
        this.key = this.userKey();
    }
    userKey() {
        const enc = new TextEncoder();
        const nameBytes = enc.encode(this.name);
        const secretBytes = enc.encode(this.secret);
        const keyScope = enc.encode(this.scoper.scope(Scope.AUTHENTICATION));
        const nameBytesLen = nameBytes.length;
        const keySalt = new Uint8Array([
            ...keyScope,
            ...bigEndian(nameBytesLen),
            ...nameBytes,
        ]);
        const N = 32768;
        const r = 8;
        const p = 2;
        const maxmem = 128 * r * (N + p + 2);
        return scrypt(secretBytes, keySalt, { N, r, p, maxmem, dkLen: 64 });
    }
    siteKey(name, counter, scope) {
        const enc = new TextEncoder();
        const nameBytes = enc.encode(name);
        const scopeBytes = enc.encode(this.scoper.scope(scope));
        const nameBytesLen = nameBytes.length;
        const keySalt = new Uint8Array([
            ...scopeBytes,
            ...bigEndian(nameBytesLen),
            ...nameBytes,
            ...bigEndian(counter),
        ]);
        const sign = new HMAC(sha256, this.key);
        sign.update(keySalt);
        return sign.digest();
    }
    site(siteName, templateType, counter = 1, scope = Scope.AUTHENTICATION) {
        if (templateType === undefined)
            templateType = defaultTemplate(scope);
        const siteKey = this.siteKey(siteName, counter, scope);
        const templateSet = templates[templateType];
        const template = templateSet[siteKey[0] % templateSet.length];
        let out = "";
        for (let i = 0; i < template.length; i++) {
            const b = template[i];
            const chars = characters[b];
            const char = chars[siteKey[i + 1] % chars.length];
            out += char;
        }
        return out;
    }
}
function bigEndian(n) {
    const buffer = new ArrayBuffer(4);
    const view = new DataView(buffer);
    view.setInt32(0, n, false);
    return new Uint8Array(buffer);
}