Skip to content

Commit

Permalink
sasl-ht-sha-256-none: Improve implementation (#1047)
Browse files Browse the repository at this point in the history
  • Loading branch information
sonnyp authored Jan 7, 2025
1 parent 1a8a2c7 commit aaaa4b1
Showing 1 changed file with 23 additions and 22 deletions.
45 changes: 23 additions & 22 deletions packages/sasl-ht-sha-256-none/index.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
/* eslint-disable n/no-unsupported-features/node-builtins */

// https://datatracker.ietf.org/doc/draft-schmaus-kitten-sasl-ht/
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API

export function Mechanism() {}

Mechanism.prototype.Mechanism = Mechanism;
Mechanism.prototype.name = "HT-SHA-256-NONE";
Mechanism.prototype.clientFirst = true;

Mechanism.prototype.response = async function response(cred) {
this.password = cred.password;
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const hmac = await crypto.subtle.importKey(
Mechanism.prototype.response = async function response({ username, password }) {
this.key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(this.password),
new TextEncoder().encode(password),
// https://developer.mozilla.org/en-US/docs/Web/API/HmacImportParams
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"]
false, // extractable
["sign", "verify"],
);
const signature = await crypto.subtle.sign(
"HMAC",
this.key,
new TextEncoder().encode("Initiator"),
);
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const digest = await crypto.subtle.sign("HMAC", hmac, new TextEncoder().encode("Initiator"));
const digestS = String.fromCharCode.apply(null, new Uint8Array(digest));
return cred.username + "\0" + digestS;
return `${username}\0${String.fromCodePoint(...new Uint8Array(signature))}`;
};

Mechanism.prototype.final = async function final(data) {
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const hmac = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(this.password),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"]
const signature = Uint8Array.from(data, (c) => c.codePointAt(0));
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify
const result = await crypto.subtle.verify(
"HMAC",
this.key,
signature,
new TextEncoder().encode("Responder"),
);
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const digest = await crypto.subtle.sign("HMAC", hmac, new TextEncoder().encode("Responder"));
const digestS = String.fromCharCode.apply(null, new Uint8Array(digest));
if (digestS !== data) {
if (result !== true) {
throw new Error("Responder message from server was wrong");
}
};
Expand Down

0 comments on commit aaaa4b1

Please sign in to comment.