import { parseExactJson, compareExactNumbers } from './exact-json.ts'; // SIGNING ON THE CONTEXT (docs/contributing/architecture.md, "What an author writes, and how": the tokens-and-keys row) // — one deterministic implementation of what vendors sign with, given to handlers as `ctx.crypto`, so no pack reaches // `node:crypto` itself: JWTs (RS256 or EdDSA with a pack's instance key, HS256 with a shared secret), their verification, a // JWKS for a public key, an HMAC and a SHA-256. Nothing here is random: a key is the pack's data (a PEM it declares), // and every value a signature carries comes from the call. // A namespace, never named imports: a browser client bundles the kernel, and the browser's `node:crypto` polyfill has no // createPublicKey or timingSafeEqual; named, the bundle fails to build. They are reached only when a signature is made. import * as nodeCrypto from 'node:crypto'; import { sealedBoxKeyPair, sealedBoxOpen } from './sealed-box.ts'; import { receiverNow } from './world-clock.ts'; type Row = Record; export type Jwk = { kty: 'RSA'; use: 'sig'; alg: 'RS256'; kid: string; n: string; e: string } | { kty: 'OKP'; use: 'sig'; alg: 'EdDSA'; crv: 'Ed25519'; kid: string; x: string }; export type Jwks = { keys: Jwk[] }; /** A signing key: an RSA or Ed25519 private key as a PEM (its public half, given or derived, is what a JWKS serves and * names by `kid`), or a shared secret. Only deterministic algorithms: an ECDSA signature is random, so a World signs * none; Ed25519's is deterministic (RFC 8032), Better Auth's default (`EdDSA`). */ export type SigningKey = { alg: 'RS256' | 'RS384' | 'RS512' | 'EdDSA'; privatePem: string; publicPem?: string } | { alg: 'HS256' | 'HS384' | 'HS512'; secret: string }; /** The algorithms `jwtSign` signs with. */ export const SIGNING_ALGORITHMS: ReadonlyArray = ['RS256', 'RS384', 'RS512', 'EdDSA', 'HS256', 'HS384', 'HS512']; const digestOf = (alg: string): string => `sha${alg.slice(2)}`; /** A token check's result, with its payload on success. `jwtVerify` checks time as well as the signature. */ export type JwtVerdict = { valid: boolean; payload?: Row; reason?: 'malformed' | 'unexpected_alg' | 'no_matching_key' | 'bad_signature' | 'expired' | 'not_yet_valid' }; export type JwtVerificationKey = Jwks | { alg: 'HS256' | 'HS384' | 'HS512'; secret: string }; export type JwtDecodeOptions = { strict?: boolean; integers?: 'exact' | 'number' }; export type JwtSignatureOptions = JwtDecodeOptions & { hmacSignature?: 'canonical' | 'bytes' }; const base64url = (input: Buffer | string): string => Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); const fromBase64url = (s: string): Buffer => Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64'); const jsonPart = (value: unknown): string => base64url(JSON.stringify(value)); /** A public key's id: a prefix and the first 16 hex of SHA-256 over its DER (what its JWKS and every token name). */ export function keyId(publicPem: string, prefix = 'ins_'): string { const der = nodeCrypto.createPublicKey(publicPem).export({ type: 'spki', format: 'der' }); return `${prefix}${nodeCrypto.createHash('sha256').update(der).digest('hex').slice(0, 16)}`; } /** A JWT: `iat` and `nbf` are `now` (seconds), `exp` `now` plus the lifetime (60 s when none is given), unless the * claims name their own. `now` defaults to the receiver's clock (`receiverNow()`: the World's where the app reads it, * else the machine's), which a token's receiver checks those claims against (ADR 0036 §4). A token of a key pair * carries the key's `kid`. */ export function jwtSign(claims: Row, key: SigningKey, opts: { now?: number; expiresInSeconds?: number; kidPrefix?: string; kid?: string; typ?: string } = {}): string { const now = opts.now ?? Math.floor(receiverNow() / 1000); return jwtSignClaims({ iat: now, exp: now + (opts.expiresInSeconds ?? 60), nbf: now, ...claims }, key, opts); } /** A JWT over exactly the supplied claims, without adding temporal claims. The caller owns their policy. A key's `kid` * is its thumbprint unless `kid` names the one a client's token carries as authored. */ export function jwtSignClaims(claims: Row, key: SigningKey, opts: { kidPrefix?: string; kid?: string; typ?: string } = {}): string { // a key of another kind than its algorithm's is refused by name (an RSA key under EdDSA would fail inside the signer) if ('privatePem' in key) { const kind = nodeCrypto.createPrivateKey(key.privatePem).asymmetricKeyType; const wants = key.alg === 'EdDSA' ? 'ed25519' : 'rsa'; if (kind !== wants) throw new Error(`jwtSign: ${key.alg} signs with an ${wants === 'rsa' ? 'RSA' : 'Ed25519'} key, and this key is ${kind ?? 'of no known type'}`); } const header = 'privatePem' in key ? { alg: key.alg, typ: opts.typ ?? 'JWT', kid: opts.kid ?? keyId(key.publicPem ?? nodeCrypto.createPublicKey(key.privatePem).export({ type: 'spki', format: 'pem' }).toString(), opts.kidPrefix) } : { alg: key.alg, typ: opts.typ ?? 'JWT' }; const input = `${jsonPart(header)}.${jsonPart(claims)}`; if ('secret' in key) return `${input}.${base64url(nodeCrypto.createHmac(digestOf(key.alg), key.secret).update(input).digest())}`; if (key.alg === 'EdDSA') return `${input}.${base64url(nodeCrypto.sign(null, Buffer.from(input), key.privatePem))}`; const signer = nodeCrypto.createSign(`RSA-SHA${key.alg.slice(2)}`); signer.update(input); signer.end(); return `${input}.${base64url(signer.sign(key.privatePem))}`; } /** A JWT's header and payload, unverified. Strict compact framing and ordinary JSON numbers are explicit * protocol policies; existing kernel callers retain permissive decoding and exact integer values. */ export function jwtDecode(token: string, opts: JwtDecodeOptions = {}): { header: Row; payload: Row } { if (opts.strict && typeof token !== 'string') throw new Error('malformed jwt'); const parts = token.split('.'); if (parts.length !== 3 || opts.strict && parts.some(part => !/^[A-Za-z0-9_-]+$/.test(part))) throw new Error('malformed jwt'); const parse = opts.integers === 'number' ? JSON.parse : parseExactJson; const part = (s: string): Row => parse(fromBase64url(s).toString('utf8')) as Row; return { header: part(parts[0]!), payload: part(parts[1]!) }; } function timely(payload: Row, now: number): JwtVerdict { if ((typeof payload.exp === 'number' || typeof payload.exp === 'string' && /^-?\d+$/.test(payload.exp)) && compareExactNumbers(now, payload.exp) >= 0) return { valid: false, reason: 'expired' }; if ((typeof payload.nbf === 'number' || typeof payload.nbf === 'string' && /^-?\d+$/.test(payload.nbf)) && compareExactNumbers(now, payload.nbf) < 0) return { valid: false, reason: 'not_yet_valid' }; return { valid: true, payload }; } /** A token checked: an RS256 or EdDSA one against a JWKS (its `kid`'s key), an HS256 one against its secret (constant time), * then its `exp`/`nbf` at `now` (seconds; the receiver's clock, `receiverNow()`, by default, the clock `jwtSign` stamps on). */ export function jwtVerify(token: string, key: JwtVerificationKey, opts: { now?: number } = {}): JwtVerdict { const verdict = jwtVerifySignature(token, key); return verdict.valid ? timely(verdict.payload!, opts.now ?? Math.floor(receiverNow() / 1000)) : verdict; } /** A token's signature checked without an `exp`/`nbf` policy. An issuer selector sees unverified claims and may * enforce its vendor's claim shape and key ownership before returning a key. HMAC signatures use canonical * text by default; a protocol that compares decoded bytes selects that existing wire policy explicitly. */ export function jwtVerifySignature(token: string, key: JwtVerificationKey | ((decoded: { header: Row; payload: Row }) => JwtVerificationKey), opts: JwtSignatureOptions = {}): JwtVerdict { let decoded: { header: Row; payload: Row }; try { decoded = jwtDecode(token, opts); } catch { return { valid: false, reason: 'malformed' }; } const selected = typeof key === 'function' ? key(decoded) : key; const [h, p, s] = token.split('.') as [string, string, string]; if ('secret' in selected) { if (decoded.header.alg !== selected.alg) return { valid: false, reason: 'unexpected_alg' }; const bytes = nodeCrypto.createHmac(digestOf(selected.alg), selected.secret).update(`${h}.${p}`).digest(); const expected = opts.hmacSignature === 'bytes' ? bytes : Buffer.from(base64url(bytes), 'utf8'); const given = opts.hmacSignature === 'bytes' ? fromBase64url(s) : Buffer.from(s, 'utf8'); if (given.length !== expected.length || !nodeCrypto.timingSafeEqual(given, expected)) return { valid: false, reason: 'bad_signature' }; return { valid: true, payload: decoded.payload }; } if (!['RS256', 'RS384', 'RS512', 'EdDSA'].includes(String(decoded.header.alg))) return { valid: false, reason: 'unexpected_alg' }; // a token naming a key the set does not hold matches none; one naming no key is tried against the set's only key const jwk = decoded.header.kid !== undefined ? selected.keys.find((k) => k.kid === decoded.header.kid) : selected.keys.length === 1 ? selected.keys[0] : undefined; if (!jwk) return { valid: false, reason: 'no_matching_key' }; if ((jwk.kty === 'OKP') !== (decoded.header.alg === 'EdDSA')) return { valid: false, reason: 'unexpected_alg' }; if (jwk.kty === 'OKP') { const edKey = nodeCrypto.createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, format: 'jwk' }); if (!nodeCrypto.verify(null, Buffer.from(`${h}.${p}`), edKey, fromBase64url(s))) return { valid: false, reason: 'bad_signature' }; return { valid: true, payload: decoded.payload }; } const verifier = nodeCrypto.createVerify(`RSA-SHA${String(decoded.header.alg).slice(2)}`); verifier.update(`${h}.${p}`); verifier.end(); const publicKey = nodeCrypto.createPublicKey({ key: { kty: 'RSA', n: jwk.n, e: jwk.e }, format: 'jwk' }); if (!verifier.verify(publicKey, fromBase64url(s))) return { valid: false, reason: 'bad_signature' }; return { valid: true, payload: decoded.payload }; } /** The JWKS that verifies every token a public key's pair signs. */ export function jwks(publicPem: string, kidPrefix?: string): Jwks { const jwk = nodeCrypto.createPublicKey(publicPem).export({ format: 'jwk' }) as { kty?: string; n?: string; e?: string; x?: string }; if (jwk.kty === 'OKP') return { keys: [{ kty: 'OKP', use: 'sig', alg: 'EdDSA', crv: 'Ed25519', kid: keyId(publicPem, kidPrefix), x: String(jwk.x) }] }; return { keys: [{ kty: 'RSA', use: 'sig', alg: 'RS256', kid: keyId(publicPem, kidPrefix), n: String(jwk.n), e: String(jwk.e) }] }; } /** An HMAC of a value, hex or base64 (a webhook's signature, a signed id): SHA-256 unless the vendor names another * (OAuth 1.0a's HMAC-SHA1). The secret is its text, or its bytes where the vendor keys with a decoded secret (Svix's * `whsec_` base64). */ export const hmac = (secret: string | Uint8Array, value: string | Uint8Array, encoding: 'hex' | 'base64' | 'base64url' = 'hex', algorithm: 'sha1' | 'sha256' | 'sha512' = 'sha256'): string => { const bytes = nodeCrypto.createHmac(algorithm, secret).update(value).digest(); return encoding === 'base64url' ? base64url(bytes) : bytes.toString(encoding); }; /** A SHA-256, hex (a key stored by its hash, a deterministic id). */ export const sha256 = (value: string): string => nodeCrypto.createHash('sha256').update(value).digest('hex'); /** A digest of a value in the algorithm and encoding a vendor names (GoTrue's SHA-224 token hashes, a PKCE challenge's * base64url SHA-256). */ export function digest(algorithm: 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512', value: string | Uint8Array, encoding: 'hex' | 'base64' | 'base64url' = 'hex'): string { const bytes = nodeCrypto.createHash(algorithm).update(value).digest(); return encoding === 'base64url' ? base64url(bytes) : bytes.toString(encoding); } // ── OAuth 1.0a (RFC 5849): the signature a request carries, which the vendor checks against the secrets it holds ────── /** RFC 3986 percent-encoding as RFC 5849 §3.6 uses it (unreserved: A-Z a-z 0-9 - . _ ~). */ export const oauth1Encode = (s: string): string => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); /** The `Authorization: OAuth k="v", …` header's parameters, decoded, in order; undefined when it is not one. */ export function oauth1Header(value: string | null | undefined): Array<[string, string]> | undefined { const m = value ? /^OAuth\s+(.*)$/is.exec(value.trim()) : null; if (!m) return undefined; const out: Array<[string, string]> = []; for (const part of m[1]!.split(',')) { const kv = /^\s*([^=\s]+)\s*=\s*"([^"]*)"\s*$/.exec(part); if (!kv) { if (part.trim() === '') continue; return undefined; } try { out.push([decodeURIComponent(kv[1]!), decodeURIComponent(kv[2]!)]); } catch { return undefined; } } return out; } /** The signature base string (RFC 5849 §3.4.1): the method, the base URL (no query) and the parameters signed, each * percent-encoded and sorted by name and value. */ export function oauth1BaseString(method: string, baseUrl: string, pairs: ReadonlyArray): string { const encoded = pairs.map(([k, v]) => [oauth1Encode(k), oauth1Encode(v)] as const).sort((a, b) => (a[0] === b[0] ? (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) : a[0] < b[0] ? -1 : 1)); return `${method.toUpperCase()}&${oauth1Encode(baseUrl)}&${oauth1Encode(encoded.map(([k, v]) => `${k}=${v}`).join('&'))}`; } /** The HMAC-SHA1 signature (RFC 5849 §3.4.2) over a base string, keyed by the consumer secret and the token secret. */ export const oauth1Signature = (base: string, consumerSecret: string, tokenSecret = ''): string => hmac(`${oauth1Encode(consumerSecret)}&${oauth1Encode(tokenSecret)}`, base, 'base64', 'sha1'); /** A digest of a value as its bytes (a key or an id drawn from a hash's bytes, a deterministic embedding). */ export function digestBytes(algorithm: 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512', value: string | Uint8Array): Uint8Array { return new Uint8Array(nodeCrypto.createHash(algorithm).update(value).digest()); } /** An MD5, hex (an object's ETag, as S3 and storage APIs give it); never a secret's protection. */ export const md5 = (value: string | Uint8Array): string => nodeCrypto.createHash('md5').update(value).digest('hex'); /** A version-4 UUID's layout over 32 hex digits. */ const uuidShape = (h: string): string => `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${'89ab'[Number.parseInt(h[16]!, 16) % 4]}${h.slice(17, 20)}-${h.slice(20, 32)}`; /** `count` characters of `alphabet`, drawn from the bytes `round` gives (round 0, 1, …), one character a byte; a byte * at or past `skipFrom` is skipped, so `256 - 256 % alphabet.length` draws evenly and 256 takes every byte. */ function draw(alphabet: string, count: number, bytesOf: (round: number) => Uint8Array, skipFrom = 256 - (256 % alphabet.length)): string { let out = ''; for (let round = 0; out.length < count; round += 1) { for (const byte of bytesOf(round)) { if (out.length === count) break; if (byte < skipFrom) out += alphabet[byte % alphabet.length]; } } return out; } /** A version-4-shaped UUID derived from `seed`: the same seed gives the same id every run (R9). */ export function uuidFrom(seed: string): string { return uuidShape(sha256(seed)); } /** `count` lowercase letters derived from `seed` (a 20-letter project ref, a slug's suffix), the same every run (every * byte taken, as the ids already minted from it were). */ export function lettersFrom(seed: string, count = 20): string { return draw('abcdefghijklmnopqrstuvwxyz', count, (round) => digestBytes('sha256', `${seed}:${round}`), 256); } /** `count` base62 characters (0-9A-Za-z) derived from `seed`, the same every run: the opaque tail of an id a vendor * writes in base62 (OpenAI's `call_unLAR8MvFNptuiZK6K6HCy5k`, 24 after its prefix). */ export function base62From(seed: string, count = 24): string { return draw(KEY_ALPHABETS.base62!, count, (round) => digestBytes('sha256', `${seed}:${round}`)); } /** A key's or an id's shape as the vendor writes it: `prefix`, a body of `alphabet` characters (`base62`, `hex` * lowercase, `base64url`, `digits`, `letters` lowercase, or the characters of a string given), `suffix`; `length` is the * whole value's, prefix and suffix included (Anthropic's `sk-ant-api03-…AA`, 108; Stripe's `sk_test_51…`; OpenAI's * `sk-proj-…`; a KSUID's 27 base62; a snowflake's digits after a nonzero prefix digit). `'uuid'` is a version-4 UUID. */ export type KeyFormat = { prefix?: string; length: number; alphabet: 'base62' | 'hex' | 'base64url' | 'digits' | 'letters' | (string & {}); suffix?: string } | 'uuid'; const KEY_ALPHABETS: Record = { base62: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', hex: '0123456789abcdef', base64url: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', digits: '0123456789', letters: 'abcdefghijklmnopqrstuvwxyz', }; /** A key in `format` drawn from HMAC-SHA256(`secret`, `label`): the same secret and label give the same key, and no one * without the secret can compute it. Each body character is an unbiased draw (a byte past the alphabet's last whole * multiple is skipped). */ export function keyFrom(secret: string, label: string, format: KeyFormat): string { if (format === 'uuid') return uuidShape(nodeCrypto.createHmac('sha256', secret).update(label).digest('hex')); const alphabet = KEY_ALPHABETS[format.alphabet] ?? format.alphabet; const prefix = format.prefix ?? '', suffix = format.suffix ?? ''; const count = format.length - prefix.length - suffix.length; if (!Number.isInteger(format.length) || count < 1) throw new Error(`a key's length (${format.length}) leaves no body after its prefix and suffix`); if (alphabet.length < 2 || alphabet.length > 256 || new Set(alphabet).size !== alphabet.length) throw new Error(`a key's alphabet must be base62, hex, base64url or 2 to 256 distinct characters, not ${JSON.stringify(format.alphabet)}`); return `${prefix}${draw(alphabet, count, (round) => nodeCrypto.createHmac('sha256', secret).update(`${label}:${round}`).digest())}${suffix}`; } /** Two strings compared in constant time. */ export function equalSecrets(a: string, b: string): boolean { const left = Buffer.from(a, 'utf8'); const right = Buffer.from(b, 'utf8'); return left.length === right.length && nodeCrypto.timingSafeEqual(left, right); } /** A key's type, from its PEM: the schemes the kernel signs with are the deterministic ones. */ function signingKey(privatePem: string): nodeCrypto.KeyObject { const key = nodeCrypto.createPrivateKey(privatePem); // ECDSA draws a random nonce for every signature, so the same write signs differently on every run: a World signs // with RSA (PKCS #1 v1.5) or Ed25519, whose signatures are functions of the key and the bytes if (key.asymmetricKeyType !== 'rsa' && key.asymmetricKeyType !== 'ed25519') throw new Error(`signWith: a ${key.asymmetricKeyType} key signs randomly; a World signs with an RSA or Ed25519 key`); return key; } /** Bytes signed with a private key (RSA with SHA-256, or Ed25519), in the encoding asked: a certificate's signature, * a transparency log's checkpoint. */ export function signWith(privatePem: string, data: string | Uint8Array, encoding: 'base64' | 'hex' | 'base64url' = 'base64'): string { const key = signingKey(privatePem); const bytes = nodeCrypto.sign(key.asymmetricKeyType === 'ed25519' ? null : 'sha256', typeof data === 'string' ? Buffer.from(data) : data, key); return encoding === 'base64url' ? base64url(bytes) : bytes.toString(encoding); } /** Whether a signature holds over bytes under a public key or a certificate's (PEM, or a certificate's DER): any * scheme a vendor uses (ECDSA, RSA, Ed25519), since verifying draws nothing. The digest is SHA-256 unless named. */ export function verifyWith(publicKey: string | Uint8Array, data: string | Uint8Array, signature: string | Uint8Array, opts: { digest?: 'sha256' | 'sha384' | 'sha512'; encoding?: 'base64' | 'hex' } = {}): boolean { try { const key = typeof publicKey !== 'string' || publicKey.includes('CERTIFICATE') ? new nodeCrypto.X509Certificate(typeof publicKey === 'string' ? publicKey : Buffer.from(publicKey)).publicKey : nodeCrypto.createPublicKey(publicKey); const sig = typeof signature === 'string' ? Buffer.from(signature, opts.encoding ?? 'base64') : signature; return nodeCrypto.verify(key.asymmetricKeyType === 'ed25519' ? null : (opts.digest ?? 'sha256'), typeof data === 'string' ? Buffer.from(data) : data, key, sig); } catch { return false; } } /** A public key's PEM and its DER (SubjectPublicKeyInfo), from a public or private key's PEM or a certificate. */ export function publicKeyOf(key: string): { pem: string; der: Uint8Array } { const k = key.includes('CERTIFICATE') ? new nodeCrypto.X509Certificate(key).publicKey : nodeCrypto.createPublicKey(key); return { pem: String(k.export({ type: 'spki', format: 'pem' })), der: new Uint8Array(k.export({ type: 'spki', format: 'der' })) }; } /** An X.509 certificate read (PEM or DER): its bytes, names, validity and key, and whether an issuer's key signed it; * undefined when it is not one. */ export function certificateOf(cert: string | Uint8Array): { der: Uint8Array; subject: string; issuer: string; subjectAltName: string | undefined; notBefore: string; notAfter: string; publicKey: { pem: string; der: Uint8Array }; issuedBy(issuer: string | Uint8Array): boolean } | undefined { try { const c = new nodeCrypto.X509Certificate(typeof cert === 'string' ? cert : Buffer.from(cert)); return { der: new Uint8Array(c.raw), subject: c.subject, issuer: c.issuer, subjectAltName: c.subjectAltName, notBefore: new Date(c.validFrom).toISOString(), notAfter: new Date(c.validTo).toISOString(), publicKey: publicKeyOf(c.toString()), issuedBy: (issuer) => { try { return c.verify(new nodeCrypto.X509Certificate(typeof issuer === 'string' ? issuer : Buffer.from(issuer)).publicKey); } catch { return false; } }, }; } catch { return undefined; } } /** What a handler signs and hashes with: `ctx.crypto`. */ export const handlerCrypto = { jwtSign, jwtSignClaims, jwtVerify, jwtVerifySignature, jwtDecode, jwks, keyId, hmac, sha256, md5, digest, uuidFrom, lettersFrom, base62From, equalSecrets, sealedBoxKeyPair, sealedBoxOpen, signWith, verifyWith, publicKeyOf, certificateOf } as const; export type HandlerCrypto = typeof handlerCrypto; /** A [KSUID](https://github.com/segmentio/ksuid) as 27 base62 characters (0-9A-Za-z, most significant first): `seconds` * past KSUID's epoch (1400000000) in four bytes, then `n` in four, then twelve bytes derived from `seed`, so KSUIDs * made in one second sort by `n`, at `width` characters (27 unless a vendor's id is longer or shorter). Deterministic: * the same arguments give the same id. */ export function ksuidFrom(seconds: number, n: number, seed: string, width = 27): string { const bytes = new Uint8Array(20); const view = new DataView(bytes.buffer); view.setUint32(0, Math.max(0, seconds - 1_400_000_000) >>> 0); view.setUint32(4, n >>> 0); const tail = sha256(seed); for (let i = 0; i < 12; i++) bytes[8 + i] = parseInt(tail.slice(i * 2, i * 2 + 2), 16); const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; let value = 0n; for (const b of bytes) value = (value << 8n) | BigInt(b); let out = ''; while (value > 0n) { out = ALPHABET[Number(value % 62n)]! + out; value /= 62n; } const full = out.padStart(27, '0'); // another width than KSUID's 27 (a vendor's id of 24 or 29 characters): its first `width` characters, which keep the // instant and the mint count (and so the order) from 11 on, or more base62 characters derived from the seed after them return width <= 27 ? full.slice(0, width) : `${full}${base62From(`${seed}:ksuid`, width - 27)}`; }