UNPKG

@ragnaraven/zitadel-node-dual

Version:

Library for API access to ZITADEL with modern ES import syntax. Works everywhere - NestJS, Node.js, any TypeScript environment. No more require()!

175 lines 6.43 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); var service_account_exports = {}; __export(service_account_exports, { ServiceAccount: () => ServiceAccount }); module.exports = __toCommonJS(service_account_exports); var import_jose = require("jose"); var import_node_rsa = __toESM(require("node-rsa")); var import_openid_client = require("openid-client"); class ServiceAccount { /** * Create a new service account * * @param userId The user ID of the service account. * @param keyId The ID of the RSA key. * @param key The private RSA key of the service account. Used to sign the JWT. * * @throws {Error} If the userId is not defined. * @throws {Error} If the keyId is not defined. * @throws {Error} If the key is not defined. */ constructor(userId, keyId, key) { this.userId = userId; this.keyId = keyId; this.key = key; if (!userId) { throw new Error("userId is required"); } if (!keyId) { throw new Error("keyId is required"); } if (!key) { throw new Error("key is required"); } } /** * The type of the object. */ static type = "serviceaccount"; /** * Create an service account from a JSON object. * * @param json The JSON object. * @returns A service account. * * @throws {Error} If the constructor throws an error. * @throws {Error} If the passed JSON cannot be properly destructed. */ static fromJson({ userId, key, keyId }) { return new ServiceAccount(userId, keyId, key); } /** * Create an service account from a JSON string. * The string is parsed using `JSON.parse`. * * @param jsonString The JSON string. * @returns A service account. * * @throws {Error} If the constructor throws an error. * @throws {Error} If the passed JSON cannot be properly parsed. * @throws {Error} If the passed JSON cannot be properly destructed. */ static fromJsonString(jsonString) { return ServiceAccount.fromJson(JSON.parse(jsonString)); } /** * Create a JSON object from the application. * * @returns A JSON object. */ toJson() { return { type: ServiceAccount.type, userId: this.userId, keyId: this.keyId, key: this.key }; } /** * Authenticates the service account against the provided audience (or issuer) to * fetch an access token. To authenticate with special options, use the * options parameter. * * The function returns an access token that can be sent * to authenticate any request as the given service account. The access token * is valid for 60 minutes. * * @param audience The audience to authenticate against. * @param options The options to use for authentication. * * @returns An access token that is valid for 60 minutes. * * @example Just authenticate the service account against ZITADEL * ```typescript * const sa = ServiceAccount.fromJson(serviceAccountJson); * const token = await sa.authenticate('https://issuer.zitadel.ch'); * ``` * * @example Authenticate the service account against ZITADEL with ZITADEL API access * ```typescript * const sa = ServiceAccount.fromJson(serviceAccountJson); * const token = await sa.authenticate('https://issuer.zitadel.ch', { apiAccess: true }); * ``` */ async authenticate(audience, options) { const { default: axios } = await import("axios"); const issuer = await import_openid_client.Issuer.discover(audience); const tokenEndpoint = issuer.metadata.token_endpoint ?? "N/A"; const jwt = await this.getSignedJwt(audience); const response = await axios.post( tokenEndpoint, new URLSearchParams({ assertion: jwt, grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", scope: createScopes(options ?? {}) }) ); if (response.status > 299) { throw new Error(`Authentication failed with status ${response.status}: ${response.statusText}.`); } if (!response.data.access_token) { throw new Error(`Authentication failed. No access token returned.`); } return response.data.access_token; } async getSignedJwt(audience) { const rsa = new import_node_rsa.default(this.key); const key = await (0, import_jose.importPKCS8)(rsa.exportKey("pkcs8-private-pem"), "RSA256"); return await new import_jose.SignJWT({}).setProtectedHeader({ kid: this.keyId, alg: "RS256" }).setIssuedAt().setExpirationTime("1h").setAudience(audience).setIssuer(this.userId).setSubject(this.userId).sign(key); } } const createScopes = ({ additionalScopes = [], apiAccess = false, projectAudiences = [], roles = [] }) => [ "openid", apiAccess ? "urn:zitadel:iam:org:project:id:zitadel:aud" : void 0, ...additionalScopes, ...roles.map((r) => `urn:zitadel:iam:org:project:role:${r}`), ...projectAudiences.map((a) => `urn:zitadel:iam:org:project:id:${a}:aud`) ].filter(Boolean).join(" "); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ServiceAccount }); //# sourceMappingURL=service-account.js.map