UNPKG

inngest

Version:

Official SDK for Inngest.com. Inngest is the reliability layer for modern applications. Inngest combines durable execution, events, and queues into a zero-infra platform with built-in observability.

64 lines (62 loc) 2.37 kB
import { logOnce } from "./log.js"; import canonicalize from "canonicalize"; import hashjs from "hash.js"; //#region src/helpers/net.ts const { hmac, sha256 } = hashjs; /** * Send an HTTP request with the given signing key. If the response is a 401 or * 403, then try again with the fallback signing key */ async function fetchWithAuthFallback({ authToken, authTokenFallback, fetch, options, url }) { let res = await fetch(url, { ...options, headers: { ...options?.headers, Authorization: `Bearer ${authToken}` } }); if ([401, 403].includes(res.status) && authTokenFallback) res = await fetch(url, { ...options, headers: { ...options?.headers, Authorization: `Bearer ${authTokenFallback}` } }); return res; } function signWithHashJs(data, signingKey, ts) { const encoded = typeof data === "string" ? data : canonicalize(data); return hmac(sha256, signingKey.replace(/signkey-\w+-/, "")).update(encoded).update(ts).digest("hex"); } const cryptoKeyCache = /* @__PURE__ */ new Map(); async function signWithNative(subtle, data, signingKey, ts) { const encoded = typeof data === "string" ? data : canonicalize(data); const key = signingKey.replace(/signkey-\w+-/, ""); let cryptoKey = cryptoKeyCache.get(key); if (!cryptoKey) { cryptoKey = await subtle.importKey("raw", new TextEncoder().encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); cryptoKeyCache.set(key, cryptoKey); } const signature = await subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(encoded + ts)); return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join(""); } /** * Sign data with a signing key using HMAC-SHA256. * Uses native crypto.subtle when available, falls back to hash.js. */ async function signDataWithKey(data, signingKey, ts, logger) { const subtle = globalThis.crypto?.subtle; logOnce(logger, "debug", "crypto-implementation", subtle ? "Using native Web Crypto for request signing" : "Using hash.js fallback for request signing (native crypto unavailable)"); if (subtle) try { return await signWithNative(subtle, data, signingKey, ts); } catch (err) { logger.debug({ err }, "Native crypto failed, falling back to hash.js"); } return signWithHashJs(data, signingKey, ts); } //#endregion export { fetchWithAuthFallback, signDataWithKey }; //# sourceMappingURL=net.js.map