Generate an opaque token, such as for a sign-in link, and store only its hash, so a leaked table can’t be used to sign in:
ts
import { generateRandomBytes, hashValue } from 'jg-crypto';const token = generateRandomBytes(32); // 43 base64url characters, sent to the userconst tokenHash = hashValue(token); // 64 hex characters, stored in the database
Generate a one-time code for an email, with its leading zeros kept:
ts
import { generateRandomDigits } from 'jg-crypto';const code = generateRandomDigits(6); // such as '042917'
Verify a webhook signature over the request’s raw body, compared in constant time:
verifyHmac returns false for any signature but the exact one, and never throws for a bad signature. An empty secret or domain throws, because it’s the program’s own mistake.
Check a code from an authenticator app, claiming its time step so it can’t be used twice. claimStep is required, and works with any store that can record a step once, such as Redis for several servers:
ts
import { generateTotpSecret, verifyTotp } from 'jg-crypto';const secret = generateTotpSecret(); // 32 base32 characters, shown to the user as a QR codeawait verifyTotp(secret, code, { claimStep: (step) => claimForUser(userId, step) });
A wrong code throws TOTP_INVALID, and a code already used throws TOTP_ALREADY_USED. Codes follow RFC 6238 as every authenticator app does: HMAC-SHA1, 6 digits, and 30-second steps, accepted up to 2 steps early or late.
Generated from TSDoc
API reference
Every export of [email protected], 13 in all, with its signature, its errors, and an example.
Generates cryptographically secure random bytes, encoded as text, such as an opaque token for a link or a session. 32 bytes give 256 bits: 43 base64url characters or 64 hex characters.
Generates a string of cryptographically secure random digits, such as a one-time code to send by email. Every digit is drawn uniformly from 0 to 9, so leading zeros are as likely as any other digit and are kept.
Signature
generateRandomDigits(count: number): string
Parameters
countnumber
How many digits to generate, an integer from 1 to 256.
Returns
string
The digits.
Throws
INVALID_DIGIT_COUNTThe digit count must be an integer from 1 to 256.
Example
import { generateRandomDigits } from 'jg-crypto';generateRandomDigits(6); // such as '042917'
Generates a secret for a TOTP authenticator app: 20 random bytes, 160 bits, as RFC 4226 recommends, written as 32 characters of base32, the form apps and their QR codes take.
Signature
generateTotpSecret(): string
Returns
string
The secret.
Example
import { generateTotpSecret } from 'jg-crypto';const secret = generateTotpSecret(); // such as 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
Hashes a value with SHA-256, or another SHA-2 algorithm, and returns the lowercase hex digest. A string is hashed as its UTF-8 bytes, so a string and its encoded bytes give the same digest.
Use it to store a token's hash instead of the token, or to compare values without keeping them. It's a plain digest, not a password hash: don't use it for passwords, which need a slow, salted function such as scrypt.
Signs a message with HMAC-SHA256 and returns the signature in lowercase hex, 64 characters.
Without a domain, it's the plain HMAC webhook providers compute, such as GitHub's X-Hub-Signature-256 without its sha256= prefix. With one, the key is derived from the secret and the domain, so the same secret can sign several kinds of values without a signature for one kind ever verifying for another.
Checks a signature from signHmac, or from a webhook provider, comparing it in constant time so the time taken reveals nothing about how much of it matched.
It returns false for anything but the exact signature: a different message, secret, or domain, an uppercase or truncated signature, or one that isn't hex. It never throws for a bad signature, because signatures come from outside the program, only for an invalid secret or domain, which are the program's own.
Checks a code from an authenticator app against its secret, as RFC 6238 computes it with TOTP_PARAMETERS: HMAC-SHA1, 6 digits, and 30-second steps. A code from up to 2 steps before or after the current one is accepted, for clocks that drift. Every step is compared in constant time.
A code that matches is then claimed with claimStep, which is required, because a code an attacker sees can otherwise be used again within its window: it runs once, with the code's step, and resolves to whether this call claimed it. Store the claim where every server that verifies codes can see it, such as Redis, for at least 150 seconds, the window's length.
The secret, base32 in any letter case, with or without padding.
codestring
The 6-digit code.
optionsIVerifyTotpOptions
The function that claims the code's step.
Returns
Promise<void>
A promise that resolves once the code is verified and claimed.
Throws
INVALID_TOTP_SECRETThe TOTP secret must be base32 of at least 16 bytes.
TOTP_INVALIDThe code is not valid.
TOTP_ALREADY_USEDThe code was already used.
ErrorWhat `claimStep` throws or rejects with.
Example
import { verifyTotp } from 'jg-crypto';// the steps already used, kept in memory, so for a single process onlyconst usedSteps = new Set<number>();await verifyTotp('JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP', '123456', { claimStep: (step) => { if (usedSteps.has(step)) { return false; } usedSteps.add(step); return true; },});
type IHmacOptions = { domain?: string | undefined;};
Members
domainproperty
string
The purpose the signature is for, such as 'cursor' or 'checkpoint'. The signing key becomes HMAC-SHA256(secret, domain), so a signature made for one purpose never verifies for another, even with the same secret. Without it, the secret signs directly, as webhook providers expect.
Records that a time step's code was used, so it can't be used again, and resolves to whether this call recorded it: false when it was already used. It runs once, after the code matches, with that step, such as (step) => claimOnce(redis, 'totp:' + userId, String(step), 150). What it throws or rejects with passes through.