import * as jose from "jose"; import bs58 from "bs58"; import crypto from "crypto"; import { RippinClient } from "../client"; import { RippinAuthPlugin } from "./authPlugin"; /** * Authentication plugin using api keys. * * RippinApiAuth is intended to be used in a NodeJS environment. */ export class RippinApiAuth implements RippinAuthPlugin { _rippin: RippinClient; apiKey: string; decodedApiKey: Uint8Array; decodedApiSecret: Uint8Array; constructor(apiKey: string, apiSecret: string) { this.apiKey = apiKey; this.decodedApiKey = bs58.decode(apiKey); this.decodedApiSecret = bs58.decode(apiSecret); } init = (_rippin: RippinClient) => { this._rippin = _rippin; _rippin.auth = () => this; }; createHeaders = async () => { const pubkeyBuffer = Buffer.from(this.decodedApiKey); const privateKeyBuffer = Buffer.from(this.decodedApiSecret); const pk = crypto.createPrivateKey({ key: { kty: "OKP", alg: "EdDSA", crv: "Ed25519", x: pubkeyBuffer.toString("base64url"), d: privateKeyBuffer.toString("base64url"), }, format: "jwk", }); const unsignedSJWT = new jose.SignJWT({ projectId: this._rippin.projectId, }) .setProtectedHeader({ alg: "EdDSA" }) .setAudience("rippin.io") .setIssuedAt() .setIssuer(this.apiKey) .setExpirationTime("2m"); const token = await unsignedSJWT.sign(pk); return { ...(this.apiKey ? { "X-Public-Key": this.apiKey, Authorization: `Bearer ${token}`, } : {}), }; }; } declare module "../client" { interface RippinClient { auth(): RippinAuthPlugin; } }