Browse packages

Package · v0.2.0 · changelog

sec

Cryptographically secure random tokens and integers

Runtime support

  • Node
  • Deno
  • Bun
  • Browser

Generate cryptographically secure random tokens and integers, and generate and verify HMAC-SHA256 message authentication codes with Web Crypto.

Installation#

sh
npm install @rcompat/sec

Usage#

js
import sec from "@rcompat/sec";

const token = sec.random.token(); // 32 random bytes, 43 characters
const shortToken = sec.random.token(16); // 22 characters
const roll = sec.random.int(1, 6); // 1 through 6, inclusive

sec.random.token(byteLength = 32)#

Returns unpadded Base64url. The length argument counts bytes before encoding. It must be an integer from 1 through 65,536, inclusive. Invalid lengths throw a RangeError.

sec.random.int(min, max)#

Returns a uniformly distributed integer between the two inclusive bounds using rejection sampling. Both bounds must be JavaScript safe integers, and min must be at most max. Invalid bounds throw a RangeError. Equal bounds return that value without drawing random bytes. The entire safe-integer range is supported, including intervals that span zero.

sec.hmac.sha256(key, message)#

Accepts a Uint8Array key and message and returns a promise for the raw 32-byte MAC as a Uint8Array. If either input is a view into a larger buffer, only bytes within that view are used. Encode the result as needed.

This example uses RFC 4231 test case 1.

js
import sec from "@rcompat/sec";

const key = new Uint8Array(20).fill(0x0b);
const message = new TextEncoder().encode("Hi There");
const mac = await sec.hmac.sha256(key, message);
console.log(mac.toHex());
// b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7

sec.signature.verify({ secret, payload, signature })#

Verifies an HMAC-SHA256 signature and returns a Promise<boolean>. The helper encodes the string secret as UTF-8. Pass the original payload bytes as an ArrayBuffer or Uint8Array. The signature must be a string with the exact sha256= prefix followed by 64 hexadecimal digits, or null if absent. Missing, malformed, and mismatched signatures resolve to false.

For a GitHub webhook, verify the original request body before decoding it. The caller reads the header and body and handles delivery deduplication.

js
import sec from "@rcompat/sec";

async function handleWebhook(request, webhookSecret) {
  const body = await request.arrayBuffer();
  const valid = await sec.signature.verify({
    secret: webhookSecret,
    payload: body,
    signature: request.headers.get("X-Hub-Signature-256"),
  });

  if (!valid) return new Response(null, { status: 401 });
  const event = JSON.parse(new TextDecoder().decode(body));
  // Process the verified event.
  return new Response(null, { status: 204 });
}

Runtime support#

Supports current Node.js, Deno, Bun, and browsers with crypto.getRandomValues and Uint8Array.prototype.toBase64.

HMAC generation and signature verification use crypto.subtle, which requires a secure context in browsers. Signature verification also uses Uint8Array.fromHex.