Skip to content

Commit

Permalink
Merging 5c790fb into trunk-temp/pr-335/a47e78fe-6197-43b3-9969-114b04…
Browse files Browse the repository at this point in the history
…b29016
  • Loading branch information
trunk-io[bot] authored Mar 11, 2024
2 parents 3d28dd9 + 5c790fb commit cf77a85
Showing 1 changed file with 44 additions and 9 deletions.
53 changes: 44 additions & 9 deletions analyze/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,35 @@ export async function generateFingerprint(ip: string): Promise<string> {
if (typeof analyze !== "undefined") {
const fingerprint = analyze.fingerprint(ip);
return fingerprint;
} else {
// Conditional import because it's not available in some runtimes, we know
// it is when running on Vercel serverless functions.
// TODO(#180): Avoid nodejs-specific import
const createHash = await import("crypto");
}

if (hasSubtleCryptoDigest()) {
// Fingerprint v1 is just the IP address
const fingerprintRaw = `fp_1_${ip}`;

const fingerprint = createHash
.createHash("sha256")
.update(fingerprintRaw)
.digest("hex");
// Based on MDN example at
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string

// Encode the raw fingerprint into a utf-8 Uint8Array
const fingerprintUint8 = new TextEncoder().encode(fingerprintRaw);
// Hash the message with SHA-256
const fingerprintArrayBuffer = await crypto.subtle.digest(
"SHA-256",
fingerprintUint8,
);
// Convert the ArrayBuffer to a byte array
const fingerprintArray = Array.from(
new Uint8Array(fingerprintArrayBuffer),
);
// Convert the bytes to a hex string
const fingerprint = fingerprintArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");

return fingerprint;
}

return "";
}
}

Expand Down Expand Up @@ -163,3 +177,24 @@ export async function detectBot(
};
}
}

function hasSubtleCryptoDigest() {
if (typeof crypto === "undefined") {
return false;
}

if (!("subtle" in crypto)) {
return false;
}
if (typeof crypto.subtle === "undefined") {
return false;
}
if (!("digest" in crypto.subtle)) {
return false;
}
if (typeof crypto.subtle.digest !== "function") {
return false;
}

return true;
}

0 comments on commit cf77a85

Please sign in to comment.