UNPKG

@livepeer/core

Version:

Livepeer UI Kit's core vanilla JS library.

179 lines (173 loc) 5.73 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/crypto.ts var crypto_exports = {}; __export(crypto_exports, { importPKCS8: () => importPKCS8, signAccessJwt: () => signAccessJwt }); module.exports = __toCommonJS(crypto_exports); // src/utils/string.ts var b64Encode = (input) => { try { if (typeof window !== "undefined" && "btoa" in window) { return window?.btoa?.(input) ?? null; } return Buffer?.from(input, "binary")?.toString("base64") ?? null; } catch (e) { return null; } }; var b64Decode = (input) => { try { if (typeof window !== "undefined" && "atob" in window) { return window?.atob?.(input) ?? null; } return Buffer?.from(input, "base64")?.toString("binary") ?? null; } catch (e) { return null; } }; var b64UrlEncode = (input) => { return escapeInput(b64Encode(input)); }; var b64UrlDecode = (input) => { const unescaped = unescapeInput(input); if (unescaped) { return b64Decode(unescaped); } return null; }; var unescapeInput = (input) => { return input ? (input + "===".slice((input.length + 3) % 4)).replace(/-/g, "+").replace(/_/g, "/") : null; }; var escapeInput = (input) => { return input?.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "") ?? null; }; // src/crypto/getSubtleCrypto.ts var getSubtleCrypto = async () => { if (typeof crypto !== "undefined" && crypto?.subtle) { return crypto.subtle; } if (typeof globalThis?.crypto !== "undefined" && globalThis?.crypto?.subtle) { return globalThis.crypto.subtle; } try { const nodeCrypto = await import("crypto"); return nodeCrypto.webcrypto.subtle; } catch (error) { if (typeof window !== "undefined") { if (window?.crypto?.subtle) { return window.crypto.subtle; } throw new Error( "Browser is not in a secure context (HTTPS), cannot use SubtleCrypto: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto" ); } throw new Error( `Failed to import Node.js crypto module: ${error?.message ?? ""}` ); } }; // src/crypto/ecdsa.ts var signEcdsaSha256 = async (privateKey, data) => { const subtleCrypto = await getSubtleCrypto(); return subtleCrypto.sign( { name: "ECDSA", hash: { name: "SHA-256" } }, privateKey, data ); }; // src/crypto/pkcs8.ts var importPKCS8 = async (pkcs8) => { if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { throw new TypeError('"pkcs8" must be PKCS8 formatted string'); } const privateKeyContents = b64UrlDecode( pkcs8.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "") ); if (!privateKeyContents) { throw new TypeError("Could not base64 decode private key contents."); } const subtleCrypto = await getSubtleCrypto(); return subtleCrypto.importKey( "pkcs8", new Uint8Array(privateKeyContents?.split("").map((c) => c.charCodeAt(0))), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"] ); }; // src/crypto/jwt.ts var signAccessJwt = async (options) => { const privateKey = typeof options.privateKey === "string" ? await importPKCS8(b64Decode(options.privateKey) ?? options.privateKey) : options.privateKey; if (!privateKey) { throw new Error("Error importing private key."); } const issuedAtSec = Date.now() / 1e3; const expirationSec = issuedAtSec + (options.expiration ?? 86400); const payload = { action: "pull", iss: options.issuer, pub: options.publicKey, sub: options.playbackId, video: "none", exp: Number(expirationSec.toFixed(0)), iat: Number(issuedAtSec.toFixed(0)), ...options.custom ? { custom: { ...options.custom } } : {} }; const header = { alg: "ES256", typ: "JWT" }; const base64Header = b64UrlEncode(JSON.stringify(header)); const base64Payload = b64UrlEncode(JSON.stringify(payload)); const body = `${base64Header}.${base64Payload}`; const signatureBuffer = await signEcdsaSha256(privateKey, Buffer.from(body)); const signature = b64UrlEncode( String.fromCharCode(...new Uint8Array(signatureBuffer)) ); return `${base64Header}.${base64Payload}.${signature}`; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { importPKCS8, signAccessJwt }); //# sourceMappingURL=index.cjs.map