@workos-inc/node12.4.0428.0 kB
// src/common/crypto/crypto-provider.ts
/**
* Interface encapsulating the various crypto computations used by the library,
* allowing pluggable underlying crypto implementations.
*/
var CryptoProvider = class {
encoder = new TextEncoder();
};
// src/common/crypto/subtle-crypto-provider.ts
/**
* `CryptoProvider which uses the SubtleCrypto interface of the Web Crypto API.
*
* This only supports asynchronous operations.
*/
var SubtleCryptoProvider = class extends CryptoProvider {
subtleCrypto;
constructor(subtleCrypto) {
super();
this.subtleCrypto = subtleCrypto || crypto.subtle;
}
computeHMACSignature(_payload, _secret) {
throw new Error("SubleCryptoProvider cannot be used in a synchronous context.");
}
/** @override */
async computeHMACSignatureAsync(payload, secret) {
const encoder = new TextEncoder();
const key = await this.subtleCrypto.importKey("raw", encoder.encode(secret), {
name: "HMAC",
hash: { name: "SHA-256" }
}, false, ["sign"]);
const signatureBuffer = await this.subtleCrypto.sign("hmac", key, encoder.encode(payload));
const signatureBytes = new Uint8Array(signatureBuffer);
const signatureHexCodes = new Array(signatureBytes.length);
for (let i = 0; i < signatureBytes.length; i++) signatureHexCodes[i] = byteHexMapping[signatureBytes[i]];
return signatureHexCodes.join("");
}
/** @override */
async secureCompare(stringA, stringB) {
const bufferA = this.encoder.encode(stringA);
const bufferB = this.encoder.encode(stringB);
if (bufferA.length !== bufferB.length) return false;
const algorithm = {
name: "HMAC",
hash: "SHA-256"
};
const key = await crypto.subtle.generateKey(algorithm, false, ["sign", "verify"]);
const hmac = await crypto.subtle.sign(algorithm, key, bufferA);
return await crypto.subtle.verify(algorithm, key, hmac, bufferB);
}
async encrypt(plaintext, key, iv, aad) {
const actualIv = iv || crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
const cryptoKey = await this.subtleCrypto.importKey("raw", key, { name: "AES-GCM" }, false, ["encrypt"]);
const encryptParams = {
name: "AES-GCM",
iv: actualIv
};
if (aad) encryptParams.additionalData = aad;
const encryptedData = await this.subtleCrypto.encrypt(encryptParams, cryptoKey, plaintext);
const encryptedBytes = new Uint8Array(encryptedData);
const tagStart = encryptedBytes.length - 16;
const tag = encryptedBytes.slice(tagStart);
return {
ciphertext: encryptedBytes.slice(0, tagStart),
iv: actualIv,
tag
};
}
async decrypt(ciphertext, key, iv, tag, aad) {
const combinedData = new Uint8Array(ciphertext.length + tag.length);
combinedData.set(ciphertext, 0);
combinedData.set(tag, ciphertext.length);
const cryptoKey = await this.subtleCrypto.importKey("raw", key, { name: "AES-GCM" }, false, ["decrypt"]);
const decryptParams = {
name: "AES-GCM",
iv
};
if (aad) decryptParams.additionalData = aad;
const decryptedData = await this.subtleCrypto.decrypt(decryptParams, cryptoKey, combinedData);
return new Uint8Array(decryptedData);
}
randomBytes(length) {
const bytes = new Uint8Array(length);
crypto.getRandomValues(bytes);
return bytes;
}
randomUUID() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
const bytes = this.randomBytes(16);
bytes[6] = bytes[6] & 15 | 64;
bytes[8] = bytes[8] & 63 | 128;
const hex = Array.from(bytes, (b) => byteHexMapping[b]).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
};
const byteHexMapping = new Array(256);
for (let i = 0; i < byteHexMapping.length; i++) byteHexMapping[i] = i.toString(16).padStart(2, "0");
/**
* Upper bound on a server-provided `Retry-After` delay. Caps how long a
* single retry can sleep so an aggressive proxy or an HTTP-date far in the
* future can't hang the caller indefinitely.
*/
const MAXIMUM_RETRY_AFTER_TIME_IN_MILLISECONDS = 6e4;
var HttpClient = class HttpClient {
baseURL;
options;
MAX_RETRY_ATTEMPTS;
BACKOFF_MULTIPLIER = 1.5;
MINIMUM_SLEEP_TIME_IN_MILLISECONDS = 500;
MAXIMUM_SLEEP_TIME_IN_MILLISECONDS = 8e3;
RETRY_STATUS_CODES = [
408,
429,
500,
502,
503,
504
];
constructor(baseURL, options) {
this.baseURL = baseURL;
this.options = options;
this.MAX_RETRY_ATTEMPTS = options?.maxRetries ?? 3;
}
static getResourceURL(baseURL, path, params) {
HttpClient.assertNoDotSegments(path);
const queryString = HttpClient.getQueryString(params);
return new URL([path, queryString].filter(Boolean).join("?"), baseURL).toString();
}
/**
* Reject request paths that contain a single-dot or double-dot segment.
*
* SDK path templates never contain such segments themselves, but a
* caller-supplied identifier interpolated with bare `encodeURIComponent`
* (the form the generated modules use) passes `.` and `..` through
* unchanged, and the WHATWG `URL` parser then collapses them, retargeting
* the request to a different endpoint (for example
* `/organizations/../api_keys` resolves to `/api_keys`). The parser also
* treats the percent-encoded forms (`%2e`, case-insensitive) as dots, so
* those are matched as well. Encoded values never trip this check because
* `encodeURIComponent` turns `%` into `%25` and `/` into `%2F`, keeping
* each identifier inside its own segment. Fail closed before any request
* is built.
*/
static assertNoDotSegments(path) {
const pathOnly = path.split(/[?#]/, 1)[0];
for (const segment of pathOnly.split("/")) {
const normalized = segment.replace(/%2e/gi, ".");
if (normalized === "." || normalized === "..") throw new TypeError(`Invalid request path "${path}": a path segment must not be "." or "..".`);
}
}
static getQueryString(queryObj) {
if (!queryObj) return void 0;
const sanitizedQueryObj = {};
Object.entries(queryObj).forEach(([param, value]) => {
if (value !== null && value !== void 0 && value !== "") sanitizedQueryObj[param] = value;
});
return new URLSearchParams(sanitizedQueryObj).toString();
}
static getContentTypeHeader(entity) {
if (entity instanceof URLSearchParams) return { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" };
}
static getBody(entity) {
if (entity === null || entity instanceof URLSearchParams) return entity;
return JSON.stringify(entity);
}
/**
* Generate a random idempotency key used to make retried write requests
* safe. Mirrors the behavior of the other WorkOS SDKs (Kotlin, Go), which
* attach an `Idempotency-Key` header to POST requests that did not already
* specify one, so a retried request is not applied more than once.
*/
static generateIdempotencyKey() {
return `retry-${globalThis.crypto.randomUUID()}`;
}
/**
* Parse a `Retry-After` header value into milliseconds. Supports both the
* delay-seconds form (e.g. `120`) and the HTTP-date form. The result is
* capped at {@link MAXIMUM_RETRY_AFTER_TIME_IN_MILLISECONDS}. Returns
* `null` when the value is absent or unparseable so the caller falls back
* to the computed exponential backoff.
*/
static parseRetryAfter(headerValue) {
if (headerValue == null) return null;
const trimmed = headerValue.trim();
if (trimmed === "") return null;
if (/^\d+$/.test(trimmed)) return Math.min(Number(trimmed) * 1e3, MAXIMUM_RETRY_AFTER_TIME_IN_MILLISECONDS);
const asDate = Date.parse(trimmed);
if (!Number.isNaN(asDate)) {
const delta = asDate - Date.now();
return delta < 0 ? 0 : Math.min(delta, MAXIMUM_RETRY_AFTER_TIME_IN_MILLISECONDS);
}
return null;
}
getSleepTimeInMilliseconds(retryAttempt) {
return Math.min(this.MINIMUM_SLEEP_TIME_IN_MILLISECONDS * Math.pow(this.BACKOFF_MULTIPLIER, retryAttempt), this.MAXIMUM_SLEEP_TIME_IN_MILLISECONDS) * (Math.random() + .5);
}
sleep = (retryAttempt, retryAfterMs) => new Promise((resolve) => setTimeout(resolve, retryAfterMs != null ? retryAfterMs : this.getSleepTimeInMilliseconds(retryAttempt)));
};
var HttpClientResponse = class {
_statusCode;
_headers;
constructor(statusCode, headers) {
this._statusCode = statusCode;
this._headers = headers;
}
getStatusCode() {
return this._statusCode;
}
getHeaders() {
return this._headers;
}
};
var HttpClientError = class extends Error {
name = "HttpClientError";
message = "The request could not be completed.";
response;
constructor({ message, response }) {
super(message);
this.message = message;
this.response = response;
}
};
// src/common/exceptions/parse-error.ts
var ParseError = class extends Error {
name = "ParseError";
status = 500;
rawBody;
rawStatus;
requestID;
rawHeaders;
constructor({ message, rawBody, rawStatus, requestID, rawHeaders }) {
super(message);
this.rawBody = rawBody;
this.rawStatus = rawStatus;
this.requestID = requestID;
this.rawHeaders = rawHeaders;
}
};
// src/common/net/fetch-client.ts
const DEFAULT_FETCH_TIMEOUT = 6e4;
var FetchHttpClient = class FetchHttpClient extends HttpClient {
baseURL;
options;
_fetchFn;
constructor(baseURL, options, fetchFn) {
super(baseURL, options);
this.baseURL = baseURL;
this.options = options;
if (!fetchFn) {
if (!globalThis.fetch) throw new Error("Fetch function not defined in the global scope and no replacement was provided.");
fetchFn = globalThis.fetch;
}
this._fetchFn = fetchFn.bind(globalThis);
}
async get(path, options) {
const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
return await this.fetchRequestWithRetry(resourceURL, "GET", null, options.headers, options.maxRetries, options.signal);
}
async post(path, entity, options) {
const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
return await this.fetchRequestWithRetry(resourceURL, "POST", HttpClient.getBody(entity), {
...HttpClient.getContentTypeHeader(entity),
...options.headers
}, options.maxRetries, options.signal);
}
async put(path, entity, options) {
const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
return await this.fetchRequestWithRetry(resourceURL, "PUT", HttpClient.getBody(entity), {
...HttpClient.getContentTypeHeader(entity),
...options.headers
}, options.maxRetries, options.signal);
}
async patch(path, entity, options) {
const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
return await this.fetchRequestWithRetry(resourceURL, "PATCH", HttpClient.getBody(entity), {
...HttpClient.getContentTypeHeader(entity),
...options.headers
}, options.maxRetries, options.signal);
}
async delete(path, options) {
const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
return await this.fetchRequestWithRetry(resourceURL, "DELETE", null, options.headers, options.maxRetries, options.signal);
}
async deleteWithBody(path, entity, options) {
const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
return await this.fetchRequestWithRetry(resourceURL, "DELETE", HttpClient.getBody(entity), {
...HttpClient.getContentTypeHeader(entity),
...options.headers
}, options.maxRetries, options.signal);
}
async fetchRequest(url, method, body, headers, signal) {
signal?.throwIfAborted();
const requestBody = body || (method === "POST" || method === "PUT" || method === "PATCH" ? "" : void 0);
const { "User-Agent": userAgent } = this.options?.headers || {};
const timeout = this.options?.timeout ?? DEFAULT_FETCH_TIMEOUT;
const abortController = new AbortController();
const timeoutId = setTimeout(() => {
abortController.abort();
}, timeout);
const abortRequest = () => abortController.abort();
signal?.addEventListener("abort", abortRequest, { once: true });
const release = () => {
clearTimeout(timeoutId);
signal?.removeEventListener("abort", abortRequest);
};
const abortError = (responseHeaders) => signal?.aborted ? signal.reason : new HttpClientError({
message: `Request timeout after ${timeout}ms`,
response: {
status: 408,
headers: responseHeaders ?? new Headers(),
data: { error: "Request timeout" }
}
});
let res;
let redirected = false;
try {
res = await this._fetchFn(url, {
method,
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
...this.options?.headers,
...headers,
"User-Agent": (userAgent || "workos-node").toString()
},
body: requestBody,
signal: abortController.signal,
redirect: "manual"
});
if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") {
clearTimeout(timeoutId);
redirected = true;
const location = res.headers.get("Location");
const message = `WorkOS API responded with ${res.type === "opaqueredirect" ? "an opaque redirect" : `a redirect (${res.status}${location ? ` to ${location}` : ""})`}. Redirects are not followed; check the apiHostname, port and https options.`;
throw new HttpClientError({
message,
response: {
status: res.status,
headers: res.headers,
data: { message }
}
});
}
if (!res.ok) {
const requestID = res.headers.get("X-Request-ID") ?? "";
const rawBody = await res.text();
release();
let responseJson;
try {
responseJson = JSON.parse(rawBody);
} catch (error) {
if (error instanceof SyntaxError) throw new ParseError({
message: error.message,
rawBody,
requestID,
rawStatus: res.status,
rawHeaders: res.headers
});
throw error;
}
throw new HttpClientError({
message: res.statusText,
response: {
status: res.status,
headers: res.headers,
data: responseJson
}
});
}
const response = res;
const rawBody = (async () => {
try {
return await response.text();
} catch (error) {
throw abortController.signal.aborted ? abortError(response.headers) : error;
} finally {
release();
}
})();
rawBody.catch(() => void 0);
return new FetchHttpClientResponse(res, rawBody);
} catch (error) {
release();
if (abortController.signal.aborted) throw abortError(res?.headers);
throw error;
} finally {
if (redirected) abortController.abort();
}
}
async fetchRequestWithRetry(url, method, body, headers, maxRetries, signal) {
const maxRetryAttempts = maxRetries ?? this.MAX_RETRY_ATTEMPTS;
const requestHeaders = FetchHttpClient.withIdempotencyKey(method, headers, maxRetryAttempts);
let response;
let retryAttempts = 1;
const makeRequest = async () => {
let requestError = null;
let failed = false;
try {
response = await this.fetchRequest(url, method, body, requestHeaders, signal);
} catch (e) {
requestError = e;
failed = true;
}
if (!signal?.aborted && this.shouldRetryRequest(requestError, retryAttempts, maxRetryAttempts)) {
retryAttempts++;
await this.sleep(retryAttempts, FetchHttpClient.getRetryAfterMs(requestError));
return makeRequest();
}
if (failed) throw requestError;
return response;
};
return makeRequest();
}
shouldRetryRequest(requestError, retryAttempt, maxRetryAttempts) {
if (retryAttempt > maxRetryAttempts) return false;
if (requestError != null) {
if (requestError instanceof TypeError) return true;
if (requestError instanceof HttpClientError && this.RETRY_STATUS_CODES.includes(requestError.response.status)) return true;
if (requestError instanceof ParseError && this.RETRY_STATUS_CODES.includes(requestError.rawStatus)) return true;
}
return false;
}
static withIdempotencyKey(method, headers, maxRetryAttempts) {
if (method !== "POST" || maxRetryAttempts <= 0 || FetchHttpClient.hasHeader(headers, "Idempotency-Key")) return headers;
return {
...headers,
"Idempotency-Key": HttpClient.generateIdempotencyKey()
};
}
static hasHeader(headers, name) {
if (!headers) return false;
const target = name.toLowerCase();
return Object.keys(headers).some((key) => key.toLowerCase() === target);
}
static getRetryAfterMs(requestError) {
let headers;
if (requestError instanceof HttpClientError) headers = requestError.response?.headers;
else if (requestError instanceof ParseError) headers = requestError.rawHeaders;
else return null;
let value;
if (headers && typeof headers.get === "function") value = headers.get("Retry-After");
else if (headers && typeof headers === "object") value = headers["Retry-After"] ?? headers["retry-after"];
return HttpClient.parseRetryAfter(value);
}
};
var FetchHttpClientResponse = class FetchHttpClientResponse extends HttpClientResponse {
_res;
_rawBody;
constructor(res, rawBody) {
super(res.status, FetchHttpClientResponse._transformHeadersToObject(res.headers));
this._res = res;
this._rawBody = rawBody;
}
getRawResponse() {
return this._res;
}
async toJSON() {
const rawBody = await this._rawBody;
if (!this._res.headers.get("content-type")?.includes("application/json")) return null;
try {
return JSON.parse(rawBody);
} catch (error) {
if (error instanceof SyntaxError) throw new ParseError({
message: error.message,
rawBody,
rawStatus: this._res.status,
requestID: this._res.headers.get("X-Request-ID") ?? ""
});
throw error;
}
}
static _transformHeadersToObject(headers) {
const headersObj = {};
for (const entry of Object.entries(headers)) {
if (!Array.isArray(entry) || entry.length !== 2) throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");
headersObj[entry[0]] = entry[1];
}
return headersObj;
}
};
// src/common/crypto/decode-payload.ts
function isBinaryPayload(payload) {
return ArrayBuffer.isView(payload) || Object.prototype.toString.call(payload) === "[object ArrayBuffer]";
}
function decodePayloadToString(payload) {
if (typeof payload === "string") return payload;
if (isBinaryPayload(payload)) {
const bytes = Object.prototype.toString.call(payload) === "[object ArrayBuffer]" ? new Uint8Array(payload) : payload;
return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
}
return JSON.stringify(payload);
}
// src/common/exceptions/api-key-required.exception.ts
var ApiKeyRequiredException = class extends Error {
status = 403;
name = "ApiKeyRequiredException";
path;
constructor(path) {
super(`API key required for "${path}". For server-side apps, initialize with: new WorkOS("sk_..."). For browser/mobile/CLI apps, use authenticateWithCodeAndVerifier() and authenticateWithRefreshToken() which work without an API key.`);
this.path = path;
}
};
// src/common/exceptions/generic-server.exception.ts
var GenericServerException = class extends Error {
status;
rawData;
requestID;
name = "GenericServerException";
message = "The request could not be completed.";
code;
constructor(status, message, rawData, requestID) {
super();
this.status = status;
this.rawData = rawData;
this.requestID = requestID;
if (message) this.message = message;
this.code = rawData.code;
}
};
// src/common/exceptions/authentication.exception.ts
const AUTHENTICATION_ERROR_CODES = /* @__PURE__ */ new Set([
"email_verification_required",
"organization_selection_required",
"mfa_enrollment",
"mfa_challenge",
"mfa_verification",
"radar_email_challenge",
"radar_sms_challenge",
"sso_required"
]);
function parseAuthenticationErrorCode(value) {
if (typeof value !== "string") return;
if (!AUTHENTICATION_ERROR_CODES.has(value)) return;
return value;
}
function getAuthenticationErrorCode(data) {
return parseAuthenticationErrorCode(data.code) ?? parseAuthenticationErrorCode(data.error);
}
function isAuthenticationErrorData(data) {
return getAuthenticationErrorCode(data) !== void 0;
}
var AuthenticationException = class extends GenericServerException {
rawData;
name = "AuthenticationException";
code;
pendingAuthenticationToken;
radarChallengeId;
constructor(status, rawData, requestID) {
const code = getAuthenticationErrorCode(rawData);
super(status, rawData.message ?? rawData.error_description, rawData, requestID);
this.rawData = rawData;
this.code = code;
this.pendingAuthenticationToken = rawData.pending_authentication_token;
this.radarChallengeId = rawData.radar_challenge_id;
}
};
// src/common/exceptions/bad-request.exception.ts
var BadRequestException = class extends Error {
status = 400;
name = "BadRequestException";
message = "Bad request";
code;
errors;
requestID;
constructor({ code, errors, message, requestID }) {
super();
this.requestID = requestID;
if (message) this.message = message;
if (code) this.code = code;
if (errors) this.errors = errors;
}
};
// src/common/exceptions/conflict.exception.ts
var ConflictException = class extends Error {
status = 409;
name = "ConflictException";
requestID;
code;
constructor({ error, message, requestID, code }) {
super();
this.requestID = requestID;
if (message) this.message = message;
else if (error) this.message = `Error: ${error}`;
else this.message = `A conflict has occurred on the server.`;
this.code = code;
}
};
// src/common/exceptions/no-api-key-provided.exception.ts
var NoApiKeyProvidedException = class extends Error {
status = 500;
name = "NoApiKeyProvidedException";
message = "Missing API key. Pass it to the constructor (new WorkOS(\"sk_test_Sz3IQjepeSWaI4cMS4ms4sMuU\")) or define it in the WORKOS_API_KEY environment variable.";
};
// src/common/exceptions/not-found.exception.ts
var NotFoundException = class extends Error {
status = 404;
name = "NotFoundException";
message;
code;
requestID;
constructor({ code, message, path, requestID }) {
super();
this.code = code;
this.message = message ?? `The requested path '${path}' could not be found.`;
this.requestID = requestID;
}
};
// src/common/exceptions/oauth.exception.ts
var OauthException = class extends Error {
status;
requestID;
error;
errorDescription;
rawData;
name = "OauthException";
constructor(status, requestID, error, errorDescription, rawData) {
super();
this.status = status;
this.requestID = requestID;
this.error = error;
this.errorDescription = errorDescription;
this.rawData = rawData;
if (error && errorDescription) this.message = `Error: ${error}\nError Description: ${errorDescription}`;
else if (error) this.message = `Error: ${error}`;
else this.message = `An error has occurred.`;
}
};
// src/common/exceptions/rate-limit-exceeded.exception.ts
var RateLimitExceededException = class extends GenericServerException {
retryAfter;
name = "RateLimitExceededException";
constructor(message, requestID, retryAfter) {
super(429, message, {}, requestID);
this.retryAfter = retryAfter;
}
};
// src/common/exceptions/signature-verification.exception.ts
var SignatureVerificationException = class extends Error {
name = "SignatureVerificationException";
constructor(message) {
super(message || "Signature verification failed.");
}
};
// src/common/exceptions/unauthorized.exception.ts
var UnauthorizedException = class extends Error {
requestID;
status = 401;
name = "UnauthorizedException";
message;
constructor(requestID) {
super();
this.requestID = requestID;
this.message = `Could not authorize the request. Maybe your API key is invalid?`;
}
};
// src/common/exceptions/unprocessable-entity.exception.ts
var UnprocessableEntityException = class extends Error {
status = 422;
name = "UnprocessableEntityException";
message = "Unprocessable entity";
code;
requestID;
constructor({ code, error, errors, message, requestID }) {
super();
this.requestID = requestID;
if (message) this.message = message;
else if (error) this.message = `Error: ${error}`;
if (code) this.code = code;
if (errors) {
const requirement = errors.length === 1 ? "requirement" : "requirements";
this.message = `The following ${requirement} must be met:\n`;
for (const { code } of errors) this.message = this.message.concat(`\t${code}\n`);
}
}
};
// src/common/crypto/signature-provider.ts
var SignatureProvider = class {
cryptoProvider;
constructor(cryptoProvider) {
this.cryptoProvider = cryptoProvider;
}
async verifyHeader({ payload, sigHeader, secret, tolerance = 18e4 }) {
const [timestamp, signatureHash] = this.getTimestampAndSignatureHash(sigHeader);
if (!signatureHash || Object.keys(signatureHash).length === 0) throw new SignatureVerificationException("No signature hash found with expected scheme v1");
const timestampMs = Number(timestamp);
if (!/^\d+$/.test(timestamp) || !Number.isSafeInteger(timestampMs)) throw new SignatureVerificationException("Invalid timestamp");
if (Math.abs(Date.now() - timestampMs) > tolerance) throw new SignatureVerificationException("Timestamp outside the tolerance zone");
const expectedSig = await this.computeSignature(timestamp, payload, secret);
if (await this.cryptoProvider.secureCompare(expectedSig, signatureHash) === false) throw new SignatureVerificationException("Signature hash does not match the expected signature hash for payload");
return true;
}
getTimestampAndSignatureHash(sigHeader) {
const [t, v1] = sigHeader.split(",");
if (typeof t === "undefined" || typeof v1 === "undefined") throw new SignatureVerificationException("Signature or timestamp missing");
const { 1: timestamp } = t.split("=");
const { 1: signatureHash } = v1.split("=");
return [timestamp, signatureHash];
}
async computeSignature(timestamp, payload, secret) {
const signedPayload = `${timestamp}.${decodePayloadToString(payload)}`;
return await this.cryptoProvider.computeHMACSignatureAsync(signedPayload, secret);
}
};
// src/common/utils/unreachable.ts
/**
* Indicates that code is unreachable.
*
* This can be used for exhaustiveness checks in situations where the compiler
* would not otherwise check for exhaustiveness.
*
* If the determination that the code is unreachable proves incorrect, an
* exception is thrown.
*/
const unreachable = (condition, message = `Entered unreachable code. Received '${condition}'.`) => {
throw new TypeError(message);
};
// src/organization-domains/serializers/organization-domain.serializer.ts
const deserializeOrganizationDomain = (organizationDomain) => ({
object: organizationDomain.object,
id: organizationDomain.id,
domain: organizationDomain.domain,
organizationId: organizationDomain.organization_id,
state: organizationDomain.state,
...organizationDomain.verification_token !== void 0 && { verificationToken: organizationDomain.verification_token },
verificationStrategy: organizationDomain.verification_strategy,
...organizationDomain.verification_prefix !== void 0 && { verificationPrefix: organizationDomain.verification_prefix },
createdAt: new Date(organizationDomain.created_at),
updatedAt: new Date(organizationDomain.updated_at)
});
// src/organizations/serializers/organization.serializer.ts
const deserializeOrganization = (organization) => ({
object: organization.object,
id: organization.id,
name: organization.name,
allowProfilesOutsideOrganization: organization.allow_profiles_outside_organization,
domains: organization.domains.map(deserializeOrganizationDomain),
...typeof organization.stripe_customer_id === "undefined" ? void 0 : { stripeCustomerId: organization.stripe_customer_id },
createdAt: new Date(organization.created_at),
updatedAt: new Date(organization.updated_at),
externalId: organization.external_id ?? null,
metadata: organization.metadata ?? {}
});
// src/user-management/serializers/authenticate-with-code-options.serializer.ts
const serializeAuthenticateWithCodeOptions = (options) => ({
grant_type: "authorization_code",
client_id: options.clientId,
client_secret: options.clientSecret,
code: options.code,
code_verifier: options.codeVerifier,
invitation_token: options.invitationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent,
signals_id: options.signalsId
});
// src/user-management/serializers/authenticate-with-code-and-verifier-options.serializer.ts
const serializeAuthenticateWithCodeAndVerifierOptions = (options) => ({
grant_type: "authorization_code",
client_id: options.clientId,
code: options.code,
code_verifier: options.codeVerifier,
invitation_token: options.invitationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent,
signals_id: options.signalsId
});
// src/user-management/serializers/authenticate-with-magic-auth-options.serializer.ts
const serializeAuthenticateWithMagicAuthOptions = (options) => ({
grant_type: "urn:workos:oauth:grant-type:magic-auth:code",
client_id: options.clientId,
client_secret: options.clientSecret,
code: options.code,
email: options.email,
invitation_token: options.invitationToken,
link_authorization_code: options.linkAuthorizationCode,
ip_address: options.ipAddress,
user_agent: options.userAgent,
radar_auth_attempt_id: options.radarAuthAttemptId,
signals_id: options.signalsId
});
// src/user-management/serializers/authenticate-with-radar-email-challenge-options.serializer.ts
const serializeAuthenticateWithRadarEmailChallengeOptions = (options) => ({
grant_type: "urn:workos:oauth:grant-type:radar-email-challenge:code",
client_id: options.clientId,
client_secret: options.clientSecret,
code: options.code,
radar_challenge_id: options.radarChallengeId,
pending_authentication_token: options.pendingAuthenticationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/authenticate-with-radar-sms-challenge-options.serializer.ts
const serializeAuthenticateWithRadarSmsChallengeOptions = (options) => ({
grant_type: "urn:workos:oauth:grant-type:radar-sms-challenge:code",
client_id: options.clientId,
client_secret: options.clientSecret,
code: options.code,
verification_id: options.verificationId,
phone_number: options.phoneNumber,
pending_authentication_token: options.pendingAuthenticationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/authenticate-with-password-options.serializer.ts
const serializeAuthenticateWithPasswordOptions = (options) => ({
grant_type: "password",
client_id: options.clientId,
client_secret: options.clientSecret,
email: options.email,
password: options.password,
invitation_token: options.invitationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent,
radar_auth_attempt_id: options.radarAuthAttemptId,
signals_id: options.signalsId
});
// src/user-management/serializers/authenticate-with-refresh-token.options.serializer.ts
const serializeAuthenticateWithRefreshTokenOptions = (options) => ({
grant_type: "refresh_token",
client_id: options.clientId,
client_secret: options.clientSecret,
refresh_token: options.refreshToken,
organization_id: options.organizationId,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/authenticate-with-refresh-token-public-client-options.serializer.ts
const serializeAuthenticateWithRefreshTokenPublicClientOptions = (options) => ({
grant_type: "refresh_token",
client_id: options.clientId,
refresh_token: options.refreshToken,
organization_id: options.organizationId,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/authenticate-with-totp-options.serializer.ts
const serializeAuthenticateWithTotpOptions = (options) => ({
grant_type: "urn:workos:oauth:grant-type:mfa-totp",
client_id: options.clientId,
client_secret: options.clientSecret,
code: options.code,
authentication_challenge_id: options.authenticationChallengeId,
pending_authentication_token: options.pendingAuthenticationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/authentication-event.serializer.ts
const deserializeAuthenticationEventSso = (sso) => ({
connectionId: sso.connection_id ?? null,
organizationId: sso.organization_id ?? null,
sessionId: sso.session_id ?? null
});
const deserializeAuthenticationEvent = (authenticationEvent) => ({
email: authenticationEvent.email,
...authenticationEvent.error !== void 0 && { error: authenticationEvent.error },
ipAddress: authenticationEvent.ip_address,
...authenticationEvent.sso !== void 0 && { sso: deserializeAuthenticationEventSso(authenticationEvent.sso) },
status: authenticationEvent.status,
type: authenticationEvent.type,
userAgent: authenticationEvent.user_agent,
userId: authenticationEvent.user_id
});
// src/multi-factor-auth/serializers/sms.serializer.ts
const deserializeSms = (sms) => ({ phoneNumber: sms.phone_number });
// src/multi-factor-auth/serializers/totp.serializer.ts
const deserializeTotp = (totp) => {
return {
issuer: totp.issuer,
user: totp.user
};
};
const deserializeTotpWithSecrets = (totp) => {
return {
issuer: totp.issuer,
user: totp.user,
qrCode: totp.qr_code,
secret: totp.secret,
uri: totp.uri
};
};
// src/user-management/serializers/authentication-factor.serializer.ts
const deserializeFactor$1 = (factor) => ({
object: factor.object,
id: factor.id,
createdAt: new Date(factor.created_at),
updatedAt: new Date(factor.updated_at),
type: factor.type,
...factor.sms ? { sms: deserializeSms(factor.sms) } : {},
...factor.totp ? { totp: deserializeTotp(factor.totp) } : {},
userId: factor.user_id
});
const deserializeFactorWithSecrets$1 = (factor) => ({
object: factor.object,
id: factor.id,
createdAt: new Date(factor.created_at),
updatedAt: new Date(factor.updated_at),
type: factor.type,
totp: deserializeTotpWithSecrets(factor.totp),
userId: factor.user_id
});
// src/user-management/serializers/oauth-tokens.serializer.ts
const deserializeOauthTokens = (oauthTokens) => oauthTokens ? {
accessToken: oauthTokens.access_token,
refreshToken: oauthTokens.refresh_token,
expiresAt: oauthTokens.expires_at,
scopes: oauthTokens.scopes
} : void 0;
// src/user-management/serializers/user.serializer.ts
const deserializeUser = (user) => ({
object: user.object,
id: user.id,
email: user.email,
emailVerified: user.email_verified,
name: user.name ?? null,
firstName: user.first_name,
profilePictureUrl: user.profile_picture_url,
lastName: user.last_name,
lastSignInAt: user.last_sign_in_at != null ? new Date(user.last_sign_in_at) : null,
locale: user.locale,
createdAt: new Date(user.created_at),
updatedAt: new Date(user.updated_at),
externalId: user.external_id ?? null,
metadata: user.metadata ?? {}
});
// src/user-management/serializers/authentication-response.serializer.ts
const deserializeAuthenticationResponse = (authenticationResponse) => {
const { user, organization_id, access_token, refresh_token, authentication_method, impersonator, oauth_tokens, ...rest } = authenticationResponse;
return {
user: deserializeUser(user),
organizationId: organization_id,
accessToken: access_token,
refreshToken: refresh_token,
impersonator,
authenticationMethod: authentication_method,
oauthTokens: deserializeOauthTokens(oauth_tokens),
...rest
};
};
// src/connect/serializers/connect-application-redirect-uri.serializer.ts
const deserializeConnectApplicationRedirectUri = (response) => ({
uri: response.uri,
default: response.default
});
// src/connect/serializers/connect-application.serializer.ts
const deserializeConnectApplication = (response) => {
switch (response.application_type) {
case "oauth": return {
object: response.object,
id: response.id,
clientId: response.client_id,
description: response.description,
name: response.name,
scopes: response.scopes,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at),
applicationType: "oauth",
redirectUris: response.redirect_uris.map(deserializeConnectApplicationRedirectUri),
usesPkce: response.uses_pkce,
isFirstParty: response.is_first_party,
wasDynamicallyRegistered: response.was_dynamically_registered,
organizationId: response.organization_id
};
case "m2m": return {
object: response.object,
id: response.id,
clientId: response.client_id,
description: response.description,
name: response.name,
scopes: response.scopes,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at),
applicationType: "m2m",
organizationId: response.organization_id
};
default: throw new Error(`Unknown application_type: ${response.application_type}`);
}
};
// src/user-management/serializers/authorized-connect-application.serializer.ts
const deserializeAuthorizedConnectApplication = (response) => ({
object: response.object,
id: response.id,
grantedScopes: response.granted_scopes,
oauthResource: response.oauth_resource,
application: deserializeConnectApplication(response.application)
});
// src/user-management/serializers/create-magic-auth-options.serializer.ts
const serializeCreateMagicAuthOptions = (options) => ({
email: options.email,
invitation_token: options.invitationToken,
ip_address: options.ipAddress,
user_agent: options.userAgent,
radar_auth_attempt_id: options.radarAuthAttemptId,
signals_id: options.signalsId
});
// src/user-management/serializers/create-password-reset-options.serializer.ts
const serializeCreatePasswordResetOptions = (options) => ({ email: options.email });
// src/user-management/serializers/create-user-api-key-options.serializer.ts
function serializeCreateUserApiKeyOptions(options) {
return {
name: options.name,
organization_id: options.organizationId,
permissions: options.permissions,
expires_at: options.expiresAt?.toISOString()
};
}
// src/user-management/serializers/email-verification.serializer.ts
const deserializeEmailVerification = (emailVerification) => ({
object: emailVerification.object,
id: emailVerification.id,
userId: emailVerification.user_id,
email: emailVerification.email,
expiresAt: new Date(emailVerification.expires_at),
code: emailVerification.code,
createdAt: new Date(emailVerification.created_at),
updatedAt: new Date(emailVerification.updated_at)
});
const deserializeEmailVerificationEvent = (emailVerification) => ({
object: emailVerification.object,
id: emailVerification.id,
userId: emailVerification.user_id,
email: emailVerification.email,
expiresAt: new Date(emailVerification.expires_at),
createdAt: new Date(emailVerification.created_at),
updatedAt: new Date(emailVerification.updated_at)
});
// src/user-management/serializers/enroll-auth-factor-options.serializer.ts
const serializeEnrollAuthFactorOptions = (options) => ({
type: options.type,
totp_issuer: options.totpIssuer,
totp_user: options.totpUser,
totp_secret: options.totpSecret
});
// src/user-management/serializers/invitation.serializer.ts
const deserializeInvitation = (invitation) => ({
object: invitation.object,
id: invitation.id,
email: invitation.email,
state: invitation.state,
acceptedAt: invitation.accepted_at != null ? new Date(invitation.accepted_at) : null,
revokedAt: invitation.revoked_at != null ? new Date(invitation.revoked_at) : null,
expiresAt: new Date(invitation.expires_at),
organizationId: invitation.organization_id,
inviterUserId: invitation.inviter_user_id,
acceptedUserId: invitation.accepted_user_id,
roleSlug: invitation.role_slug,
token: invitation.token,
acceptInvitationUrl: invitation.accept_invitation_url,
createdAt: new Date(invitation.created_at),
updatedAt: new Date(invitation.updated_at)
});
const deserializeInvitationEvent = (invitation) => ({
object: invitation.object,
id: invitation.id,
email: invitation.email,
state: invitation.state,
acceptedAt: invitation.accepted_at != null ? new Date(invitation.accepted_at) : null,
revokedAt: invitation.revoked_at != null ? new Date(invitation.revoked_at) : null,
expiresAt: new Date(invitation.expires_at),
organizationId: invitation.organization_id,
inviterUserId: invitation.inviter_user_id,
acceptedUserId: invitation.accepted_user_id,
roleSlug: invitation.role_slug,
createdAt: new Date(invitation.created_at),
updatedAt: new Date(invitation.updated_at)
});
// src/user-management/serializers/list-sessions-options.serializer.ts
const serializeListSessionsOptions = (options) => ({ ...options });
// src/user-management/serializers/list-user-api-keys-options.serializer.ts
function serializeListUserApiKeysOptions(options) {
return {
limit: options.limit,
before: options.before,
after: options.after,
order: options.order,
organization_id: options.organizationId
};
}
// src/user-management/serializers/magic-auth.serializer.ts
const deserializeMagicAuth = (magicAuth) => ({
object: magicAuth.object,
id: magicAuth.id,
userId: magicAuth.user_id,
email: magicAuth.email,
expiresAt: new Date(magicAuth.expires_at),
code: magicAuth.code,
createdAt: new Date(magicAuth.created_at),
updatedAt: new Date(magicAuth.updated_at)
});
const deserializeMagicAuthEvent = (magicAuth) => ({
object: magicAuth.object,
id: magicAuth.id,
userId: magicAuth.user_id,
email: magicAuth.email,
expiresAt: new Date(magicAuth.expires_at),
createdAt: new Date(magicAuth.created_at),
updatedAt: new Date(magicAuth.updated_at)
});
// src/user-management/serializers/password-reset.serializer.ts
const deserializePasswordReset = (passwordReset) => ({
object: passwordReset.object,
id: passwordReset.id,
userId: passwordReset.user_id,
email: passwordReset.email,
passwordResetToken: passwordReset.password_reset_token,
passwordResetUrl: passwordReset.password_reset_url,
expiresAt: new Date(passwordReset.expires_at),
createdAt: new Date(passwordReset.created_at)
});
const deserializePasswordResetEvent = (passwordReset) => ({
object: passwordReset.object,
id: passwordReset.id,
userId: passwordReset.user_id,
email: passwordReset.email,
expiresAt: new Date(passwordReset.expires_at),
createdAt: new Date(passwordReset.created_at)
});
// src/user-management/serializers/reset-password-options.serializer.ts
const serializeResetPasswordOptions = (options) => ({
token: options.token,
new_password: options.newPassword
});
// src/user-management/serializers/session.serializer.ts
const deserializeSession = (session) => ({
object: "session",
id: session.id,
userId: session.user_id,
ipAddress: session.ip_address,
userAgent: session.user_agent,
...session.organization_id !== void 0 && { organizationId: session.organization_id },
...session.impersonator !== void 0 && { impersonator: session.impersonator },
authMethod: session.auth_method,
status: session.status,
expiresAt: new Date(session.expires_at),
endedAt: session.ended_at != null ? new Date(session.ended_at) : null,
createdAt: new Date(session.created_at),
updatedAt: new Date(session.updated_at)
});
// src/user-management/serializers/create-user-options.serializer.ts
const serializeCreateUserOptions = (options) => ({
email: options.email,
password: options.password,
password_hash: options.passwordHash,
password_hash_type: options.passwordHashType,
name: options.name,
first_name: options.firstName,
last_name: options.lastName,
email_verified: options.emailVerified,
external_id: options.externalId,
metadata: options.metadata,
ip_address: options.ipAddress,
user_agent: options.userAgent,
signals_id: options.signalsId
});
// src/user-management/serializers/send-radar-sms-challenge-options.serializer.ts
const serializeSendRadarSmsChallengeOptions = (options) => ({
user_id: options.userId,
pending_authentication_token: options.pendingAuthenticationToken,
phone_number: options.phoneNumber,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/update-user-options.serializer.ts
const serializeUpdateUserOptions = (options) => ({
email: options.email,
email_verified: options.emailVerified,
name: options.name,
first_name: options.firstName,
last_name: options.lastName,
password: options.password,
password_hash: options.passwordHash,
password_hash_type: options.passwordHashType,
external_id: options.externalId,
locale: options.locale,
metadata: options.metadata
});
// src/user-management/serializers/user-api-key.serializer.ts
function deserializeUserApiKey(apiKey) {
return {
object: apiKey.object,
id: apiKey.id,
owner: {
type: "user",
id: apiKey.owner.id,
organizationId: apiKey.owner.organization_id
},
name: apiKey.name,
obfuscatedValue: apiKey.obfuscated_value,
lastUsedAt: apiKey.last_used_at != null ? new Date(apiKey.last_used_at) : null,
expiresAt: apiKey.expires_at != null ? new Date(apiKey.expires_at) : null,
permissions: apiKey.permissions,
createdAt: new Date(apiKey.created_at),
updatedAt: new Date(apiKey.updated_at)
};
}
// src/user-management/serializers/user-api-key-with-value.serializer.ts
function deserializeUserApiKeyWithValue(apiKey) {
return {
...deserializeUserApiKey(apiKey),
value: apiKey.value
};
}
// src/user-management/serializers/waitlist.serializer.ts
const deserializeWaitlist = (waitlist) => ({
object: waitlist.object,
id: waitlist.id,
createdAt: new Date(waitlist.created_at),
updatedAt: new Date(waitlist.updated_at)
});
// src/user-management/serializers/waitlist-entry.serializer.ts
const deserializeWaitlistEntry = (waitlistEntry) => ({
object: waitlistEntry.object,
id: waitlistEntry.id,
email: waitlistEntry.email,
state: waitlistEntry.state,
approvedAt: waitlistEntry.approved_at != null ? new Date(waitlistEntry.approved_at) : null,
additionalFields: waitlistEntry.additional_fields,
waitlistId: waitlistEntry.waitlist_id ?? null,
createdAt: new Date(waitlistEntry.created_at),
updatedAt: new Date(waitlistEntry.updated_at)
});
// src/user-management/serializers/waitlist-user-event.serializer.ts
const deserializeWaitlistUserEvent = (data) => ({
object: data.object,
id: data.id,
email: data.email,
state: data.state,
approvedAt: data.approved_at != null ? new Date(data.approved_at) : null,
additionalFields: data.additional_fields,
waitlistId: data.waitlist_id ?? null,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
// src/user-management/serializers/organization-membership.serializer.ts
const deserializeOrganizationMembership = (organizationMembership) => ({
object: organizationMembership.object,
id: organizationMembership.id,
userId: organizationMembership.user_id,
organizationId: organizationMembership.organization_id,
organizationName: organizationMembership.organization_name,
status: organizationMembership.status,
directoryManaged: organizationMembership.directory_managed ?? false,
createdAt: new Date(organizationMembership.created_at),
updatedAt: new Date(organizationMembership.updated_at),
role: organizationMembership.role,
...organizationMembership.roles && { roles: organizationMembership.roles },
customAttributes: organizationMembership.custom_attributes ?? {},
...organizationMembership.user && { user: deserializeUser(organizationMembership.user) }
});
const deserializeAuthorizationOrganizationMembership = (organizationMembership) => ({
object: organizationMembership.object,
id: organizationMembership.id,
userId: organizationMembership.user_id,
organizationId: organizationMembership.organization_id,
status: organizationMembership.status,
directoryManaged: organizationMembership.directory_managed ?? false,
createdAt: new Date(organizationMembership.created_at),
updatedAt: new Date(organizationMembership.updated_at),
customAttributes: organizationMembership.custom_attributes ?? {}
});
// src/actions/serializers/action.serializer.ts
const deserializeUserData = (userData) => {
return {
object: userData.object,
email: userData.email,
name: userData.name ?? null,
firstName: userData.first_name,
lastName: userData.last_name
};
};
const deserializeAction = (actionPayload) => {
switch (actionPayload.object) {
case "user_registration_action_context": return {
id: actionPayload.id,
object: actionPayload.object,
userData: deserializeUserData(actionPayload.user_data),
invitation: actionPayload.invitation ? deserializeInvitation(actionPayload.invitation) : void 0,
authenticationMethod: actionPayload.authentication_method,
ipAddress: actionPayload.ip_address,
userAgent: actionPayload.user_agent,
deviceFingerprint: actionPayload.device_fingerprint
};
case "authentication_action_context": return {
id: actionPayload.id,
object: actionPayload.object,
user: deserializeUser(actionPayload.user),
organization: actionPayload.organization ? deserializeOrganization(actionPayload.organization) : void 0,
organizationMembership: actionPayload.organization_membership ? deserializeOrganizationMembership(actionPayload.organization_membership) : void 0,
authenticationMethod: actionPayload.authentication_method,
ipAddress: actionPayload.ip_address,
userAgent: actionPayload.user_agent,
deviceFingerprint: actionPayload.device_fingerprint,
issuer: actionPayload.issuer
};
}
};
// src/actions/actions.ts
var Actions = class {
signatureProvider;
constructor(cryptoProvider) {
this.signatureProvider = new SignatureProvider(cryptoProvider);
}
get computeSignature() {
return this.signatureProvider.computeSignature.bind(this.signatureProvider);
}
get verifyHeader() {
return this.signatureProvider.verifyHeader.bind(this.signatureProvider);
}
serializeType(type) {
switch (type) {
case "authentication": return "authentication_action_response";
case "user_registration": return "user_registration_action_response";
default: return unreachable(type);
}
}
async signResponse(data, secret) {
let errorMessage;
const { verdict, type } = data;
if (verdict === "Deny" && data.errorMessage) errorMessage = data.errorMessage;
const responsePayload = {
timestamp: Date.now(),
verdict,
...verdict === "Deny" && data.errorMessage && { error_message: errorMessage }
};
return {
object: this.serializeType(type),
payload: responsePayload,
signature: await this.computeSignature(responsePayload.timestamp, responsePayload, secret)
};
}
async constructAction({ payload, sigHeader, secret, tolerance = 3e4 }) {
const options = {
payload,
sigHeader,
secret,
tolerance
};
await this.verifyHeader(options);
const parsed = typeof payload === "string" || isBinaryPayload(payload) ? JSON.parse(decodePayloadToString(payload)) : payload;
return deserializeAction(parsed);
}
};
// src/common/utils/pagination.ts
var AutoPaginatable = class {
list;
apiCall;
object = "list";
options;
constructor(list, apiCall, options) {
this.list = list;
this.apiCall = apiCall;
this.options = options ?? {};
}
get data() {
return this.list.data;
}
get listMetadata() {
return this.list.listMetadata;
}
async *generatePages(after) {
const { before, ...options } = this.options;
const result = await this.apiCall({
...options,
limit: 100,
after
});
yield result.data;
if (result.listMetadata.after) {
await new Promise((resolve) => setTimeout(resolve, 350));
yield* this.generatePages(result.listMetadata.after);
}
}
/**
* Automatically paginates over the list of results, returning the complete data set.
* Returns the first result if `options.limit` is passed to the first request.
*/
async autoPagination() {
if (this.options.limit || !this.listMetadata.after) return this.data;
const results = [...this.data];
for await (const page of this.generatePages(this.listMetadata.after)) results.push(...page);
return results;
}
};
// src/agents/serializers/agent-blueprint.serializer.ts
function deserializeAgentBlueprint(blueprint) {
return {
object: blueprint.object,
id: blueprint.id,
name: blueprint.name,
description: blueprint.description,
permissions: blueprint.permissions,
invocableBy: {
roleSlugs: blueprint.invocable_by.role_slugs,
organizationIds: blueprint.invocable_by.organization_ids
},
sessionSettings: {
maxAgeSeconds: blueprint.session_settings.max_age_seconds,
accessTokenTtlSeconds: blueprint.session_settings.access_token_ttl_seconds,
refreshTokenTtlSeconds: blueprint.session_settings.refresh_token_ttl_seconds
},
createdAt: new Date(blueprint.created_at),
updatedAt: new Date(blueprint.updated_at)
};
}
function serializeCreateAgentBlueprintOptions(options) {
return {
name: options.name,
...options.description !== void 0 && { description: options.description },
...options.permissions !== void 0 && { permissions: options.permissions },
...options.invocableBy !== void 0 && { invocable_by: {
...options.invocableBy.roleSlugs !== void 0 && { role_slugs: options.invocableBy.roleSlugs },
...options.invocableBy.organizationIds !== void 0 && { organization_ids: options.invocableBy.organizationIds }
} },
session_settings: {
max_age_seconds: options.sessionSettings.maxAgeSeconds,
access_token_ttl_seconds: options.sessionSettings.accessTokenTtlSeconds,
refresh_token_ttl_seconds: options.sessionSettings.refreshTokenTtlSeconds
}
};
}
function serializeUpdateAgentBlueprintOptions(options) {
return {
...options.name !== void 0 && { name: options.name },
...options.description !== void 0 && { description: options.description },
...options.permissions !== void 0 && { permissions: options.permissions },
...options.invocableBy !== void 0 && { invocable_by: {
...options.invocableBy.roleSlugs !== void 0 && { role_slugs: options.invocableBy.roleSlugs },
...options.invocableBy.organizationIds !== void 0 && { organization_ids: options.invocableBy.organizationIds }
} },
...options.sessionSettings !== void 0 && { session_settings: {
...options.sessionSettings.maxAgeSeconds !== void 0 && { max_age_seconds: options.sessionSettings.maxAgeSeconds },
...options.sessionSettings.accessTokenTtlSeconds !== void 0 && { access_token_ttl_seconds: options.sessionSettings.accessTokenTtlSeconds },
...options.sessionSettings.refreshTokenTtlSeconds !== void 0 && { refresh_token_ttl_seconds: options.sessionSettings.refreshTokenTtlSeconds }
} }
};
}
// src/agents/serializers/agent-event.serializer.ts
const deserializeAgentBlueprintEvent = (data) => ({
...deserializeAgentBlueprint(data),
invocableAs: { instanceTypes: data.invocable_as.instance_types }
});
const deserializeAgentBlueprintDeletedEvent = (data) => ({
object: data.object,
id: data.id,
name: data.name,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
const deserializeAgentInstanceSessionEvent = (data) => ({
object: data.object,
id: data.id,
agentInstanceId: data.agent_instance_id,
organizationId: data.organization_id,
expiresAt: new Date(data.expires_at),
revokedAt: data.revoked_at != null ? new Date(data.revoked_at) : null,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
const deserializeAgentInstanceSessionCreatedEvent = (data) => ({
...deserializeAgentInstanceSessionEvent(data),
permissionSlugs: data.permission_slugs
});
const deserializeAgentRegistrationCreatedEvent = (data) => ({
object: data.object,
id: data.id,
agentIdentity: {
object: data.agent_identity.object,
id: data.agent_identity.id,
userlandUserId: data.agent_identity.userland_user_id
},
organizationId: data.organization_id,
status: data.status,
kind: data.kind,
method: data.method,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
const deserializeAgentRegistrationClaimAttemptCreatedEvent = (data) => ({
object: data.object,
id: data.id,
agentRegistrationId: data.agent_registration_id,
agentRegistrationClaimId: data.agent_registration_claim_id,
loginHint: data.login_hint,
expiresAt: new Date(data.expires_at),
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
const deserializeAgentRegistrationClaimCompletedEvent = (data) => ({
object: data.object,
id: data.id,
agentRegistrationId: data.agent_registration_id,
completedByAttemptId: data.completed_by_attempt_id,
claimedBy: {
userId: data.claimed_by.user_id,
organizationId: data.claimed_by.organization_id
},
completedAt: new Date(data.completed_at),
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
const deserializeAgentRegistrationCredentialDetail = (detail) => {
switch (detail.kind) {
case "api_key": return {
kind: detail.kind,
apiKeyId: detail.api_key_id
};
case "access_token": return {
kind: detail.kind,
jti: detail.jti,
expiresAt: detail.expires_at != null ? new Date(detail.expires_at) : null
};
}
};
const deserializeAgentRegistrationCredentialIssuedEvent = (data) => ({
object: data.object,
id: data.id,
agentRegistrationId: data.agent_registration_id,
detail: deserializeAgentRegistrationCredentialDetail(data.detail),
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at)
});
const deserializeAgentRegistrationOrganizationSwitchedEvent = (data) => ({
agentRegistrationId: data.agent_registration_id,
fromOrganizationId: data.from_organization_id,
toOrganizationId: data.to_organization_id
});
const deserializeAgentRegistrationLifecycleEvent = (data) => ({ agentRegistrationId: data.agent_registration_id });
// src/agents/serializers/agent-instance.serializer.ts
function deserializeAgentInstance(instance) {
return {
object: instance.object,
id: instance.id,
agentBlueprintId: instance.agent_blueprint_id,
organizationId: instance.organization_id,
organizationMembershipId: instance.organization_membership_id,
type: instance.type,
createdAt: new Date(instance.created_at),
updatedAt: new Date(instance.updated_at)
};
}
function serializeListAgentInstancesOptions(options) {
return {
organization_id: options.organizationId,
agent_blueprint_id: options.agentBlueprintId,
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
};
}
// src/directory-sync/serializers/directory-metadata-user.serializer.ts
const deserializeDirectoryMetadataUser = (response) => ({
active: response.active,
inactive: response.inactive
});
// src/directory-sync/serializers/directory-metadata.serializer.ts
const deserializeDirectoryMetadata = (response) => ({
users: deserializeDirectoryMetadataUser(response.users),
groups: response.groups
});
// src/directory-sync/serializers/directory.serializer.ts
const deserializeDirectoryState = (value) => {
if (value === "linked") return "active";
if (value === "unlinked") return "inactive";
return value;
};
const deserializeDirectory = (response) => ({
object: response.object,
id: response.id,
organizationId: response.organization_id,
externalKey: response.external_key,
type: response.type,
state: deserializeDirectoryState(response.state),
name: response.name,
domain: response.domain,
metadata: response.metadata != null ? deserializeDirectoryMetadata(response.metadata) : void 0,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/directory-sync/serializers/directory-group.serializer.ts
const deserializeDirectoryGroup = (response) => ({
object: response.object,
id: response.id,
idpId: response.idp_id,
directoryId: response.directory_id,
organizationId: response.organization_id,
name: response.name,
rawAttributes: response.raw_attributes,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/directory-sync/serializers/directory-user.serializer.ts
const deserializeDirectoryUser = (directoryUser) => ({
object: directoryUser.object,
id: directoryUser.id,
directoryId: directoryUser.directory_id,
organizationId: directoryUser.organization_id,
rawAttributes: directoryUser.raw_attributes,
customAttributes: directoryUser.custom_attributes,
idpId: directoryUser.idp_id,
firstName: directoryUser.first_name,
email: directoryUser.email,
lastName: directoryUser.last_name,
name: directoryUser.name ?? null,
state: directoryUser.state,
...directoryUser.role !== void 0 && { role: directoryUser.role },
...directoryUser.roles !== void 0 && { roles: directoryUser.roles },
createdAt: new Date(directoryUser.created_at),
updatedAt: new Date(directoryUser.updated_at)
});
const deserializeDirectoryUserWithGroups = (directoryUserWithGroups) => ({
...deserializeDirectoryUser(directoryUserWithGroups),
groups: directoryUserWithGroups.groups.map(deserializeDirectoryGroup)
});
const deserializeUpdatedEventDirectoryUser = (directoryUser) => ({
object: "directory_user",
id: directoryUser.id,
directoryId: directoryUser.directory_id,
organizationId: directoryUser.organization_id,
rawAttributes: directoryUser.raw_attributes,
customAttributes: directoryUser.custom_attributes,
idpId: directoryUser.idp_id,
firstName: directoryUser.first_name,
email: directoryUser.email,
lastName: directoryUser.last_name,
name: directoryUser.name ?? null,
state: directoryUser.state,
...directoryUser.role !== void 0 && { role: directoryUser.role },
...directoryUser.roles !== void 0 && { roles: directoryUser.roles },
createdAt: new Date(directoryUser.created_at),
updatedAt: new Date(directoryUser.updated_at),
previousAttributes: directoryUser.previous_attributes
});
// src/directory-sync/serializers/event-directory.serializer.ts
const deserializeEventDirectory = (directory) => ({
object: directory.object,
id: directory.id,
externalKey: directory.external_key,
type: directory.type,
state: directory.state,
name: directory.name,
organizationId: directory.organization_id,
domains: directory.domains,
createdAt: new Date(directory.created_at),
updatedAt: new Date(directory.updated_at)
});
const deserializeDeletedEventDirectory = (directory) => ({
object: directory.object,
id: directory.id,
type: directory.type,
state: directory.state,
name: directory.name,
organizationId: directory.organization_id,
createdAt: new Date(directory.created_at),
updatedAt: new Date(directory.updated_at)
});
const deserializeUpdatedEventDirectoryGroup = (directoryGroup) => ({
...deserializeDirectoryGroup(directoryGroup),
previousAttributes: directoryGroup.previous_attributes
});
// src/directory-sync/serializers/directory-token.serializer.ts
const deserializeDirectoryToken = (token) => ({
object: token.object,
id: token.id,
directoryId: token.directory_id,
...token.organization_id !== void 0 && { organizationId: token.organization_id },
tokenSuffix: token.token_suffix,
createdAt: new Date(token.created_at)
});
// src/organizations/serializers/create-organization-options.serializer.ts
const serializeCreateOrganizationOptions = (options) => ({
name: options.name,
domain_data: options.domainData,
external_id: options.externalId,
metadata: options.metadata
});
// src/organizations/serializers/it-contact-options.serializer.ts
const serializeCreateItContactOptions = (options) => ({ email: options.email });
const serializeInviteItContactOptions = (options) => ({ intents: options.intents });
// src/organizations/serializers/it-contact.serializer.ts
const deserializeItContact = (itContact) => ({
object: itContact.object,
id: itContact.id,
email: itContact.email,
createdAt: new Date(itContact.created_at),
updatedAt: new Date(itContact.updated_at)
});
// src/organizations/serializers/update-organization-options.serializer.ts
const serializeUpdateOrganizationOptions = (options) => ({
name: options.name,
domain_data: options.domainData,
stripe_customer_id: options.stripeCustomerId,
external_id: options.externalId,
metadata: options.metadata
});
// src/sso/serializers/authorize-logout.serializer.ts
const serializeAuthorizeLogoutOptions = (options) => ({ profile_id: options.profileId });
const deserializeAuthorizeLogout = (response) => ({
logoutToken: response.logout_token,
logoutUrl: response.logout_url
});
// src/sso/serializers/connection.serializer.ts
const deserializeConnection = (connection) => ({
object: connection.object,
id: connection.id,
...connection.organization_id !== void 0 && { organizationId: connection.organization_id },
name: connection.name,
type: connection.connection_type,
state: connection.state,
domains: connection.domains,
createdAt: new Date(connection.created_at),
updatedAt: new Date(connection.updated_at)
});
// src/sso/serializers/connection-event.serializer.ts
const deserializeConnectionEventConnection = (connection) => ({
id: connection.id,
...connection.organization_id !== void 0 && { organizationId: connection.organization_id }
});
const deserializeConnectionSamlCertificateRenewalRequiredEvent = (data) => ({
connection: deserializeConnectionEventConnection(data.connection),
certificate: {
certificateType: data.certificate.certificate_type,
expiryDate: new Date(data.certificate.expiry_date),
isExpired: data.certificate.is_expired
},
daysUntilExpiry: data.days_until_expiry
});
const deserializeConnectionSamlCertificateRenewedEvent = (data) => ({
connection: deserializeConnectionEventConnection(data.connection),
certificate: {
certificateType: data.certificate.certificate_type,
expiryDate: new Date(data.certificate.expiry_date)
},
renewedAt: new Date(data.renewed_at)
});
// src/sso/serializers/list-connections-options.serializer.ts
const serializeListConnectionsOptions = (options) => ({
connection_type: options.connectionType,
domain: options.domain,
organization_id: options.organizationId,
state: options.state,
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
});
// src/sso/serializers/profile.serializer.ts
const deserializeProfile = (profile) => ({
object: profile.object,
id: profile.id,
idpId: profile.idp_id,
organizationId: profile.organization_id ?? null,
connectionId: profile.connection_id,
connectionType: profile.connection_type,
email: profile.email,
name: profile.name ?? null,
firstName: profile.first_name ?? null,
lastName: profile.last_name ?? null,
...profile.role !== void 0 && { role: profile.role },
...profile.roles !== void 0 && { roles: profile.roles },
...profile.groups !== void 0 && { groups: profile.groups },
...profile.custom_attributes !== void 0 && { customAttributes: profile.custom_attributes },
rawAttributes: profile.raw_attributes
});
// src/sso/serializers/profile-and-token.serializer.ts
const deserializeProfileAndToken = (profileAndToken) => ({
accessToken: profileAndToken.access_token,
profile: deserializeProfile(profileAndToken.profile),
oauthTokens: deserializeOauthTokens(profileAndToken.oauth_tokens)
});
// src/user-management/serializers/role.serializer.ts
const deserializeRoleEvent = (role) => ({
object: role.object,
slug: role.slug,
resourceTypeSlug: role.resource_type_slug,
permissions: role.permissions,
createdAt: new Date(role.created_at),
updatedAt: new Date(role.updated_at)
});
// src/user-management/serializers/authentication-radar-risk-event-serializer.ts
const deserializeAuthenticationRadarRiskDetectedEvent = (authenticationRadarRiskDetectedEvent) => ({
authMethod: authenticationRadarRiskDetectedEvent.auth_method,
action: authenticationRadarRiskDetectedEvent.action,
control: authenticationRadarRiskDetectedEvent.control,
blocklistType: authenticationRadarRiskDetectedEvent.blocklist_type,
ipAddress: authenticationRadarRiskDetectedEvent.ip_address,
userAgent: authenticationRadarRiskDetectedEvent.user_agent,
userId: authenticationRadarRiskDetectedEvent.user_id,
email: authenticationRadarRiskDetectedEvent.email
});
// src/api-keys/serializers/api-key.serializer.ts
function deserializeApiKey(apiKey) {
return {
object: apiKey.object,
id: apiKey.id,
owner: apiKey.owner.type === "user" ? {
type: "user",
id: apiKey.owner.id,
organizationId: apiKey.owner.organization_id
} : apiKey.owner,
name: apiKey.name,
obfuscatedValue: apiKey.obfuscated_value,
lastUsedAt: apiKey.last_used_at != null ? new Date(apiKey.last_used_at) : null,
expiresAt: apiKey.expires_at != null ? new Date(apiKey.expires_at) : null,
permissions: apiKey.permissions,
createdAt: new Date(apiKey.created_at),
updatedAt: new Date(apiKey.updated_at)
};
}
// src/authorization/serializers/organization-role.serializer.ts
const deserializeRole = (role) => ({
object: role.object,
id: role.id,
name: role.name,
slug: role.slug,
description: role.description,
permissions: role.permissions,
resourceTypeSlug: role.resource_type_slug,
type: role.type,
createdAt: new Date(role.created_at),
updatedAt: new Date(role.updated_at)
});
const deserializeOrganizationRole = (role) => ({
object: role.object,
id: role.id,
name: role.name,
slug: role.slug,
description: role.description,
permissions: role.permissions,
resourceTypeSlug: role.resource_type_slug,
type: "OrganizationRole",
createdAt: new Date(role.created_at),
updatedAt: new Date(role.updated_at)
});
const deserializeOrganizationRoleEvent = (event) => ({
object: event.object,
organizationId: event.organization_id,
slug: event.slug,
name: event.name,
description: event.description,
resourceTypeSlug: event.resource_type_slug,
permissions: event.permissions,
createdAt: new Date(event.created_at),
updatedAt: new Date(event.updated_at)
});
// src/authorization/serializers/permission.serializer.ts
const deserializePermission = (permission) => ({
object: permission.object,
id: permission.id,
slug: permission.slug,
name: permission.name,
description: permission.description,
resourceTypeSlug: permission.resource_type_slug,
system: permission.system,
createdAt: new Date(permission.created_at),
updatedAt: new Date(permission.updated_at)
});
// src/feature-flags/serializers/feature-flag.serializer.ts
const deserializeFeatureFlag = (featureFlag) => ({
object: featureFlag.object,
id: featureFlag.id,
name: featureFlag.name,
slug: featureFlag.slug,
description: featureFlag.description,
tags: featureFlag.tags,
enabled: featureFlag.enabled,
defaultValue: featureFlag.default_value,
createdAt: new Date(featureFlag.created_at),
updatedAt: new Date(featureFlag.updated_at)
});
// src/feature-flags/serializers/flag-rule.serializer.ts
const deserializeFlagRule = (rule) => ({
object: rule.object,
id: rule.id,
flagId: rule.flag_id,
flagSlug: rule.flag_slug,
environmentId: rule.environment_id,
targetType: rule.target_type,
position: rule.position,
valueType: rule.value_type,
value: rule.value,
createdAt: new Date(rule.created_at),
updatedAt: new Date(rule.updated_at)
});
// src/feature-flags/serializers/flag-target.serializer.ts
const deserializeTargetFields = (target) => ({
object: target.object,
id: target.id,
flagId: target.flag_id,
flagSlug: target.flag_slug,
environmentId: target.environment_id,
targetType: target.target_type,
targetId: target.target_id,
createdAt: new Date(target.created_at),
updatedAt: new Date(target.updated_at)
});
const deserializeFlagTarget = (target) => ({
...deserializeTargetFields(target),
ruleId: target.rule_id
});
const deserializeFlagTargetResource = (target) => "rule_id" in target ? deserializeFlagTarget(target) : {
...deserializeTargetFields(target),
valueType: target.value_type,
value: target.value
};
// src/common/serializers/feature-flag-event.serializer.ts
const deserializeFeatureFlagOwner = (owner) => owner === null ? null : {
email: owner.email,
firstName: owner.first_name,
lastName: owner.last_name
};
const deserializeFeatureFlagEventData = (flag) => ({
object: flag.object,
id: flag.id,
environmentId: flag.environment_id,
slug: flag.slug,
name: flag.name,
description: flag.description,
owner: deserializeFeatureFlagOwner(flag.owner),
tags: flag.tags,
enabled: flag.enabled,
defaultValue: flag.default_value,
createdAt: new Date(flag.created_at),
updatedAt: new Date(flag.updated_at)
});
const deserializeFeatureFlagRuleContext = (context) => ({
clientId: context.client_id,
...context.actor === void 0 ? {} : { actor: context.actor }
});
const deserializeFeatureFlagRuleUpdatedContext = (context) => {
const previous = context.previous_attributes;
const data = previous?.data;
return {
...deserializeFeatureFlagRuleContext(context),
...previous === void 0 ? {} : { previousAttributes: { ...data === void 0 ? {} : { data: data.value === void 0 ? {} : { value: data.value } } } }
};
};
const deserializeFeatureFlagUpdatedContext = (context) => {
const previous = context.previous_attributes;
const data = previous?.data;
return {
clientId: context.client_id,
actor: context.actor,
...previous === void 0 ? {} : { previousAttributes: { ...data === void 0 ? {} : { data: {
...data.name === void 0 ? {} : { name: data.name },
...data.description === void 0 ? {} : { description: data.description },
...data.tags === void 0 ? {} : { tags: data.tags },
...data.owner === void 0 ? {} : { owner: deserializeFeatureFlagOwner(data.owner) },
...data.enabled === void 0 ? {} : { enabled: data.enabled },
...data.default_value === void 0 ? {} : { defaultValue: data.default_value }
} } } }
};
};
// src/groups/serializers/create-group.serializer.ts
const serializeCreateGroup = (model) => ({
name: model.name,
description: model.description ?? null
});
// src/groups/serializers/create-group-membership.serializer.ts
const serializeCreateGroupMembership = (model) => ({ organization_membership_id: model.organizationMembershipId });
// src/groups/serializers/group.serializer.ts
const deserializeGroup = (response) => ({
object: response.object,
id: response.id,
organizationId: response.organization_id,
name: response.name,
description: response.description ?? null,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/groups/serializers/update-group.serializer.ts
const serializeUpdateGroup = (model) => ({
name: model.name,
description: model.description ?? null
});
// src/vault/serializers/vault-event.serializer.ts
const deserializeVaultActor = (actor) => ({
actorId: actor.actor_id,
actorSource: actor.actor_source,
actorName: actor.actor_name
});
const deserializeVaultDataCreatedEvent = (data) => ({
...deserializeVaultActor(data),
kvName: data.kv_name,
keyId: data.key_id,
keyContext: data.key_context
});
const deserializeVaultDataUpdatedEvent = (data) => ({
...deserializeVaultActor(data),
kvName: data.kv_name,
keyId: data.key_id,
keyContext: data.key_context
});
const deserializeVaultDataReadEvent = (data) => ({
...deserializeVaultActor(data),
kvName: data.kv_name,
keyId: data.key_id
});
const deserializeVaultDataDeletedEvent = (data) => ({
...deserializeVaultActor(data),
kvName: data.kv_name
});
const deserializeVaultMetadataReadEvent = (data) => ({
...deserializeVaultActor(data),
kvName: data.kv_name
});
const deserializeVaultNamesListedEvent = (data) => deserializeVaultActor(data);
const deserializeVaultKekCreatedEvent = (data) => ({
...deserializeVaultActor(data),
keyName: data.key_name,
keyId: data.key_id
});
const deserializeVaultDekReadEvent = (data) => ({
...deserializeVaultActor(data),
keyIds: data.key_ids,
keyContext: data.key_context
});
const deserializeVaultDekDecryptedEvent = (data) => ({
...deserializeVaultActor(data),
keyId: data.key_id
});
const deserializeVaultByokKeyVerificationCompletedEvent = (data) => ({
organizationId: data.organization_id,
keyProvider: data.key_provider,
verified: data.verified
});
const deserializeVaultKekDeletedEvent = (data) => ({
...deserializeVaultActor(data),
keyName: data.key_name,
keyId: data.key_id
});
const deserializeVaultDekRekeyedEvent = (data) => ({
...deserializeVaultActor(data),
keyIds: data.key_ids,
keyContext: data.key_context
});
const deserializeVaultByokKeyDeletedEvent = (data) => ({
organizationId: data.organization_id,
keyProvider: data.key_provider
});
// src/organization-domains/serializers/organization-domain-verification-failed.serializer.ts
const deserializeOrganizationDomainVerificationFailed = (organizationDomainVerificationFailed) => ({
reason: organizationDomainVerificationFailed.reason,
organizationDomain: deserializeOrganizationDomain(organizationDomainVerificationFailed.organization_domain)
});
// src/actions/serializers/action-event.serializer.ts
const deserializeActionAuthenticationDeniedEvent = (data) => ({
actionEndpointId: data.action_endpoint_id,
actionExecutionId: data.action_execution_id,
type: data.type,
verdict: data.verdict,
userId: data.user_id,
organizationId: data.organization_id,
email: data.email,
ipAddress: data.ip_address,
userAgent: data.user_agent
});
const deserializeActionUserRegistrationDeniedEvent = (data) => ({
actionEndpointId: data.action_endpoint_id,
actionExecutionId: data.action_execution_id,
type: data.type,
verdict: data.verdict,
organizationId: data.organization_id,
email: data.email,
ipAddress: data.ip_address,
userAgent: data.user_agent
});
// src/api-keys/serializers/api-key-event.serializer.ts
function deserializeApiKeyUpdatedEvent(data) {
return {
...deserializeApiKey(data),
previousAttributes: { expiresAt: data.previous_attributes.expires_at != null ? new Date(data.previous_attributes.expires_at) : null }
};
}
// src/radar/serializers/radar-event.serializer.ts
const deserializeRadarChallengeCreatedEvent = (data) => ({
type: data.type,
radarChallengeId: data.radar_challenge_id,
userId: data.user_id,
email: data.email
});
// src/common/serializers/resource-export-event.serializer.ts
const deserializeResourceExportEvent = (data) => ({
id: data.id,
resourceType: data.resource_type
});
// src/common/serializers/event.serializer.ts
const deserializePipesConnectedAccount = (connectedAccount) => ({
object: connectedAccount.object,
id: connectedAccount.id,
...connectedAccount.connection_role !== void 0 && { connectionRole: connectedAccount.connection_role },
...connectedAccount.account_identifier !== void 0 && { accountIdentifier: connectedAccount.account_identifier },
...connectedAccount.account_display_name !== void 0 && { accountDisplayName: connectedAccount.account_display_name },
dataIntegrationId: connectedAccount.data_integration_id,
providerSlug: connectedAccount.provider_slug,
userId: connectedAccount.user_id,
organizationId: connectedAccount.organization_id,
scopes: connectedAccount.scopes,
...connectedAccount.auth_method !== void 0 && { authMethod: connectedAccount.auth_method },
...connectedAccount.api_key_last_4 !== void 0 && { apiKeyLast4: connectedAccount.api_key_last_4 },
state: connectedAccount.state,
...connectedAccount.established_by_user_id !== void 0 && { establishedByUserId: connectedAccount.established_by_user_id },
...connectedAccount.state_reason !== void 0 && { stateReason: connectedAccount.state_reason },
createdAt: new Date(connectedAccount.created_at),
updatedAt: new Date(connectedAccount.updated_at)
});
const deserializePipesConnectionFailed = (connectionFailed) => ({
object: connectionFailed.object,
dataIntegrationId: connectionFailed.data_integration_id,
providerSlug: connectionFailed.provider_slug,
userId: connectionFailed.user_id,
organizationId: connectionFailed.organization_id,
...connectionFailed.account_identifier !== void 0 && { accountIdentifier: connectionFailed.account_identifier },
errorCode: connectionFailed.error_code,
errorReason: connectionFailed.error_reason,
providerError: connectionFailed.provider_error,
providerErrorDescription: connectionFailed.provider_error_description,
createdAt: new Date(connectionFailed.created_at)
});
const deserializeEvent = (event) => {
const eventBase = {
id: event.id,
createdAt: new Date(event.created_at),
context: event.context
};
const knownEvent = deserializeKnownEvent(event, eventBase);
if (knownEvent) return knownEvent;
const unknownEvent = event;
return {
...eventBase,
event: unknownEvent.event,
data: unknownEvent.data,
context: unknownEvent.context
};
};
function deserializeKnownEvent(event, eventBase) {
switch (event.event) {
case "agent.blueprint.created":
case "agent.blueprint.updated": return {
...eventBase,
event: event.event,
data: deserializeAgentBlueprintEvent(event.data)
};
case "agent.blueprint.deleted": return {
...eventBase,
event: event.event,
data: deserializeAgentBlueprintDeletedEvent(event.data)
};
case "agent.instance.created":
case "agent.instance.deleted": return {
...eventBase,
event: event.event,
data: deserializeAgentInstance(event.data)
};
case "agent.instance.session.created": return {
...eventBase,
event: event.event,
data: deserializeAgentInstanceSessionCreatedEvent(event.data)
};
case "agent.instance.session.revoked": return {
...eventBase,
event: event.event,
data: deserializeAgentInstanceSessionEvent(event.data)
};
case "agent.registration.created": return {
...eventBase,
event: event.event,
data: deserializeAgentRegistrationCreatedEvent(event.data)
};
case "agent.registration.claim.attempt.created": return {
...eventBase,
event: event.event,
data: deserializeAgentRegistrationClaimAttemptCreatedEvent(event.data)
};
case "agent.registration.claim.completed": return {
...eventBase,
event: event.event,
data: deserializeAgentRegistrationClaimCompletedEvent(event.data)
};
case "agent.registration.credential.issued": return {
...eventBase,
event: event.event,
data: deserializeAgentRegistrationCredentialIssuedEvent(event.data)
};
case "agent.registration.organization.switched": return {
...eventBase,
event: event.event,
data: deserializeAgentRegistrationOrganizationSwitchedEvent(event.data)
};
case "agent.registration.refreshed":
case "agent.registration.expired":
case "agent.registration.revoked":
case "agent.registration.deleted": return {
...eventBase,
event: event.event,
data: deserializeAgentRegistrationLifecycleEvent(event.data)
};
case "authentication.email_verification_failed":
case "authentication.email_verification_succeeded":
case "authentication.magic_auth_failed":
case "authentication.magic_auth_succeeded":
case "authentication.mfa_failed":
case "authentication.mfa_succeeded":
case "authentication.oauth_failed":
case "authentication.oauth_succeeded":
case "authentication.passkey_failed":
case "authentication.passkey_succeeded":
case "authentication.password_failed":
case "authentication.password_succeeded":
case "authentication.reauthentication_succeeded":
case "authentication.sso_failed":
case "authentication.sso_started":
case "authentication.sso_succeeded":
case "authentication.sso_timed_out": return {
...eventBase,
event: event.event,
data: deserializeAuthenticationEvent(event.data)
};
case "authentication.radar_risk_detected": return {
...eventBase,
event: event.event,
data: deserializeAuthenticationRadarRiskDetectedEvent(event.data)
};
case "connection.activated":
case "connection.deactivated":
case "connection.deleted": return {
...eventBase,
event: event.event,
data: deserializeConnection(event.data)
};
case "dsync.activated": return {
...eventBase,
event: event.event,
data: deserializeEventDirectory(event.data)
};
case "dsync.deleted": return {
...eventBase,
event: event.event,
data: deserializeDeletedEventDirectory(event.data)
};
case "dsync.group.created":
case "dsync.group.deleted": return {
...eventBase,
event: event.event,
data: deserializeDirectoryGroup(event.data)
};
case "dsync.group.updated": return {
...eventBase,
event: event.event,
data: deserializeUpdatedEventDirectoryGroup(event.data)
};
case "dsync.group.user_added":
case "dsync.group.user_removed": return {
...eventBase,
event: event.event,
data: {
directoryId: event.data.directory_id,
user: deserializeDirectoryUser(event.data.user),
group: deserializeDirectoryGroup(event.data.group)
}
};
case "dsync.user.created":
case "dsync.user.deleted": return {
...eventBase,
event: event.event,
data: deserializeDirectoryUser(event.data)
};
case "dsync.user.updated": return {
...eventBase,
event: event.event,
data: deserializeUpdatedEventDirectoryUser(event.data)
};
case "email_verification.created": return {
...eventBase,
event: event.event,
data: deserializeEmailVerificationEvent(event.data)
};
case "invitation.accepted":
case "invitation.created":
case "invitation.revoked":
case "invitation.resent": return {
...eventBase,
event: event.event,
data: deserializeInvitationEvent(event.data)
};
case "magic_auth.created": return {
...eventBase,
event: event.event,
data: deserializeMagicAuthEvent(event.data)
};
case "password_reset.created":
case "password_reset.succeeded": return {
...eventBase,
event: event.event,
data: deserializePasswordResetEvent(event.data)
};
case "user.created":
case "user.updated":
case "user.deleted": return {
...eventBase,
event: event.event,
data: deserializeUser(event.data)
};
case "organization_membership.created":
case "organization_membership.deleted":
case "organization_membership.updated": return {
...eventBase,
event: event.event,
data: deserializeOrganizationMembership(event.data)
};
case "role.created":
case "role.deleted":
case "role.updated": return {
...eventBase,
event: event.event,
data: deserializeRoleEvent(event.data)
};
case "organization_role.created":
case "organization_role.updated":
case "organization_role.deleted": return {
...eventBase,
event: event.event,
data: deserializeOrganizationRoleEvent(event.data)
};
case "permission.created":
case "permission.updated":
case "permission.deleted": return {
...eventBase,
event: event.event,
data: deserializePermission(event.data)
};
case "session.created":
case "session.revoked": return {
...eventBase,
event: event.event,
data: deserializeSession(event.data)
};
case "organization.created":
case "organization.updated":
case "organization.deleted": return {
...eventBase,
event: event.event,
data: deserializeOrganization(event.data)
};
case "organization_domain.verification_failed": return {
...eventBase,
event: event.event,
data: deserializeOrganizationDomainVerificationFailed(event.data)
};
case "organization_domain.verified":
case "organization_domain.created":
case "organization_domain.updated":
case "organization_domain.deleted": return {
...eventBase,
event: event.event,
data: deserializeOrganizationDomain(event.data)
};
case "api_key.created":
case "api_key.revoked": return {
...eventBase,
event: event.event,
data: deserializeApiKey(event.data)
};
case "feature_flags.flag.created":
case "feature_flags.flag.deleted": return {
...eventBase,
event: event.event,
data: deserializeFeatureFlagEventData(event.data),
context: {
clientId: event.context.client_id,
actor: event.context.actor
}
};
case "feature_flags.flag.updated": return {
...eventBase,
event: event.event,
data: deserializeFeatureFlagEventData(event.data),
context: deserializeFeatureFlagUpdatedContext(event.context)
};
case "feature_flags.flag_rule.created":
case "feature_flags.flag_rule.deleted": return {
...eventBase,
event: event.event,
data: deserializeFlagRule(event.data),
context: deserializeFeatureFlagRuleContext(event.context)
};
case "feature_flags.flag_rule.updated": return {
...eventBase,
event: event.event,
data: deserializeFlagRule(event.data),
context: deserializeFeatureFlagRuleUpdatedContext(event.context)
};
case "feature_flags.flag_target.created":
case "feature_flags.flag_target.deleted": return {
...eventBase,
event: event.event,
data: deserializeFlagTargetResource(event.data),
context: {
clientId: event.context.client_id,
actor: event.context.actor
}
};
case "flag.created":
case "flag.updated":
case "flag.deleted":
case "flag.rule_updated": return {
...eventBase,
event: event.event,
data: deserializeFeatureFlag(event.data)
};
case "group.created":
case "group.updated":
case "group.deleted": return {
...eventBase,
event: event.event,
data: deserializeGroup(event.data)
};
case "group.member_added":
case "group.member_removed": return {
...eventBase,
event: event.event,
data: {
groupId: event.data.group_id,
organizationMembershipId: event.data.organization_membership_id
}
};
case "pipes.connected_account.connected":
case "pipes.connected_account.disconnected":
case "pipes.connected_account.reauthorization_needed": return {
...eventBase,
event: event.event,
data: deserializePipesConnectedAccount(event.data)
};
case "pipes.connected_account.connection_failed": return {
...eventBase,
event: event.event,
data: deserializePipesConnectionFailed(event.data)
};
case "vault.data.created": return {
...eventBase,
event: event.event,
data: deserializeVaultDataCreatedEvent(event.data)
};
case "vault.data.updated": return {
...eventBase,
event: event.event,
data: deserializeVaultDataUpdatedEvent(event.data)
};
case "vault.data.read": return {
...eventBase,
event: event.event,
data: deserializeVaultDataReadEvent(event.data)
};
case "vault.data.deleted": return {
...eventBase,
event: event.event,
data: deserializeVaultDataDeletedEvent(event.data)
};
case "vault.names.listed": return {
...eventBase,
event: event.event,
data: deserializeVaultNamesListedEvent(event.data)
};
case "vault.metadata.read": return {
...eventBase,
event: event.event,
data: deserializeVaultMetadataReadEvent(event.data)
};
case "vault.kek.created": return {
...eventBase,
event: event.event,
data: deserializeVaultKekCreatedEvent(event.data)
};
case "vault.dek.read": return {
...eventBase,
event: event.event,
data: deserializeVaultDekReadEvent(event.data)
};
case "vault.dek.decrypted": return {
...eventBase,
event: event.event,
data: deserializeVaultDekDecryptedEvent(event.data)
};
case "vault.byok_key.verification_completed": return {
...eventBase,
event: event.event,
data: deserializeVaultByokKeyVerificationCompletedEvent(event.data)
};
case "action.authentication.denied": return {
...eventBase,
event: event.event,
data: deserializeActionAuthenticationDeniedEvent(event.data)
};
case "action.user_registration.denied": return {
...eventBase,
event: event.event,
data: deserializeActionUserRegistrationDeniedEvent(event.data)
};
case "api_key.updated": return {
...eventBase,
event: event.event,
data: deserializeApiKeyUpdatedEvent(event.data)
};
case "connection.saml_certificate_renewal_required": return {
...eventBase,
event: event.event,
data: deserializeConnectionSamlCertificateRenewalRequiredEvent(event.data)
};
case "connection.saml_certificate_renewed": return {
...eventBase,
event: event.event,
data: deserializeConnectionSamlCertificateRenewedEvent(event.data)
};
case "dsync.token.created":
case "dsync.token.revoked": return {
...eventBase,
event: event.event,
data: deserializeDirectoryToken(event.data)
};
case "pipes.account_connection.connected":
case "pipes.account_connection.disconnected":
case "pipes.account_connection.reauthorization_needed": return {
...eventBase,
event: event.event,
data: deserializePipesConnectedAccount(event.data)
};
case "pipes.account_connection.add_failed":
case "pipes.account_connection.connection_failed": return {
...eventBase,
event: event.event,
data: deserializePipesConnectionFailed(event.data)
};
case "radar.challenge_created": return {
...eventBase,
event: event.event,
data: deserializeRadarChallengeCreatedEvent(event.data)
};
case "resource_export.completed":
case "resource_export.created":
case "resource_export.downloaded":
case "resource_export.failed": return {
...eventBase,
event: event.event,
data: deserializeResourceExportEvent(event.data)
};
case "vault.byok_key.deleted": return {
...eventBase,
event: event.event,
data: deserializeVaultByokKeyDeletedEvent(event.data)
};
case "vault.dek.rekeyed": return {
...eventBase,
event: event.event,
data: deserializeVaultDekRekeyedEvent(event.data)
};
case "vault.kek.deleted": return {
...eventBase,
event: event.event,
data: deserializeVaultKekDeletedEvent(event.data)
};
case "waitlist_user.approved":
case "waitlist_user.created":
case "waitlist_user.denied": return {
...eventBase,
event: event.event,
data: deserializeWaitlistUserEvent(event.data)
};
default: return;
}
}
// src/common/serializers/list.serializer.ts
const deserializeList = (list, deserializer) => ({
object: "list",
data: list.data.map(deserializer),
listMetadata: list.list_metadata
});
// src/common/serializers/pagination-options.serializer.ts
const serializePaginationOptions = (options) => ({
...options.limit !== void 0 && { limit: options.limit },
...options.after && { after: options.after },
...options.before && { before: options.before },
...options.order && { order: options.order }
});
// src/common/utils/fetch-and-deserialize.ts
const setDefaultOptions = (options) => {
return {
...options,
order: options?.order || "desc"
};
};
const fetchAndDeserialize = async (workos, endpoint, deserializeFn, options, requestOptions) => {
const { data } = await workos.get(endpoint, {
query: setDefaultOptions(options),
...requestOptions
});
return deserializeList(data, deserializeFn);
};
// src/webhooks/serializers/webhook-endpoint.serializer.ts
const deserializeWebhookEndpoint = (response) => ({
object: response.object,
id: response.id,
endpointUrl: response.endpoint_url,
secret: response.secret,
status: response.status,
events: response.events,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/webhooks/serializers/create-webhook-endpoint.serializer.ts
const serializeCreateWebhookEndpoint = (model) => ({
endpoint_url: model.endpointUrl,
events: model.events
});
// src/webhooks/serializers/update-webhook-endpoint.serializer.ts
const serializeUpdateWebhookEndpoint = (model) => ({
endpoint_url: model.endpointUrl,
status: model.status,
events: model.events
});
// src/webhooks/webhooks.ts
var Webhooks = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* List Webhook Endpoints
*
* Get a list of all of your existing webhook endpoints.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<WebhookEndpoint, PaginationOptions>>}
*/
async listWebhookEndpoints(options) {
const paginationOptions = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/webhook_endpoints", deserializeWebhookEndpoint, paginationOptions), (params) => fetchAndDeserialize(this.workos, "/webhook_endpoints", deserializeWebhookEndpoint, params), paginationOptions);
}
/**
* Create a Webhook Endpoint
*
* Create a new webhook endpoint to receive event notifications.
* @param options - Object containing endpointUrl, events.
* @param options.endpointUrl - The HTTPS URL where webhooks will be sent.
* @example "https://example.com/webhooks"
* @param options.events - The events that the Webhook Endpoint is subscribed to.
* @example ["user.created","dsync.user.created"]
* @returns {Promise<WebhookEndpoint>}
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createWebhookEndpoint(options) {
const payload = options;
const { data } = await this.workos.post("/webhook_endpoints", serializeCreateWebhookEndpoint(payload));
return deserializeWebhookEndpoint(data);
}
/**
* Update a Webhook Endpoint
*
* Update the properties of an existing webhook endpoint.
* @param options - The request body.
* @param options.id - Unique identifier of the Webhook Endpoint.
* @example "we_0123456789"
* @param options.endpointUrl - The HTTPS URL where webhooks will be sent.
* @example "https://example.com/webhooks"
* @param options.status - Whether the Webhook Endpoint is enabled or disabled.
* @example "enabled"
* @param options.events - The events that the Webhook Endpoint is subscribed to.
* @example ["user.created","dsync.user.created"]
* @returns {Promise<WebhookEndpoint>}
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateWebhookEndpoint(options) {
const { id, ...payload } = options;
const { data } = await this.workos.patch(`/webhook_endpoints/${encodeURIComponent(id)}`, serializeUpdateWebhookEndpoint(payload));
return deserializeWebhookEndpoint(data);
}
/**
* Delete a Webhook Endpoint
*
* Delete an existing webhook endpoint.
* @param options - The request options.
* @param options.id - Unique identifier of the Webhook Endpoint.
* @example "we_0123456789"
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteWebhookEndpoint(options) {
const { id } = options;
await this.workos.delete(`/webhook_endpoints/${encodeURIComponent(id)}`);
}
_signatureProvider;
get signatureProvider() {
if (!this._signatureProvider) this._signatureProvider = new SignatureProvider(this.workos.getCryptoProvider());
return this._signatureProvider;
}
get verifyHeader() {
return this.signatureProvider.verifyHeader.bind(this.signatureProvider);
}
get computeSignature() {
return this.signatureProvider.computeSignature.bind(this.signatureProvider);
}
get getTimestampAndSignatureHash() {
return this.signatureProvider.getTimestampAndSignatureHash.bind(this.signatureProvider);
}
async constructEvent({ payload, sigHeader, secret, tolerance = 18e4 }) {
const options = {
payload,
sigHeader,
secret,
tolerance
};
await this.verifyHeader(options);
const webhookPayload = this.parseVerifiedPayload(payload);
return deserializeEvent(webhookPayload);
}
parseVerifiedPayload(payload) {
if (typeof payload === "object" && !isBinaryPayload(payload)) return payload;
return JSON.parse(decodePayloadToString(payload));
}
};
// src/pkce/pkce.ts
/**
* PKCE (Proof Key for Code Exchange) utilities for OAuth 2.0 public clients.
*
* Implements RFC 7636 for secure authorization code exchange without a client secret.
* Used by Electron apps, React Native/mobile apps, CLI tools, and other public clients.
*/
var PKCE = class {
/**
* Generate a cryptographically random code verifier.
*
* @param length - Length of verifier (43-128, default 43)
* @returns RFC 7636 compliant code verifier
*/
generateCodeVerifier(length = 43) {
if (length < 43 || length > 128) throw new RangeError(`Code verifier length must be between 43 and 128, got ${length}`);
const byteLength = Math.ceil(length * 3 / 4);
const randomBytes = new Uint8Array(byteLength);
crypto.getRandomValues(randomBytes);
return this.base64UrlEncode(randomBytes).slice(0, length);
}
/**
* Generate S256 code challenge from a verifier.
*
* @param verifier - The code verifier
* @returns Base64URL-encoded SHA256 hash
*/
async generateCodeChallenge(verifier) {
const data = new TextEncoder().encode(verifier);
const hash = await crypto.subtle.digest("SHA-256", data);
return this.base64UrlEncode(new Uint8Array(hash));
}
/**
* Generate a complete PKCE pair (verifier + challenge).
*
* @returns Code verifier, challenge, and method ('S256')
*/
async generate() {
const codeVerifier = this.generateCodeVerifier();
return {
codeVerifier,
codeChallenge: await this.generateCodeChallenge(codeVerifier),
codeChallengeMethod: "S256"
};
}
base64UrlEncode(buffer) {
return btoa(String.fromCharCode(...buffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
};
// src/utils/jose.ts
let _josePromise;
/**
* Dynamically imports the jose library using import() to support Node.js 20.0-20.18.
*
* The jose library is ESM-only and cannot be loaded via require() in Node.js versions
* before 20.19.0. This wrapper uses dynamic import() which works in both ESM and CJS
* across all Node.js 20+ versions.
*
* This workaround can be removed when Node.js 20 reaches end-of-life (April 2026),
* at which point we can bump to Node.js 22+ and use direct imports.
*
* @returns Promise that resolves to the jose module
*/
function getJose() {
return _josePromise ??= Promise.resolve().then(() => require("./webapi-rpGT44g1.cjs"));
}
// src/agents/serializers/agent-instance-session.serializer.ts
function deserializeAgentInstanceSession(session) {
return {
object: session.object,
id: session.id,
agentInstanceId: session.agent_instance_id,
status: session.status,
expiresAt: new Date(session.expires_at),
revokedAt: session.revoked_at != null ? new Date(session.revoked_at) : null,
createdAt: new Date(session.created_at),
updatedAt: new Date(session.updated_at)
};
}
function serializeListAgentInstanceSessionsOptions(options) {
return {
agent_blueprint_id: options.agentBlueprintId,
agent_instance_id: options.agentInstanceId,
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
};
}
// src/agents/serializers/agent-registration.serializer.ts
function deserializeAgentRegistration(registration) {
return {
id: registration.id,
agentIdentity: {
id: registration.agent_identity.id,
userlandUserId: registration.agent_identity.userland_user_id,
createdAt: new Date(registration.agent_identity.created_at),
updatedAt: new Date(registration.agent_identity.updated_at)
},
organizationId: registration.organization_id,
status: registration.status,
kind: registration.kind,
revokedAt: registration.revoked_at != null ? new Date(registration.revoked_at) : null,
claim: registration.claim ? {
id: registration.claim.id,
claimCompletion: registration.claim.claim_completion ? {
id: registration.claim.claim_completion.id,
createdAt: new Date(registration.claim.claim_completion.created_at),
updatedAt: new Date(registration.claim.claim_completion.updated_at),
expiresAt: new Date(registration.claim.claim_completion.expires_at),
claimedAt: new Date(registration.claim.claim_completion.claimed_at)
} : null,
createdAt: new Date(registration.claim.created_at),
updatedAt: new Date(registration.claim.updated_at),
expiresAt: new Date(registration.claim.expires_at)
} : null,
createdAt: new Date(registration.created_at),
updatedAt: new Date(registration.updated_at)
};
}
// src/agents/serializers/agent-token.serializer.ts
function deserializeAgentToken(token) {
return {
accessToken: token.access_token,
tokenType: token.token_type,
expiresIn: token.expires_in,
refreshToken: token.refresh_token,
agentInstanceId: token.agent_instance_id,
newInstance: token.new_instance,
agentInstanceSessionId: token.agent_instance_session_id,
permissions: token.permissions
};
}
function serializeMintAgentTokenOptions(options) {
const intent = options.intent !== void 0 ? { intent: options.intent } : {};
switch (options.type) {
case "user_delegated": return {
type: "user_delegated",
user_access_token: options.userAccessToken,
...intent
};
case "autonomous": return {
type: "autonomous",
organization_id: options.organizationId,
...intent
};
case "agent_delegated": return {
type: "agent_delegated",
agent_access_token: options.agentAccessToken,
...intent
};
case "refresh": return {
type: "refresh",
refresh_token: options.refreshToken,
...intent
};
}
}
// src/agents/serializers/claim-attempt.serializer.ts
function serializeLinkClaimAttemptToExternalUserOptions(options) {
return {
type: "link_external_user",
claim_attempt_token: options.claimAttemptToken,
user: {
email: options.user.email,
external_id: options.user.externalId
},
...options.organizationId !== void 0 && { organization_id: options.organizationId }
};
}
function deserializeClaimAttemptResponse(response) {
return {
id: response.id,
status: response.status,
userCode: response.user_code,
organizations: response.organizations
};
}
// src/agents/serializers/validate-agent-credential.serializer.ts
function serializeValidateAgentCredentialOptions(options) {
return {
type: options.type,
credential: options.credential,
...options.type === "access_token" && options.audience !== void 0 && { audience: options.audience }
};
}
function deserializeAgentCredentialValidation(validation) {
if (!validation.valid || validation.registration_id == null) return {
valid: false,
registrationId: null,
expiresAt: null,
claims: null
};
return {
valid: true,
registrationId: validation.registration_id,
expiresAt: validation.expires_at != null ? new Date(validation.expires_at) : null,
claims: null
};
}
function deserializeAgentAccessTokenClaims(payload) {
return {
issuer: payload.iss,
audience: payload.aud,
registrationId: payload.sub,
jti: payload.jti,
organizationId: payload.org_id,
scope: payload.scope,
actor: payload.act,
expiresAt: payload.exp,
issuedAt: payload.iat
};
}
// src/agents/agents.ts
/**
* A decoded JWT payload is only an agent credential if it carries every claim
* the SDK guarantees. A token signed by the same JWKS for another purpose
* (e.g. a user session) lacks these and is rejected rather than reported valid
* with empty identifiers.
*/
function hasRequiredAgentClaims(payload) {
return typeof payload.iss === "string" && (typeof payload.aud === "string" || Array.isArray(payload.aud)) && typeof payload.sub === "string" && typeof payload.jti === "string" && typeof payload.org_id === "string" && typeof payload.exp === "number" && typeof payload.iat === "number";
}
var Agents = class {
workos;
_jwks;
constructor(workos) {
this.workos = workos;
}
/**
* Create an agent blueprint
*
* Creates an agent blueprint: the template describing what an agent may do
* (its permission ceiling), who may invoke it, and the lifetimes of its
* sessions.
*
* @param options - Configuration for the new agent blueprint.
* @returns {Promise<AgentBlueprint>}
* @throws {BadRequestException} 400
* @throws {ConflictException} 409 - Name already in use.
* @throws {UnprocessableEntityException} 422 - Permission, role, or organization not found.
*/
async createBlueprint(options) {
const { data } = await this.workos.post("/agents/blueprints", serializeCreateAgentBlueprintOptions(options));
return deserializeAgentBlueprint(data);
}
/**
* List agent blueprints
*
* Lists the agent blueprints in the current environment.
*
* @param options - Pagination options.
* @returns {Promise<AutoPaginatable<AgentBlueprint, ListAgentBlueprintsOptions>>}
*/
async listBlueprints(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/agents/blueprints", deserializeAgentBlueprint, options), (params) => fetchAndDeserialize(this.workos, "/agents/blueprints", deserializeAgentBlueprint, params), options);
}
/**
* Get an agent blueprint
*
* Retrieves an agent blueprint by ID.
* @param agentBlueprintId - Unique identifier of the agent blueprint.
*
* @example
* "agent_blueprint_01EHWNCE74X7JSDV0X3SZ3KJNY"
*
* @returns {Promise<AgentBlueprint>}
* @throws {NotFoundException} 404
*/
async getBlueprint(agentBlueprintId) {
const { data } = await this.workos.get(`/agents/blueprints/${encodeURIComponent(agentBlueprintId)}`);
return deserializeAgentBlueprint(data);
}
/**
* Update an agent blueprint
*
* Updates an agent blueprint. Omitted fields are left unchanged; provided
* lists replace the existing configuration.
*
* @param options - Object containing the agent blueprint ID and the fields to update.
* @returns {Promise<AgentBlueprint>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {ConflictException} 409 - Name already in use.
* @throws {UnprocessableEntityException} 422 - Permission, role, or organization not found.
*/
async updateBlueprint(options) {
const { agentBlueprintId, ...payload } = options;
const { data } = await this.workos.patch(`/agents/blueprints/${encodeURIComponent(agentBlueprintId)}`, serializeUpdateAgentBlueprintOptions(payload));
return deserializeAgentBlueprint(data);
}
/**
* Delete an agent blueprint
*
* Deletes an agent blueprint by ID.
* @param agentBlueprintId - Unique identifier of the agent blueprint.
*
* @example
* "agent_blueprint_01EHWNCE74X7JSDV0X3SZ3KJNY"
*
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteBlueprint(agentBlueprintId) {
await this.workos.delete(`/agents/blueprints/${encodeURIComponent(agentBlueprintId)}`);
}
/**
* Mint an agent token
*
* Mints tokens for an agent session from a blueprint. Supports
* user-delegated, autonomous, and agent-delegated mints, as well as
* refreshing an existing session with a refresh token.
*
* @param options - Object containing the agent blueprint ID, the mint type, and its credentials.
* @returns {Promise<AgentToken>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async mintToken(options) {
const { data } = await this.workos.post(`/agents/blueprints/${encodeURIComponent(options.agentBlueprintId)}/tokens`, serializeMintAgentTokenOptions(options));
return deserializeAgentToken(data);
}
/**
* List agent instances
*
* Lists the agent instances in the current environment, optionally filtered
* by organization or agent blueprint.
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<AgentInstance, SerializedListAgentInstancesOptions>>}
*/
async listInstances(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/agents/instances", deserializeAgentInstance, options ? serializeListAgentInstancesOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/agents/instances", deserializeAgentInstance, params), options ? serializeListAgentInstancesOptions(options) : void 0);
}
/**
* Get an agent instance
*
* Retrieves an agent instance by ID.
* @param agentInstanceId - Unique identifier of the agent instance.
*
* @example
* "agent_instance_01EHWNCE74X7JSDV0X3SZ3KJNY"
*
* @returns {Promise<AgentInstance>}
* @throws {NotFoundException} 404
*/
async getInstance(agentInstanceId) {
const { data } = await this.workos.get(`/agents/instances/${encodeURIComponent(agentInstanceId)}`);
return deserializeAgentInstance(data);
}
/**
* Delete an agent instance
*
* Deletes an agent instance by ID.
* @param agentInstanceId - Unique identifier of the agent instance.
*
* @example
* "agent_instance_01EHWNCE74X7JSDV0X3SZ3KJNY"
*
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteInstance(agentInstanceId) {
await this.workos.delete(`/agents/instances/${encodeURIComponent(agentInstanceId)}`);
}
/**
* List agent instance sessions
*
* Lists the agent instance sessions in the current environment, optionally
* filtered by agent blueprint or agent instance.
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<AgentInstanceSession, SerializedListAgentInstanceSessionsOptions>>}
*/
async listInstanceSessions(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/agents/sessions", deserializeAgentInstanceSession, options ? serializeListAgentInstanceSessionsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/agents/sessions", deserializeAgentInstanceSession, params), options ? serializeListAgentInstanceSessionsOptions(options) : void 0);
}
/**
* Get an agent instance session
*
* Retrieves an agent instance session by ID.
* @param agentInstanceSessionId - Unique identifier of the agent instance session.
*
* @example
* "agent_instance_session_01EHWNCE74X7JSDV0X3SZ3KJNY"
*
* @returns {Promise<AgentInstanceSession>}
* @throws {NotFoundException} 404
*/
async getInstanceSession(agentInstanceSessionId) {
const { data } = await this.workos.get(`/agents/sessions/${encodeURIComponent(agentInstanceSessionId)}`);
return deserializeAgentInstanceSession(data);
}
/**
* Revoke an agent instance session
*
* Revokes an agent instance session by ID, invalidating its tokens.
* @param agentInstanceSessionId - Unique identifier of the agent instance session.
*
* @example
* "agent_instance_session_01EHWNCE74X7JSDV0X3SZ3KJNY"
*
* @returns {Promise<AgentInstanceSession>}
* @throws {NotFoundException} 404
*/
async revokeInstanceSession(agentInstanceSessionId) {
const { data } = await this.workos.post(`/agents/sessions/${encodeURIComponent(agentInstanceSessionId)}/revoke`, {});
return deserializeAgentInstanceSession(data);
}
/**
* Link a claim attempt to an external user
*
* Link an external user to a claim attempt and retrieve the code needed
* for the agent to complete the claim. The user is looked up by external
* ID; if no user exists, one is created. When the user belongs to multiple
* organizations, an explicit organization must be provided.
*
* @param options - Object containing the claim attempt token, user details, and optional organization ID.
* @returns {Promise<ClaimAttemptResponse>}
* @throws {BadRequestException} 400 - Invalid request, email mismatch, or wrong account.
* @throws {ForbiddenException} 403 - Claim denied or auth method disabled.
* @throws {ConflictException} 409 - Organization selection required, external ID conflict, or already claimed.
* @throws {GoneException} 410 - Claim or user code expired.
*/
async linkClaimAttemptToExternalUser(options) {
const { data } = await this.workos.patch("/agents/claims/attempts", serializeLinkClaimAttemptToExternalUserOptions(options));
return deserializeClaimAttemptResponse(data);
}
/**
* Get an agent registration
*
* Retrieve a single agent registration scoped to the API key's environment.
* @param id - Unique identifier of the agent registration.
*
* @example
* "agent_reg_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @returns {Promise<AgentRegistration>}
* @throws {NotFoundException} 404
*/
async getRegistration(id) {
const { data } = await this.workos.get(`/agents/registrations/${encodeURIComponent(id)}`);
return deserializeAgentRegistration(data);
}
/**
* Validate an agent credential
*
* For `access_token` credentials, the token is decoded and verified locally
* against the environment's JWKS and its claims are returned — no network
* request is made unless `checkForRevoked` is set, in which case the WorkOS
* API is also called to confirm the token has not been revoked.
*
* For `api_key` credentials, the WorkOS API is always called to validate the
* key against the environment.
*
* @param options - Object containing the credential type and value.
* @returns {Promise<AgentCredentialValidation>}
*/
async validateCredential(options) {
if (options.type === "access_token") return this.validateAccessToken(options);
return this.validateCredentialRemotely(options);
}
async validateAccessToken(options) {
const claims = await this.verifyAccessTokenClaims(options.credential, options.audience);
if (!claims) return {
valid: false,
registrationId: null,
expiresAt: null,
claims: null
};
if (!options.checkForRevoked) return {
valid: true,
registrationId: claims.registrationId,
expiresAt: /* @__PURE__ */ new Date(claims.expiresAt * 1e3),
claims
};
const remote = await this.validateCredentialRemotely(options);
if (!remote.valid) return remote;
if (remote.registrationId !== claims.registrationId) return {
valid: false,
registrationId: null,
expiresAt: null,
claims: null
};
return {
...remote,
claims
};
}
async validateCredentialRemotely(options) {
const { data } = await this.workos.post("/agents/credentials/validate", serializeValidateAgentCredentialOptions(options));
return deserializeAgentCredentialValidation(data);
}
/**
* Verifies an access token's signature, audience, and time claims against the
* environment's JWKS and returns its decoded claims, or `null` when the token
* is invalid (bad signature, wrong audience, expired, malformed, or missing
* the agent identity claims). Errors that are not JWT validation failures
* (e.g. network errors fetching the JWKS) propagate.
*
* The audience defaults to the client ID; resource-scoped tokens carry the
* resource as their audience and require it to be passed explicitly.
*/
async verifyAccessTokenClaims(credential, audience) {
const { jwtVerify } = await getJose();
const jwks = await this.getJWKS();
try {
const { payload } = await jwtVerify(credential, jwks, { audience: audience ?? this.workos.clientId });
if (!hasRequiredAgentClaims(payload)) return null;
if (payload.exp * 1e3 <= Date.now()) return null;
return deserializeAgentAccessTokenClaims(payload);
} catch (e) {
if (e instanceof Error && "code" in e && typeof e.code === "string" && (e.code.startsWith("ERR_JWT_") || e.code.startsWith("ERR_JWS_"))) return null;
throw e;
}
}
async getJWKS() {
const { clientId } = this.workos;
if (!clientId) throw new Error("Missing client ID. Did you provide it when initializing WorkOS?");
const { createRemoteJWKSet } = await getJose();
this._jwks ??= createRemoteJWKSet(new URL(`${this.workos.baseURL}/sso/jwks/${clientId}`), { cooldownDuration: 3e5 });
return this._jwks;
}
};
// src/api-keys/serializers/create-organization-api-key-options.serializer.ts
function serializeCreateOrganizationApiKeyOptions(options) {
return {
name: options.name,
permissions: options.permissions,
expires_at: options.expiresAt?.toISOString()
};
}
// src/api-keys/serializers/created-api-key.serializer.ts
function deserializeCreatedApiKey(apiKey) {
return {
object: apiKey.object,
id: apiKey.id,
owner: apiKey.owner,
name: apiKey.name,
obfuscatedValue: apiKey.obfuscated_value,
value: apiKey.value,
lastUsedAt: apiKey.last_used_at != null ? new Date(apiKey.last_used_at) : null,
expiresAt: apiKey.expires_at != null ? new Date(apiKey.expires_at) : null,
permissions: apiKey.permissions,
createdAt: new Date(apiKey.created_at),
updatedAt: new Date(apiKey.updated_at)
};
}
// src/api-keys/serializers/validate-api-key.serializer.ts
function deserializeValidateApiKeyResponse(response) {
return {
apiKey: response.api_key ? deserializeApiKey(response.api_key) : null,
...typeof response.agent_registration_id === "undefined" ? void 0 : { agentRegistrationId: response.agent_registration_id }
};
}
// src/api-keys/api-keys.ts
var ApiKeys = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Validate API key
*
* Validate an API key value and return the API key object if valid.
* @param payload - Object containing value.
* @returns {Promise<ApiKeyValidationResponse>}
* @throws {UnauthorizedException} 401
* @throws {UnprocessableEntityException} 422
*/
async createValidation(payload) {
const { data } = await this.workos.post("/api_keys/validations", payload);
return deserializeValidateApiKeyResponse(data);
}
/**
* Delete an API key
*
* Permanently deletes an API key. This action cannot be undone. Once deleted, any requests using this API key will fail authentication.
* @param id - The unique ID of the API key.
*
* @example
* "api_key_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteApiKey(id) {
await this.workos.delete(`/api_keys/${encodeURIComponent(id)}`);
}
/**
* List API keys for an organization
*
* Get a list of all API keys for an organization.
* @param organizationId - Unique identifier of the Organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<ApiKey>>}
* @throws {NotFoundException} 404
*/
async listOrganizationApiKeys(options) {
const { organizationId, ...paginationOptions } = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/organizations/${encodeURIComponent(organizationId)}/api_keys`, deserializeApiKey, paginationOptions), (params) => fetchAndDeserialize(this.workos, `/organizations/${encodeURIComponent(organizationId)}/api_keys`, deserializeApiKey, params), paginationOptions);
}
/**
* Create an API key for an organization
*
* Create a new API key for an organization.
* @param organizationId - Unique identifier of the Organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param options - Object containing name, permissions, and expiresAt.
* @returns {Promise<ApiKeyWithValue>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createOrganizationApiKey(options, requestOptions = {}) {
const { organizationId } = options;
const { data } = await this.workos.post(`/organizations/${encodeURIComponent(organizationId)}/api_keys`, serializeCreateOrganizationApiKeyOptions(options), requestOptions);
return deserializeCreatedApiKey(data);
}
};
// src/connect/serializers/external-auth-complete-response.serializer.ts
const deserializeExternalAuthCompleteResponse = (response) => ({ redirectUri: response.redirect_uri });
// src/connect/serializers/token-exchange-response.serializer.ts
const deserializeTokenExchangeResponse = (response) => ({
accessToken: response.access_token,
issuedTokenType: response.issued_token_type,
tokenType: response.token_type,
expiresIn: response.expires_in,
...response.scope !== void 0 && { scope: response.scope }
});
// src/connect/serializers/application-credentials-list-item.serializer.ts
const deserializeApplicationCredentialsListItem = (response) => ({
object: response.object,
id: response.id,
secretHint: response.secret_hint,
lastUsedAt: response.last_used_at != null ? new Date(response.last_used_at) : null,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/connect/serializers/new-connect-application-secret.serializer.ts
const deserializeNewConnectApplicationSecret = (response) => ({
object: response.object,
id: response.id,
secretHint: response.secret_hint,
lastUsedAt: response.last_used_at != null ? new Date(response.last_used_at) : null,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at),
secret: response.secret
});
// src/connect/serializers/user-object.serializer.ts
const serializeUserObject = (model) => ({
id: model.id,
email: model.email,
first_name: model.firstName,
last_name: model.lastName,
metadata: model.metadata
});
// src/connect/serializers/user-consent-option-choice.serializer.ts
const serializeUserConsentOptionChoice = (model) => ({
value: model.value,
label: model.label
});
// src/connect/serializers/user-consent-option.serializer.ts
const serializeUserConsentOption = (model) => ({
claim: model.claim,
type: model.type,
label: model.label,
choices: model.choices.map(serializeUserConsentOptionChoice)
});
// src/connect/serializers/user-management-login-request.serializer.ts
const serializeUserManagementLoginRequest = (model) => ({
external_auth_id: model.externalAuthId,
user: serializeUserObject(model.user),
user_consent_options: model.userConsentOptions != null ? model.userConsentOptions.map(serializeUserConsentOption) : void 0
});
// src/connect/serializers/redirect-uri-input.serializer.ts
const serializeRedirectUriInput = (model) => ({
uri: model.uri,
default: model.default ?? null
});
// src/connect/serializers/create-oauth-application.serializer.ts
const serializeCreateOAuthApplication = (model) => ({
name: model.name,
application_type: model.applicationType,
description: model.description ?? null,
scopes: model.scopes ?? null,
redirect_uris: model.redirectUris != null ? model.redirectUris.map(serializeRedirectUriInput) : null,
uses_pkce: model.usesPkce ?? null,
is_first_party: model.isFirstParty,
organization_id: model.organizationId ?? null
});
// src/connect/serializers/create-m2m-application.serializer.ts
const serializeCreateM2MApplication = (model) => ({
name: model.name,
application_type: model.applicationType,
description: model.description ?? null,
scopes: model.scopes ?? null,
organization_id: model.organizationId
});
// src/connect/serializers/update-oauth-application.serializer.ts
const serializeUpdateOAuthApplication = (model) => ({
name: model.name,
description: model.description ?? null,
scopes: model.scopes ?? null,
redirect_uris: model.redirectUris != null ? model.redirectUris.map(serializeRedirectUriInput) : null
});
// src/connect/serializers/create-application-secret.serializer.ts
const serializeCreateApplicationSecret = (_model) => ({});
// src/connect/connect.ts
const serializeListApplicationsOptions = (options) => {
const wire = {
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
};
if (options.organizationId !== void 0) wire.organization_id = options.organizationId;
return wire;
};
var Connect = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Complete external authentication
*
* Completes an external authentication flow and returns control to AuthKit. This endpoint is used with [Standalone Connect](https://workos.com/docs/authkit/connect/standalone) to bridge your existing authentication system with the Connect OAuth API infrastructure.
*
* After successfully authenticating a user in your application, calling this endpoint will:
*
* - Create or update the user in AuthKit, using the given `id` as its `external_id`.
* - Return a `redirect_uri` your application should redirect to in order for AuthKit to complete the flow
*
* Users are automatically created or updated based on the `id` and `email` provided. If a user with the same `id` exists, their information is updated. Otherwise, a new user is created.
*
* If you provide a new `id` with an `email` that already belongs to an existing user, the request will fail with an error as email addresses are unique to a user.
* @param options - Object containing externalAuthId, user.
* @param options.externalAuthId - Identifier provided when AuthKit redirected to your login page.
* @example "ext_auth_01HXYZ123456789ABCDEFGHIJ"
* @param options.user - The user to create or update in AuthKit.
* @param options.userConsentOptions - Array of [User Consent Options](https://workos.com/docs/reference/workos-connect/standalone/user-consent-options) to store with the session.
* @returns {Promise<ExternalAuthCompleteResponse>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async completeOAuth2(options) {
const payload = options;
const { data } = await this.workos.post("/authkit/oauth2/complete", serializeUserManagementLoginRequest(payload));
return deserializeExternalAuthCompleteResponse(data);
}
/**
* Exchange an access token for one issued to another Resource Indicator
*
* Performs an [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange against the environment's
* `/oauth2/token` endpoint, authenticating as a first-party Connect Application with its client ID and client
* secret. The issued access token keeps the subject token's user and consent and is audienced to `resource`.
*
* Unlike other SDK methods this does not call the WorkOS API with your API key: the request goes to the
* environment's issuer (AuthKit domain) using the Connect Application's credentials. The client's `fetchFn`,
* `timeout`, `maxRetries` and `config` options still apply.
* @param options - Object containing issuer, clientId, clientSecret, subjectToken, resource, scope.
* @returns {Promise<TokenExchangeResponse>}
* @throws {OauthException} `invalid_client`, `unauthorized_client`, `invalid_grant`, `invalid_target`,
* `invalid_scope`, `unsupported_grant_type`
*/
async exchangeToken(options) {
const { issuer, clientId, clientSecret, subjectToken, resource, scope } = options;
const path = "/oauth2/token";
const client = this.createIssuerHttpClient(issuer);
const body = new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
subject_token: subjectToken,
subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
resource,
...scope !== void 0 && { scope }
});
let res;
try {
res = await client.post(path, body, {});
} catch (error) {
this.throwOauthErrorFromTokenEndpoint(error);
this.workos.handleHttpError({
path,
error
});
throw error;
}
const data = await this.workos.readResponseJSON(path, res);
return deserializeTokenExchangeResponse(data);
}
/**
* Builds an HTTP client for the environment's issuer that carries the SDK's
* transport settings (`fetchFn`, `timeout`, `maxRetries`, `config`) but not
* the WorkOS API key.
*/
createIssuerHttpClient(issuer) {
const { config, timeout, maxRetries, fetchFn } = this.workos.options;
return new FetchHttpClient(issuer, {
...config,
timeout,
maxRetries,
headers: { "User-Agent": `workos-node/${this.workos.version}` }
}, fetchFn);
}
/**
* The token endpoint reports client authentication failures as a 401 with
* an RFC 6749 error body; surface that as an `OauthException` instead of the
* generic `UnauthorizedException` used for API-key failures.
*/
throwOauthErrorFromTokenEndpoint(error) {
if (!(error instanceof HttpClientError) || !error.response) return;
const { status, data, headers } = error.response;
if (status === 401 && (data.error || data.error_description)) throw new OauthException(status, headers.get("X-Request-ID") ?? "", data.error, data.error_description, data);
}
/**
* List Connect Applications
*
* List all Connect Applications in the current environment with optional filtering.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<ConnectApplication, ListApplicationsOptions>>}
* @throws {UnprocessableEntityException} 422
*/
async listApplications(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/connect/applications", deserializeConnectApplication, options ? serializeListApplicationsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/connect/applications", deserializeConnectApplication, params), options ? serializeListApplicationsOptions(options) : void 0);
}
/**
* Create a Connect Application
*
* Create a new Connect Application. Supports both OAuth and Machine-to-Machine (M2M) application types.
* @param options - The request body.
* @returns {Promise<ConnectApplication>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createApplication(options) {
const payload = options;
const { data } = await this.workos.post("/connect/applications", (() => {
switch (payload.applicationType) {
case "oauth": return serializeCreateOAuthApplication(payload);
case "m2m": return serializeCreateM2MApplication(payload);
default: throw new Error(`Unknown applicationType: ${payload.applicationType}`);
}
})());
return deserializeConnectApplication(data);
}
/**
* Create oauth application.
* @param name - The name of the application.
* @param isFirstParty - Whether this is a first-party application. Third-party applications require an organization_id.
* @param description - A description for the application.
* @param scopes - The OAuth scopes granted to the application.
* @param redirectUris - Redirect URIs for the application.
* @param usesPkce - Whether the application uses PKCE (Proof Key for Code Exchange).
* @param organizationId - The organization ID this application belongs to. Required when is_first_party is false.
* @returns {Promise<ConnectApplication>}
*/
async createOAuthApplication(name, isFirstParty, description, scopes, redirectUris, usesPkce, organizationId) {
const body = {
application_type: "oauth",
name,
is_first_party: isFirstParty
};
if (description !== void 0) body.description = description;
if (scopes !== void 0) body.scopes = scopes;
if (redirectUris !== void 0) body.redirect_uris = redirectUris;
if (usesPkce !== void 0) body.uses_pkce = usesPkce;
if (organizationId !== void 0) body.organization_id = organizationId;
const { data } = await this.workos.post("/connect/applications", body);
return deserializeConnectApplication(data);
}
/**
* Create m2m application.
* @param name - The name of the application.
* @param organizationId - The organization ID this application belongs to.
* @param description - A description for the application.
* @param scopes - The OAuth scopes granted to the application.
* @returns {Promise<ConnectApplication>}
*/
async createM2MApplication(name, organizationId, description, scopes) {
const body = {
application_type: "m2m",
name,
organization_id: organizationId
};
if (description !== void 0) body.description = description;
if (scopes !== void 0) body.scopes = scopes;
const { data } = await this.workos.post("/connect/applications", body);
return deserializeConnectApplication(data);
}
/**
* Get a Connect Application
*
* Retrieve details for a specific Connect Application by ID or client ID.
* @param options - The request options.
* @param options.id - The application ID or client ID of the Connect Application.
* @example "conn_app_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<ConnectApplication>}
* @throws {NotFoundException} 404
*/
async getApplication(options) {
const { id } = options;
const { data } = await this.workos.get(`/connect/applications/${encodeURIComponent(id)}`);
return deserializeConnectApplication(data);
}
/**
* Update a Connect Application
*
* Update an existing Connect Application. For OAuth applications, you can update redirect URIs. For all applications, you can update the name, description, and scopes.
* @param options - The request body.
* @param options.id - The application ID or client ID of the Connect Application.
* @example "conn_app_01HXYZ123456789ABCDEFGHIJ"
* @param options.name - The name of the application.
* @example "My Application"
* @param options.description - A description for the application.
* @example "An application for managing user access"
* @param options.scopes - The OAuth scopes granted to the application.
* @example ["openid","profile","email"]
* @param options.redirectUris - Updated redirect URIs for the application. OAuth applications only.
* @example [{"uri":"https://example.com/callback","default":true}]
* @returns {Promise<ConnectApplication>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updateApplication(options) {
const { id, ...payload } = options;
const { data } = await this.workos.put(`/connect/applications/${encodeURIComponent(id)}`, serializeUpdateOAuthApplication(payload));
return deserializeConnectApplication(data);
}
/**
* Delete a Connect Application
*
* Delete an existing Connect Application.
* @param options - The request options.
* @param options.id - The application ID or client ID of the Connect Application.
* @example "conn_app_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteApplication(options) {
const { id } = options;
await this.workos.delete(`/connect/applications/${encodeURIComponent(id)}`);
}
/**
* List Client Secrets for a Connect Application
*
* List all client secrets associated with a Connect Application.
* @param options - The request options.
* @param options.id - The application ID or client ID of the Connect Application.
* @example "conn_app_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<ApplicationCredentialsListItem[]>}
* @throws {NotFoundException} 404
*/
async listApplicationClientSecrets(options) {
const { id } = options;
const { data } = await this.workos.get(`/connect/applications/${encodeURIComponent(id)}/client_secrets`);
return data.map(deserializeApplicationCredentialsListItem);
}
/**
* Create a new client secret for a Connect Application
*
* Create new secrets for a Connect Application.
* @param options - The request body.
* @param options.id - The application ID or client ID of the Connect Application.
* @example "conn_app_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<NewConnectApplicationSecret>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createApplicationClientSecret(options) {
const { id, ...payload } = options;
const { data } = await this.workos.post(`/connect/applications/${encodeURIComponent(id)}/client_secrets`, serializeCreateApplicationSecret(payload));
return deserializeNewConnectApplicationSecret(data);
}
/**
* Delete a Client Secret
*
* Delete (revoke) an existing client secret.
* @param options - The request options.
* @param options.id - The unique ID of the client secret.
* @example "secret_01J9Q2Z3X4Y5W6V7U8T9S0R1Q"
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteClientSecret(options) {
const { id } = options;
await this.workos.delete(`/connect/client_secrets/${encodeURIComponent(id)}`);
}
};
// src/directory-sync/directory-sync.ts
const serializeListDirectoriesOptions = (options) => {
const wire = {
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
};
if (options.organizationId !== void 0) wire.organization_id = options.organizationId;
if (options.search !== void 0) wire.search = options.search;
return wire;
};
const serializeListUsersInDirectoryOptions = (options) => {
const wire = {
limit: options.limit,
before: options.before,
after: options.after,
order: options.order,
group: options.group,
email: options.email
};
if (options.idpId !== void 0) wire.idp_id = options.idpId;
return wire;
};
var DirectorySync = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* List Directories
*
* Get a list of all of your existing directories matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Directory, PaginationOptions>>}
* @throws {AuthorizationException} 403
* @throws {UnprocessableEntityException} 422
*/
async listDirectories(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/directories", deserializeDirectory, options ? serializeListDirectoriesOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/directories", deserializeDirectory, params), options ? serializeListDirectoriesOptions(options) : void 0);
}
/**
* Get a Directory
*
* Get the details of an existing directory.
* @param options - The request options.
* @param options.id - Unique identifier for the Directory.
* @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
* @returns {Promise<Directory>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async getDirectory(options) {
const { id } = options;
const { data } = await this.workos.get(`/directories/${encodeURIComponent(id)}`);
return deserializeDirectory(data);
}
/**
* Delete a Directory
*
* Permanently deletes an existing directory. It cannot be undone.
* @param options - The request options.
* @param options.id - Unique identifier for the Directory.
* @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
* @returns {Promise<void>}
* @throws {AuthorizationException} 403
*/
async deleteDirectory(options) {
const { id } = options;
await this.workos.delete(`/directories/${encodeURIComponent(id)}`);
}
/**
* List Directory Groups
*
* Get a list of all of existing directory groups matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<DirectoryGroup, ListDirectoryGroupsOptions>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
* @deprecated Use {@link DirectorySync.listDirectoryGroups} instead.
*/
async listGroups(options) {
const paginationOptions = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/directory_groups", deserializeDirectoryGroup, paginationOptions), (params) => fetchAndDeserialize(this.workos, "/directory_groups", deserializeDirectoryGroup, params), paginationOptions);
}
/**
* Get a Directory Group
*
* Get the details of an existing Directory Group.
* @param options - The request options.
* @param options.id - Unique identifier for the Directory Group.
* @example "directory_group_01E1JJS84MFPPQ3G655FHTKX6Z"
* @returns {Promise<DirectoryGroup>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @deprecated Use {@link DirectorySync.getDirectoryGroup} instead.
*/
async getGroup(options) {
const { id } = options;
const { data } = await this.workos.get(`/directory_groups/${encodeURIComponent(id)}`);
return deserializeDirectoryGroup(data);
}
/**
* List Directory Users
*
* Get a list of all of existing Directory Users matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<DirectoryUserWithGroups<TCustomAttributes>, ListDirectoryUsersOptions>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
* @throws {RateLimitExceededException} 429
* @deprecated Use {@link DirectorySync.listDirectoryUsers} instead.
*/
async listUsers(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/directory_users", deserializeDirectoryUserWithGroups, options), (params) => fetchAndDeserialize(this.workos, "/directory_users", deserializeDirectoryUserWithGroups, params), options);
}
/**
* Get a Directory User
*
* Get the details of an existing Directory User.
* @param options - The request options.
* @param options.id - Unique identifier for the Directory User.
* @example "directory_user_01E1JG7J09H96KYP8HM9B0G5SJ"
* @returns {Promise<DirectoryUserWithGroups<TCustomAttributes>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @deprecated Use {@link DirectorySync.getDirectoryUser} instead.
*/
async getUser(options) {
const { id } = options;
const { data } = await this.workos.get(`/directory_users/${encodeURIComponent(id)}`);
return deserializeDirectoryUserWithGroups(data);
}
/**
* List Users for a Directory
*
* Get a list of the Directory Users in a Directory, optionally filtered to the members of a Directory Group.
* @param options - Pagination and filter options.
* @param options.directoryId - Unique identifier of the Directory.
* @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
* @param options.group - Filter Directory Users to the members of this Directory Group.
* @example "directory_group_01E64QTDNS0EGJ0FMCVY9BWGZT"
* @param options.idpId - Filter Directory Users by the identity provider's unique identifier.
* @example "2836"
* @param options.email - Filter Directory Users by their primary email address.
* @example "jane.doe@example.com"
* @returns {Promise<AutoPaginatable<DirectoryUser<TCustomAttributes>, PaginationOptions>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listDirectoryUsers(options) {
const { directoryId, ...rest } = options;
const endpoint = `/directories/${encodeURIComponent(directoryId)}/users`;
const wire = serializeListUsersInDirectoryOptions(rest);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryUser, wire), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryUser, params), wire);
}
/**
* Get a User for a Directory
*
* Get the details of a Directory User in a Directory.
* @param options - The request options.
* @param options.directoryId - Unique identifier of the Directory.
* @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
* @param options.userId - Unique identifier for the Directory User.
* @example "directory_user_01E1JG7J09H96KYP8HM9B0G5SJ"
* @returns {Promise<DirectoryUser<TCustomAttributes>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async getDirectoryUser(options) {
const { directoryId, userId } = options;
const { data } = await this.workos.get(`/directories/${encodeURIComponent(directoryId)}/users/${encodeURIComponent(userId)}`);
return deserializeDirectoryUser(data);
}
/**
* List Groups for a Directory
*
* Get a list of the Directory Groups in a Directory, optionally filtered to the groups a Directory User belongs to.
* @param options - Pagination and filter options.
* @param options.directoryId - Unique identifier of the Directory.
* @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
* @param options.user - Filter Directory Groups to those this Directory User belongs to.
* @example "directory_user_01E1JG7J09H96KYP8HM9B0G5SJ"
* @returns {Promise<AutoPaginatable<DirectoryGroup, PaginationOptions>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listDirectoryGroups(options) {
const { directoryId, ...wire } = options;
const endpoint = `/directories/${encodeURIComponent(directoryId)}/groups`;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryGroup, wire), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryGroup, params), wire);
}
/**
* Get a Group for a Directory
*
* Get the details of a Directory Group in a Directory.
* @param options - The request options.
* @param options.directoryId - Unique identifier of the Directory.
* @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
* @param options.groupId - Unique identifier for the Directory Group.
* @example "directory_group_01E1JJS84MFPPQ3G655FHTKX6Z"
* @returns {Promise<DirectoryGroup>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async getDirectoryGroup(options) {
const { directoryId, groupId } = options;
const { data } = await this.workos.get(`/directories/${encodeURIComponent(directoryId)}/groups/${encodeURIComponent(groupId)}`);
return deserializeDirectoryGroup(data);
}
};
// src/events/serializers/list-event-options.serializer.ts
const serializeListEventOptions = (options) => ({
events: options.events,
organization_id: options.organizationId,
range_start: options.rangeStart,
range_end: options.rangeEnd,
limit: options.limit,
after: options.after
});
// src/events/events.ts
var Events = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* List events
*
* List events for the current environment.
* @param options - Pagination and filter options.
* @returns {Promise<List<Event>>}
* @throws {BadRequestException} 400
* @throws {UnprocessableEntityException} 422
*/
async listEvents(options) {
const { data } = await this.workos.get(`/events`, { query: options ? serializeListEventOptions(options) : void 0 });
return deserializeList(data, deserializeEvent);
}
};
// src/common/utils/encode-path-parameter.ts
/**
* Encode a caller-supplied identifier for safe interpolation into a single URL
* path segment.
*
* SDK path templates interpolate caller-supplied identifiers (user IDs,
* invitation tokens, MFA factor IDs, organization IDs, external IDs, role and
* permission slugs, ...) into the request path. Without encoding, a value such
* as `../../user_management/users/user_01ABC` would be resolved by the WHATWG
* `URL` parser (see `HttpClient.getResourceURL`) into a different API path,
* letting an attacker who influences one identifier retarget the request to an
* arbitrary same-verb endpoint. `encodeURIComponent` neutralizes this by
* percent-encoding the path/query/fragment metacharacters (`/`, `?`, `#`, ...)
* that enable the injection, keeping one parameter mapped to exactly one path
* segment.
*
* `encodeURIComponent` alone is not sufficient for the two dot-only segments
* `.` and `..`: it leaves them unchanged, and the WHATWG `URL` parser then
* removes them as relative path segments (even when a value like `..` is a
* single segment, a template such as `/feature-flags/${slug}/enable` supplies
* the trailing segment, so `..` still climbs and retargets the request).
* Percent-encoding the dots does not help because the parser also treats the
* `%2e` forms as dot segments. A `.` or `..` is never a valid WorkOS
* identifier, so we fail closed and throw rather than emit an ambiguous path.
*
* The one deviation from `encodeURIComponent` is that a literal `:` is kept
* unescaped. Colons are valid path-segment characters (RFC 3986 `pchar`) and
* are used by WorkOS RBAC slugs (e.g. `users:read`); an interpolated value is
* always preceded by a `/`-delimited segment, so a `:` can never be read as a
* URL scheme. Preserving it keeps the wire format identical for existing slugs.
*/
function encodePathParameter(value) {
const encoded = encodeURIComponent(value).replace(/%3A/gi, ":");
if (encoded === "." || encoded === "..") throw new TypeError("Invalid path parameter: a path parameter must not be \".\" or \"..\".");
return encoded;
}
// src/organizations/organizations.ts
var Organizations = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* List Organizations
*
* Get a list of all of your existing organizations matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Organization, ListOrganizationsOptions>>}
* @throws {UnprocessableEntityException} 422
*/
async listOrganizations(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/organizations", deserializeOrganization, options), (params) => fetchAndDeserialize(this.workos, "/organizations", deserializeOrganization, params), options);
}
/**
* Create an Organization
*
* Creates a new organization in the current environment.
* @param payload - Object containing name.
* @returns {Promise<Organization>}
* @throws {BadRequestException} 400
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createOrganization(payload, requestOptions = {}) {
const { data } = await this.workos.post("/organizations", serializeCreateOrganizationOptions(payload), requestOptions);
return deserializeOrganization(data);
}
/**
* Delete an Organization
*
* Permanently deletes an organization in the current environment. It cannot be undone.
* @param id - Unique identifier of the Organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @returns {Promise<void>}
* @throws 403 response from the API.
*/
async deleteOrganization(id) {
await this.workos.delete(`/organizations/${encodePathParameter(id)}`);
}
/**
* Get an Organization
*
* Get the details of an existing organization.
* @param id - Unique identifier of the Organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @returns {Promise<Organization>}
* @throws {NotFoundException} 404
*/
async getOrganization(id) {
const { data } = await this.workos.get(`/organizations/${encodePathParameter(id)}`);
return deserializeOrganization(data);
}
/**
* Get an Organization by External ID
*
* Get the details of an existing organization by an [external identifier](https://workos.com/docs/authkit/metadata/external-identifiers).
* @param externalId - The external ID of the Organization.
*
* @example
* "2fe01467-f7ea-4dd2-8b79-c2b4f56d0191"
*
* @returns {Promise<Organization>}
* @throws {NotFoundException} 404
*/
async getOrganizationByExternalId(externalId) {
const { data } = await this.workos.get(`/organizations/external_id/${encodePathParameter(externalId)}`);
return deserializeOrganization(data);
}
/**
* Update an Organization
*
* Updates an organization in the current environment.
* @param payload - The request body.
* @returns {Promise<Organization>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateOrganization(options) {
const { organization: organizationId, ...payload } = options;
const { data } = await this.workos.put(`/organizations/${encodePathParameter(organizationId)}`, serializeUpdateOrganizationOptions(payload));
return deserializeOrganization(data);
}
/**
* List IT Contacts
*
* Get the IT Contacts for an Organization.
* @param options - Object containing the Organization ID.
* @returns {Promise<List<ItContact>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async listItContacts(options) {
const { organizationId } = options;
const { data } = await this.workos.get(`/organizations/${encodePathParameter(organizationId)}/it_contacts`);
return {
object: data.object,
data: data.data.map(deserializeItContact),
listMetadata: {
before: data.list_metadata.before,
after: data.list_metadata.after
}
};
}
/**
* Create an IT Contact
*
* Add an IT Contact to an Organization. No Admin Portal invitation is sent,
* though the contact is notified if the Organization has a connection
* certificate nearing expiry.
* @param options - Object containing the Organization ID and the email address.
* @returns {Promise<ItContact>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createItContact(options) {
const { organizationId, ...payload } = options;
const { data } = await this.workos.post(`/organizations/${encodePathParameter(organizationId)}/it_contacts`, serializeCreateItContactOptions(payload));
return deserializeItContact(data);
}
/**
* Delete an IT Contact
*
* Remove an IT Contact from an Organization and revoke the contact's active
* setup links.
* @param options - Object containing the Organization ID and the IT Contact ID.
* @returns {Promise<void>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async deleteItContact(options) {
const { organizationId, contactId } = options;
await this.workos.delete(`/organizations/${encodePathParameter(organizationId)}/it_contacts/${encodePathParameter(contactId)}`);
}
/**
* Invite an IT Contact
*
* Create an Admin Portal setup link and email it to the IT Contact. An
* Organization can have at most one active invitation.
* @param options - Object containing the Organization ID, the IT Contact ID and the intents.
* @returns {Promise<void>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async inviteItContact(options) {
const { organizationId, contactId, ...payload } = options;
await this.workos.post(`/organizations/${encodePathParameter(organizationId)}/it_contacts/${encodePathParameter(contactId)}/invite`, serializeInviteItContactOptions(payload));
}
/**
* Revoke an IT Contact's invitation
*
* Revoke the Organization's active Admin Portal invitation.
* @param options - Object containing the Organization ID and the IT Contact ID.
* @returns {Promise<void>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async revokeItContact(options) {
const { organizationId, contactId } = options;
await this.workos.post(`/organizations/${encodePathParameter(organizationId)}/it_contacts/${encodePathParameter(contactId)}/revoke`, {});
}
};
// src/organization-domains/serializers/create-organization-domain-options.serializer.ts
const serializeCreateOrganizationDomainOptions = (options) => ({
domain: options.domain,
organization_id: options.organizationId
});
// src/organization-domains/organization-domains.ts
var OrganizationDomains = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Get an Organization Domain
*
* Get the details of an existing organization domain.
* @param id - Unique identifier of the organization domain.
*
* @example
* "org_domain_01EHZNVPK2QXHMVWCEDQEKY69A"
*
* @returns {Promise<OrganizationDomain>}
* @throws {NotFoundException} 404
*/
async getOrganizationDomain(id) {
const { data } = await this.workos.get(`/organization_domains/${encodePathParameter(id)}`);
return deserializeOrganizationDomain(data);
}
/**
* Verify an Organization Domain
*
* Initiates verification process for an Organization Domain.
* @param id - Unique identifier of the organization domain.
*
* @example
* "org_domain_01EHZNVPK2QXHMVWCEDQEKY69A"
*
* @returns {Promise<OrganizationDomain>}
* @throws {BadRequestException} 400
*/
async verifyOrganizationDomain(id) {
const { data } = await this.workos.post(`/organization_domains/${encodePathParameter(id)}/verify`, {});
return deserializeOrganizationDomain(data);
}
/**
* Create an Organization Domain
*
* Creates a new Organization Domain.
* @param payload - Object containing domain, organizationId.
* @returns {Promise<OrganizationDomain>}
* @throws {ConflictException} 409
*/
async createOrganizationDomain(payload) {
const { data } = await this.workos.post(`/organization_domains`, serializeCreateOrganizationDomainOptions(payload));
return deserializeOrganizationDomain(data);
}
/**
* Delete an Organization Domain
*
* Permanently deletes an organization domain. It cannot be undone.
* @param id - Unique identifier of the organization domain.
*
* @example
* "org_domain_01EHZNVPK2QXHMVWCEDQEKY69A"
*
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteOrganizationDomain(id) {
await this.workos.delete(`/organization_domains/${encodePathParameter(id)}`);
}
};
// src/passwordless/serializers/passwordless-session.serializer.ts
const deserializePasswordlessSession = (passwordlessSession) => ({
id: passwordlessSession.id,
email: passwordlessSession.email,
expiresAt: new Date(passwordlessSession.expires_at),
link: passwordlessSession.link,
object: passwordlessSession.object
});
// src/passwordless/passwordless.ts
var Passwordless = class {
workos;
constructor(workos) {
this.workos = workos;
}
async createSession({ redirectURI, expiresIn, ...options }) {
const { data } = await this.workos.post("/passwordless/sessions", {
...options,
redirect_uri: redirectURI,
expires_in: expiresIn
});
return deserializePasswordlessSession(data);
}
async sendSession(sessionId) {
const { data } = await this.workos.post(`/passwordless/sessions/${encodePathParameter(sessionId)}/send`, {});
return data;
}
};
// src/pipes/serializers/data-integration-credential.serializer.ts
const deserializeDataIntegrationCredential = (response) => ({
type: response.type,
clientId: response.client_id ?? null,
redactedClientSecret: response.redacted_client_secret ?? null
});
// src/pipes/serializers/data-integration-installation.serializer.ts
const deserializeDataIntegrationInstallation = (response) => ({
id: response.id,
connectionRole: response.connection_role,
accountIdentifier: response.account_identifier ?? null,
accountDisplayName: response.account_display_name ?? null,
userId: response.user_id ?? null,
organizationId: response.organization_id ?? null,
apiKeyLast4: response.api_key_last_4 ?? null
});
// src/pipes/serializers/data-integration-custom-provider.serializer.ts
const deserializeDataIntegrationCustomProvider = (response) => ({
name: response.name,
authorizationUrl: response.authorization_url ?? null,
tokenUrl: response.token_url ?? null,
refreshTokenUrl: response.refresh_token_url ?? null,
pkceEnabled: response.pkce_enabled,
requestScopeSeparator: response.request_scope_separator,
scopesRequired: response.scopes_required,
clientSecretRequired: response.client_secret_required,
additionalAuthorizationParameters: response.additional_authorization_parameters,
tokenBodyContentType: response.token_body_content_type,
authenticateVia: response.authenticate_via
});
// src/pipes/serializers/data-integration.serializer.ts
const deserializeDataIntegration = (response) => ({
object: response.object,
id: response.id,
slug: response.slug,
integrationType: response.integration_type,
ownership: response.ownership,
description: response.description ?? null,
enabled: response.enabled,
state: response.state,
scopes: response.scopes ?? null,
redirectUri: response.redirect_uri,
authMethods: response.auth_methods,
credentials: response.credentials != null ? deserializeDataIntegrationCredential(response.credentials) : null,
installation: response.installation != null ? deserializeDataIntegrationInstallation(response.installation) : null,
config: response.config,
customProvider: response.custom_provider != null ? deserializeDataIntegrationCustomProvider(response.custom_provider) : null,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/pipes/serializers/connected-account-warning.serializer.ts
const deserializeConnectedAccountWarning = (response) => ({
code: response.code,
message: response.message
});
// src/pipes/serializers/connected-account.serializer.ts
const deserializeConnectedAccount = (response) => ({
object: response.object,
id: response.id,
connectionRole: response.connection_role,
accountIdentifier: response.account_identifier ?? null,
accountDisplayName: response.account_display_name ?? null,
userId: response.user_id ?? null,
organizationId: response.organization_id ?? null,
scopes: response.scopes,
authMethod: response.auth_method,
apiKeyLast4: response.api_key_last_4 ?? null,
clientId: response.client_id ?? null,
clientSecretLast4: response.client_secret_last_4 ?? null,
config: response.config,
state: response.state,
establishedByUserId: response.established_by_user_id ?? null,
stateReason: response.state_reason ?? null,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at),
warnings: response.warnings != null ? response.warnings.map(deserializeConnectedAccountWarning) : void 0
});
// src/pipes/serializers/data-integration-finish-connection-response.serializer.ts
const deserializeDataIntegrationFinishConnectionResponse = (response) => ({ connectedAccount: deserializeConnectedAccount(response.connected_account) });
// src/pipes/serializers/data-integration-authorize-url-response.serializer.ts
const deserializeDataIntegrationAuthorizeUrlResponse = (response) => ({
url: response.url,
state: response.state ?? "",
completion: response.completion
});
// src/pipes/serializers/data-integration-vended-credential.serializer.ts
const deserializeDataIntegrationVendedCredential = (response) => {
switch (response.auth_method) {
case "oauth": return {
authMethod: "oauth",
object: response.object,
value: response.value,
expiresAt: response.expires_at != null ? new Date(response.expires_at) : null,
scopes: response.scopes,
missingScopes: response.missing_scopes,
metadata: response.metadata,
config: response.config
};
case "api_key": return {
authMethod: "api_key",
object: response.object,
value: response.value,
config: response.config
};
case "client_credentials": return {
authMethod: "client_credentials",
object: response.object,
value: response.value,
expiresAt: response.expires_at != null ? new Date(response.expires_at) : null,
scopes: response.scopes,
missingScopes: response.missing_scopes,
metadata: response.metadata,
config: response.config
};
default: throw new Error("Unknown auth_method: " + String(response.auth_method));
}
};
// src/pipes/serializers/data-integration-credentials-response.serializer.ts
const deserializeDataIntegrationCredentialsResponse = (response) => {
switch (response.active) {
case true: return {
active: true,
credential: deserializeDataIntegrationVendedCredential(response.credential)
};
case false: return {
active: false,
error: response.error
};
default: throw new Error("Unknown active: " + String(response.active));
}
};
// src/pipes/serializers/data-integration-access-token-response-access-token.serializer.ts
const deserializeDataIntegrationAccessTokenResponseAccessToken = (response) => ({
object: response.object,
accessToken: response.access_token,
expiresAt: response.expires_at != null ? new Date(response.expires_at) : null,
scopes: response.scopes,
missingScopes: response.missing_scopes
});
// src/pipes/serializers/data-integration-access-token-response.serializer.ts
const deserializeDataIntegrationAccessTokenResponse = (response) => {
switch (response.active) {
case true: return {
active: true,
accessToken: deserializeDataIntegrationAccessTokenResponseAccessToken(response.access_token)
};
case false: return {
active: false,
error: response.error
};
default: throw new Error("Unknown active: " + String(response.active));
}
};
// src/pipes/serializers/data-integrations-list-response-data-connected-account.serializer.ts
const deserializeDataIntegrationsListResponseDataConnectedAccount = (response) => ({
object: response.object,
id: response.id,
connectionRole: response.connection_role,
accountIdentifier: response.account_identifier ?? null,
accountDisplayName: response.account_display_name ?? null,
userId: response.user_id ?? null,
organizationId: response.organization_id ?? null,
scopes: response.scopes,
authMethod: response.auth_method,
apiKeyLast4: response.api_key_last_4 ?? null,
clientId: response.client_id ?? null,
clientSecretLast4: response.client_secret_last_4 ?? null,
config: response.config,
state: response.state,
establishedByUserId: response.established_by_user_id ?? null,
stateReason: response.state_reason ?? null,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at),
warnings: response.warnings != null ? response.warnings.map(deserializeConnectedAccountWarning) : void 0,
userlandUserId: response.userland_user_id ?? null
});
// src/pipes/serializers/data-integrations-list-response-data.serializer.ts
const deserializeDataIntegrationsListResponseData = (response) => ({
object: response.object,
id: response.id,
name: response.name,
description: response.description ?? null,
slug: response.slug,
integrationType: response.integration_type,
credentialsType: response.credentials_type,
scopes: response.scopes ?? null,
authMethods: response.auth_methods,
connectionOwner: response.connection_owner,
ownership: response.ownership,
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at),
connectedAccount: response.connected_account != null ? deserializeDataIntegrationsListResponseDataConnectedAccount(response.connected_account) : null,
connectedAccounts: response.connected_accounts != null ? response.connected_accounts.map(deserializeDataIntegrationsListResponseDataConnectedAccount) : void 0
});
// src/pipes/serializers/data-integrations-list-response.serializer.ts
const deserializeDataIntegrationsListResponse = (response) => ({
object: response.object,
data: response.data.map(deserializeDataIntegrationsListResponseData)
});
// src/pipes/serializers/data-integration-credentials-input.serializer.ts
const serializeDataIntegrationCredentialsInput = (model) => ({
type: model.type,
client_id: model.clientId,
client_secret: model.clientSecret
});
// src/pipes/serializers/api-key-installation.serializer.ts
const serializeApiKeyInstallation = (model) => ({
secret: model.secret,
user_id: model.userId,
organization_id: model.organizationId
});
// src/pipes/serializers/custom-provider-definition.serializer.ts
const serializeCustomProviderDefinition = (model) => ({
name: model.name,
authorization_url: model.authorizationUrl,
token_url: model.tokenUrl,
refresh_token_url: model.refreshTokenUrl,
pkce_enabled: model.pkceEnabled,
request_scope_separator: model.requestScopeSeparator,
scopes_required: model.scopesRequired,
client_secret_required: model.clientSecretRequired,
additional_authorization_parameters: model.additionalAuthorizationParameters,
token_body_content_type: model.tokenBodyContentType,
authenticate_via: model.authenticateVia
});
// src/pipes/serializers/create-data-integration.serializer.ts
const serializeCreateDataIntegration = (model) => ({
provider: model.provider,
ownership: model.ownership,
description: model.description,
enabled: model.enabled,
scopes: model.scopes,
auth_methods: model.authMethods,
config: model.config,
credentials: model.credentials != null ? serializeDataIntegrationCredentialsInput(model.credentials) : void 0,
api_key: model.apiKey != null ? serializeApiKeyInstallation(model.apiKey) : void 0,
custom_provider: model.customProvider != null ? serializeCustomProviderDefinition(model.customProvider) : void 0
});
// src/pipes/serializers/data-integrations-finish-connection-request.serializer.ts
const serializeDataIntegrationsFinishConnectionRequest = (model) => ({
connect_code: model.connectCode,
code_verifier: model.codeVerifier,
state: model.state
});
// src/pipes/serializers/update-custom-provider-definition.serializer.ts
const serializeUpdateCustomProviderDefinition = (model) => ({
name: model.name,
authorization_url: model.authorizationUrl,
token_url: model.tokenUrl,
refresh_token_url: model.refreshTokenUrl,
pkce_enabled: model.pkceEnabled,
request_scope_separator: model.requestScopeSeparator,
scopes_required: model.scopesRequired,
client_secret_required: model.clientSecretRequired,
additional_authorization_parameters: model.additionalAuthorizationParameters,
token_body_content_type: model.tokenBodyContentType,
authenticate_via: model.authenticateVia
});
// src/pipes/serializers/update-data-integration.serializer.ts
const serializeUpdateDataIntegration = (model) => ({
description: model.description,
enabled: model.enabled,
scopes: model.scopes,
credentials: model.credentials != null ? serializeDataIntegrationCredentialsInput(model.credentials) : void 0,
api_key: model.apiKey != null ? serializeApiKeyInstallation(model.apiKey) : void 0,
custom_provider: model.customProvider != null ? serializeUpdateCustomProviderDefinition(model.customProvider) : void 0
});
// src/pipes/serializers/data-integrations-create-api-key-connection-request.serializer.ts
const serializeDataIntegrationsCreateApiKeyConnectionRequest = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
user_id: model.userId,
organization_id: model.organizationId,
connection_owner: model.connectionOwner,
secret: model.secret,
connection_intent: model.connectionIntent
});
// src/pipes/serializers/data-integrations-get-data-integration-authorize-url-request.serializer.ts
const serializeDataIntegrationsGetDataIntegrationAuthorizeUrlRequest = (model) => ({
account_display_name: model.accountDisplayName,
user_id: model.userId,
organization_id: model.organizationId,
connection_owner: model.connectionOwner,
return_to: model.returnTo,
code_challenge: model.codeChallenge,
code_challenge_method: model.codeChallengeMethod,
config: model.config,
connection_intent: model.connectionIntent,
connected_account_id: model.connectedAccountId
});
// src/pipes/serializers/data-integrations-create-client-credentials-connection-request.serializer.ts
const serializeDataIntegrationsCreateClientCredentialsConnectionRequest = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
user_id: model.userId,
organization_id: model.organizationId,
connection_owner: model.connectionOwner,
client_id: model.clientId,
client_secret: model.clientSecret,
config: model.config,
connection_intent: model.connectionIntent
});
// src/pipes/serializers/data-integrations-vend-credentials-request.serializer.ts
const serializeDataIntegrationsVendCredentialsRequest = (model) => ({
user_id: model.userId,
organization_id: model.organizationId,
connected_account_id: model.connectedAccountId,
connection_owner: model.connectionOwner,
supports_multiple_connections: model.supportsMultipleConnections
});
// src/pipes/serializers/data-integrations-get-user-token-request.serializer.ts
const serializeDataIntegrationsGetUserTokenRequest = (model) => ({
user_id: model.userId,
organization_id: model.organizationId,
connected_account_id: model.connectedAccountId,
connection_owner: model.connectionOwner,
supports_multiple_connections: model.supportsMultipleConnections
});
// src/pipes/serializers/create-organization-connected-account.serializer.ts
const serializeCreateOrganizationConnectedAccount = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
access_token: model.accessToken,
refresh_token: model.refreshToken,
expires_at: model.expiresAt != null ? model.expiresAt.toISOString() : void 0,
scopes: model.scopes,
state: model.state,
user_id: model.userId,
connection_intent: model.connectionIntent
});
// src/pipes/serializers/organization-connected-account.serializer.ts
const serializeOrganizationConnectedAccount = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
access_token: model.accessToken,
refresh_token: model.refreshToken,
expires_at: model.expiresAt != null ? model.expiresAt.toISOString() : void 0,
scopes: model.scopes,
state: model.state,
user_id: model.userId
});
// src/pipes/serializers/create-connected-account.serializer.ts
const serializeCreateConnectedAccount = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
access_token: model.accessToken,
refresh_token: model.refreshToken,
expires_at: model.expiresAt != null ? model.expiresAt.toISOString() : void 0,
scopes: model.scopes,
state: model.state,
connection_intent: model.connectionIntent
});
// src/pipes/serializers/connected-account-input.serializer.ts
const serializeConnectedAccountInput = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
access_token: model.accessToken,
refresh_token: model.refreshToken,
expires_at: model.expiresAt != null ? model.expiresAt.toISOString() : void 0,
scopes: model.scopes,
state: model.state
});
// src/pipes/serializers/data-integrations-upsert-api-key-request.serializer.ts
const serializeDataIntegrationsUpsertApiKeyRequest = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
user_id: model.userId,
organization_id: model.organizationId,
connected_account_id: model.connectedAccountId,
connection_intent: model.connectionIntent,
connection_owner: model.connectionOwner,
secret: model.secret
});
// src/pipes/serializers/data-integrations-upsert-client-credentials-request.serializer.ts
const serializeDataIntegrationsUpsertClientCredentialsRequest = (model) => ({
account_display_name: model.accountDisplayName,
account_identifier: model.accountIdentifier,
user_id: model.userId,
organization_id: model.organizationId,
connected_account_id: model.connectedAccountId,
connection_intent: model.connectionIntent,
connection_owner: model.connectionOwner,
client_id: model.clientId,
client_secret: model.clientSecret,
config: model.config
});
// src/pipes/pipes.ts
var Pipes = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Upsert an API key for a connected account
*
* Creates or updates an API-key-based installation for the specified integration, owned by the user or, when `connection_owner` is `organization`, shared by the organization. If an installation already exists, the stored API key is rotated to the new value.
* @param options - Object containing userId, secret.
* @param options.slug - The identifier of the integration.
* @example "github"
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter to scope the connection to a specific organization. Required when `connection_owner` is `organization`.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to rotate a specific existing connection.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionOwner - Whose connection to create or rotate. `user` (the default) addresses the connection owned by `user_id`. `organization` addresses the connection shared by every member of `organization_id`; `user_id` then identifies the member performing the request and must be an active member of the organization.
* @example "user"
* @param options.secret - The API key secret to store for this integration.
* @example "sk-1234567890abcdef"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateDataIntegrationApiKey(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.put(`/data-integrations/${encodeURIComponent(slug)}/api-key`, serializeDataIntegrationsUpsertApiKeyRequest(payload));
return deserializeConnectedAccount(data);
}
/**
* Upsert client credentials for a connected account
*
* Creates or updates a client-credentials-based installation for the specified integration, owned by the user or, when `connection_owner` is `organization`, shared by the organization. If an installation already exists, the stored client credentials are rotated to the new values.
* @param options - The request options.
* @param options.slug - The identifier of the integration.
* @example "salesforce"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateDataIntegrationClientCredentials(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.put(`/data-integrations/${encodeURIComponent(slug)}/client-credentials`, serializeDataIntegrationsUpsertClientCredentialsRequest(payload));
return deserializeConnectedAccount(data);
}
/**
* Delete an organization connected account
*
* Disconnects the organization's account for the provider, including removing any stored access and refresh tokens. A member will need to reauthorize if the organization wants to reconnect. This does not revoke access on the provider side.
* @param options - Additional query options.
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select the connection to delete.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async deleteOrganizationConnectedAccount(options) {
const { organizationId, slug } = options;
await this.workos.delete(`/organizations/${encodeURIComponent(organizationId)}/connected_accounts/${encodeURIComponent(slug)}`, {
supports_multiple_connections: options.supportsMultipleConnections,
connected_account_id: options.connectedAccountId
});
}
/**
* Delete a connected account
*
* Disconnects WorkOS's account for the user, including removing any stored access and refresh tokens. The user will need to reauthorize if they want to reconnect. Access is not revoked on the provider side, except for the WorkOS OAuth provider, whose underlying AuthKit grant is revoked.
* @param options - Additional query options.
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter if the connection is scoped to an organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select the connection to delete.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async deleteUserConnectedAccount(options) {
const { userId, slug } = options;
await this.workos.delete(`/user_management/users/${encodeURIComponent(userId)}/connected_accounts/${encodeURIComponent(slug)}`, {
organization_id: options.organizationId,
supports_multiple_connections: options.supportsMultipleConnections,
connected_account_id: options.connectedAccountId
});
}
/**
* List data integrations
*
* Lists the environment's data integrations configured with `custom` or `organization` credentials, including custom providers and API key integrations. Both user-owned and organization-owned roots are returned, each as its own row with an `ownership`; filter with `ownership` to return only one kind.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<DataIntegration, ListDataIntegrationsOptions>>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listDataIntegrations(options) {
const paginationOptions = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/data-integrations", deserializeDataIntegration, paginationOptions), (params) => fetchAndDeserialize(this.workos, "/data-integrations", deserializeDataIntegration, params), paginationOptions);
}
/**
* Create a data integration
*
* Creates a data integration for a provider. Set `credentials.type` to `custom` to use your own OAuth app credentials or `organization` to have each organization supply its own. Set `auth_methods` to `["api_key"]` to create an API key integration; you may optionally supply an `api_key` block to install a first tenant in the same call. Set `auth_methods` to `["client_credentials"]` to create a client-credentials integration; client credentials are installed per-tenant afterwards. Set `ownership` to `organization` to create the integration organizations connect to instead of the default user-owned one; a provider may have one of each. For a built-in provider, pass its slug as `provider`. For a custom provider, pass a new slug plus a `custom_provider` definition, or the slug of an existing custom provider (without `custom_provider`) to add the other ownership.
* @param options - Object containing provider.
* @param options.provider - The provider to create a Data Integration for. For a built-in provider use its slug (e.g. `github`, `slack`). For a custom provider, this is the new provider slug and `custom_provider` must be supplied. A custom provider slug cannot shadow an existing global provider slug.
* @example "github"
* @param options.ownership - Who owns the Data Integration. `user` (the default) creates the integration users connect their own accounts to; `organization` creates the root organizations connect to. Ownership is fixed at creation, and one integration of each ownership may exist per provider. Independent of `credentials.type`.
* @example "user"
* @param options.description - An optional description of the Data Integration.
* @example "Production GitHub app"
* @param options.enabled - Whether the Data Integration is enabled. Defaults to `false`.
* @example true
* @param options.scopes - The OAuth scopes to request for the Data Integration. Defaults to the provider's configured scopes when omitted.
* @example ["repo","read:org"]
* @param options.authMethods - How accounts authenticate with the provider. Defaults to `["oauth"]`. Use `["api_key"]` to declare an API key integration; `credentials` is then not required and keys are supplied per-tenant (optionally via `api_key` on this request). Use `["client_credentials"]` to declare a client-credentials integration; `credentials` is likewise not required and client credentials are supplied per-tenant.
* @example ["oauth"]
* @param options.config - Provider-specific config values (e.g. a Snowflake `account`), keyed by the config field. Only fields the built-in provider declares are accepted.
* @example {"account":"myorg-myaccount"}
* @param options.credentials - The OAuth credentials to configure for the Data Integration. Required for OAuth integrations; omit when `auth_methods` is `["api_key"]`.
* @param options.apiKey - An optional API key to install for the first tenant on an `api_key` integration. Omit to declare a keyless integration; tenants can be added later via the per-installation API key path.
* @param options.customProvider - The OAuth definition for a custom provider. Supply this to define a custom provider; omit it to create an integration for a built-in provider.
* @returns {Promise<DataIntegration>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createDataIntegration(options) {
const payload = options;
const { data } = await this.workos.post("/data-integrations", serializeCreateDataIntegration(payload));
return deserializeDataIntegration(data);
}
/**
* Finish connection
*
* Saves a connection that was started with `code_challenge`. After the user authorizes, WorkOS redirects them to `return_to` with a `connect_code` and `state`. Call this endpoint from your server with that `connect_code` and the `code_verifier` behind the challenge to save the connected account.
* @returns {Promise<DataIntegrationFinishConnectionResponse>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
*/
async finishConnection(options) {
const payload = options;
const { data } = await this.workos.post("/data-integrations/finish", serializeDataIntegrationsFinishConnectionRequest(payload));
return deserializeDataIntegrationFinishConnectionResponse(data);
}
/**
* Get a data integration
*
* Retrieves the user-owned data integration by its slug.
* @param options - The request options.
* @param options.slug - The slug identifier of the data integration.
* @example "github"
* @returns {Promise<DataIntegration>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async getDataIntegration(options) {
const { slug } = options;
const { data } = await this.workos.get(`/data-integrations/${encodeURIComponent(slug)}`);
return deserializeDataIntegration(data);
}
/**
* Update a data integration
*
* Updates the description, enabled state, or custom credentials of the user-owned data integration. For custom providers, `custom_provider` updates the OAuth definition.
* @param options - The request body.
* @param options.slug - The slug identifier of the data integration.
* @example "github"
* @param options.description - An optional description of the Data Integration.
* @example "Production GitHub app"
* @param options.enabled - Whether the Data Integration is enabled.
* @example true
* @param options.scopes - The OAuth scopes to request for the Data Integration. Pass `null` to reset to the provider's configured scopes.
* @example ["repo","read:org"]
* @param options.credentials - New OAuth credentials for the Data Integration. When provided, rotates the stored client secret. Mutually exclusive with `api_key`.
* @param options.apiKey - An API key to install or rotate for a tenant on an `api_key` integration. Upserts the tenant installation identified by `user_id` (and optional `organization_id`).
* @param options.customProvider - Updates to a custom provider's OAuth definition. Only valid for custom-provider integrations.
* @returns {Promise<DataIntegration>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateDataIntegration(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.put(`/data-integrations/${encodeURIComponent(slug)}`, serializeUpdateDataIntegration(payload));
return deserializeDataIntegration(data);
}
/**
* Delete a data integration
*
* Deletes the user-owned data integration and all of its connected installations. For a custom provider, the provider definition is deleted once no organization-owned root references it either.
* @param options - The request options.
* @param options.slug - The slug identifier of the data integration.
* @example "github"
* @returns {Promise<void>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async deleteDataIntegration(options) {
const { slug } = options;
await this.workos.delete(`/data-integrations/${encodeURIComponent(slug)}`);
}
/**
* Create another API key connected account
*
* Creates another API key-based connected account for the specified integration, owned by the user or, when `connection_owner` is `organization`, shared by the organization. Requires `connection_intent: add` and does not accept `connected_account_id`; use PUT to create or rotate the compatibility connection or to update an exact connection.
* @param options - Object containing userId, secret, connectionIntent.
* @param options.slug - The identifier of the integration.
* @example "github"
* @param options.accountDisplayName - A mutable, non-unique label. Omit to preserve an existing label; null clears it. Labels are never account identifiers.
* @example "Acme production"
* @param options.accountIdentifier - A developer-attested provider account identifier, never inferred from a label or credential. Omit to preserve an existing identifier; null clears it.
* @example "workspace_123"
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter to scope the connection to a specific organization. Required when `connection_owner` is `organization`.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionOwner - Whose connection to create or rotate. `user` (the default) addresses the connection owned by `user_id`. `organization` addresses the connection shared by every member of `organization_id`; `user_id` then identifies the member performing the request and must be an active member of the organization.
* @example "user"
* @param options.secret - The API key secret to store for this integration.
* @example "sk-1234567890abcdef"
* @param options.connectionIntent - Must be `add`: this endpoint only creates another connection. The first connection for an owner shape fills the compatibility slot; later connections are standard.
* @example "add"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async createDataIntegrationApiKey(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.post(`/data-integrations/${encodeURIComponent(slug)}/api-key`, serializeDataIntegrationsCreateApiKeyConnectionRequest(payload));
return deserializeConnectedAccount(data);
}
/**
* Get authorization URL
*
* Generates an OAuth authorization URL to initiate the connection flow for a user. Redirect the user to the returned URL to begin the OAuth flow with the third-party provider.
* @param options - Object containing userId.
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.accountDisplayName - A mutable, non-unique label. Omit to preserve an existing label; null clears it. Labels are never account identifiers.
* @example "Acme production"
* @param options.userId - The ID of the user to authorize. When `connection_owner` is `organization`, this is the user authorizing on behalf of the organization; they must be an active member of the organization and do not become the owner of the resulting connected account.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An organization ID to scope the authorization to a specific organization. Required when `connection_owner` is `organization`.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionOwner - Who will own the connected account. `user` (the default) connects the user's own account. `organization` connects the organization's shared account and requires `organization_id`.
* @example "user"
* @param options.returnTo - The URL to redirect the user to after authorization. Required with `code_challenge`, and must then exactly match a redirect URI registered on one of the environment's applications. Loopback URLs match on any port; wildcard redirect URIs are not honored, and a `return_to` with a query string or fragment never matches.
* @example "https://example.com/callback"
* @param options.codeChallenge - A PKCE-style code challenge: the base64url-encoded SHA-256 of a `code_verifier` your app keeps. When set, the connection isn't saved when the user finishes authorizing. Instead, the user is redirected to `return_to` with a `connect_code` and `state`, and your app must call [Finish connection](https://workos.com/docs/reference/pipes/connected-account/finish-connection) with the `connect_code` and `code_verifier` within 90 seconds to save it.
* @example "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
* @param options.codeChallengeMethod - The method used to derive `code_challenge`. Only `S256` is supported, and it is the default. Requires `code_challenge`.
* @example "S256"
* @param options.config - Connect-time config values for the provider-declared `installation`-scope fields (e.g. a Zendesk `subdomain`), keyed by the config field. Only fields the provider declares may be supplied, and required fields must be provided unless already pinned on the integration.
* @example {"subdomain":"acme"}
* @param options.connectionIntent - Which connection the request targets. Omit it to use the compatibility connection. Send `add` to create another connection: the first connection for an owner shape fills the compatibility slot, and later connections are standard. Send `reauthorize` with `connected_account_id` to reauthorize one exact connection.
* @example "add"
* @param options.connectedAccountId - The exact connected account to reauthorize. Required with `connection_intent: reauthorize` and not accepted otherwise.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<DataIntegrationAuthorizeUrlResponse>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async authorizeDataIntegration(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.post(`/data-integrations/${encodeURIComponent(slug)}/authorize`, serializeDataIntegrationsGetDataIntegrationAuthorizeUrlRequest(payload));
return deserializeDataIntegrationAuthorizeUrlResponse(data);
}
/**
* Create another client credentials connected account
*
* Creates another client credentials-based connected account for the specified integration, owned by the user or, when `connection_owner` is `organization`, shared by the organization. Requires `connection_intent: add` and does not accept `connected_account_id`; use PUT to create or rotate the compatibility connection or to update an exact connection.
* @param options - Object containing userId, clientId, clientSecret, connectionIntent.
* @param options.slug - The identifier of the integration.
* @example "salesforce"
* @param options.accountDisplayName - A mutable, non-unique label. Omit to preserve an existing label; null clears it. Labels are never account identifiers.
* @example "Acme production"
* @param options.accountIdentifier - A developer-attested provider account identifier, never inferred from a label or credential. Omit to preserve an existing identifier; null clears it.
* @example "workspace_123"
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter to scope the connection to a specific organization. Required when `connection_owner` is `organization`.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionOwner - Whose connection to create or rotate. `user` (the default) addresses the connection owned by `user_id`. `organization` addresses the connection shared by every member of `organization_id`; `user_id` then identifies the member performing the request and must be an active member of the organization.
* @example "user"
* @param options.clientId - The OAuth client ID to store for this integration.
* @example "3MVG9..."
* @param options.clientSecret - The OAuth client secret to store for this integration.
* @example "shhh-secret"
* @param options.config - Provider-specific configuration values collected for this installation, keyed by the provider's config field descriptors.
* @example {"salesforce_host":"acme.my.salesforce.com"}
* @param options.connectionIntent - Must be `add`: this endpoint only creates another connection. The first connection for an owner shape fills the compatibility slot; later connections are standard.
* @example "add"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async createDataIntegrationClientCredential(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.post(`/data-integrations/${encodeURIComponent(slug)}/client-credentials`, serializeDataIntegrationsCreateClientCredentialsConnectionRequest(payload));
return deserializeConnectedAccount(data);
}
/**
* Vend credentials for a connected account
*
* Returns credentials for a user's connected account. Branches on the installation's `auth_method`: OAuth installations return an access token (refreshed if needed); API-key installations return the stored secret. Every active credential includes `config`: provider-declared, non-secret values from the installation snapshot, with current provider defaults for unset fields. Editing integration or organization configuration does not change the snapshot; reconnect or explicitly rebind the connection to adopt those edits. Defaults remain live, so a changed default can appear in `config` before a cached token is refreshed or re-minted. Credentials that never refresh require a reconnect or rebind when a default changes their routing.
* @param options - Object containing userId.
* @param options.slug - The identifier of the integration.
* @example "github"
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier. When `connection_owner` is `organization`, this is the user the credentials are vended on behalf of; they must be an active member of the organization.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter to scope the connection to a specific organization. Required when `connection_owner` is `organization`.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select a specific connection when the user has several for this provider.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionOwner - Which connection to vend from. `user` (the default) vends the user's own connection and requires `user_id`. `organization` vends the organization's shared connection and requires `organization_id`.
* @example "user"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. If no `connected_account_id` is supplied and several connections match, the request returns `account_selection_required`. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @returns {Promise<DataIntegrationCredentialsResponse>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createDataIntegrationCredential(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.post(`/data-integrations/${encodeURIComponent(slug)}/credentials`, serializeDataIntegrationsVendCredentialsRequest(payload));
return deserializeDataIntegrationCredentialsResponse(data);
}
/**
* Get an organization-owned data integration
*
* Retrieves the organization-owned data integration for a provider by its slug. The `/organization` suffix selects the environment-level organization-owned root for the provider; it does not name a particular organization.
* @param options - The request options.
* @param options.slug - The slug identifier of the data integration.
* @example "github"
* @returns {Promise<DataIntegration>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async getOrganizationDataIntegration(options) {
const { slug } = options;
const { data } = await this.workos.get(`/data-integrations/${encodeURIComponent(slug)}/organization`);
return deserializeDataIntegration(data);
}
/**
* Update an organization-owned data integration
*
* Updates the description, enabled state, or custom credentials of the organization-owned data integration for a provider. For custom providers, `custom_provider` updates the OAuth definition, which is shared with the user-owned root. The `/organization` suffix selects the environment-level organization-owned root for the provider; it does not name a particular organization.
* @param options - The request body.
* @param options.slug - The slug identifier of the data integration.
* @example "github"
* @param options.description - An optional description of the Data Integration.
* @example "Production GitHub app"
* @param options.enabled - Whether the Data Integration is enabled.
* @example true
* @param options.scopes - The OAuth scopes to request for the Data Integration. Pass `null` to reset to the provider's configured scopes.
* @example ["repo","read:org"]
* @param options.credentials - New OAuth credentials for the Data Integration. When provided, rotates the stored client secret. Mutually exclusive with `api_key`.
* @param options.apiKey - An API key to install or rotate for a tenant on an `api_key` integration. Upserts the tenant installation identified by `user_id` (and optional `organization_id`).
* @param options.customProvider - Updates to a custom provider's OAuth definition. Only valid for custom-provider integrations.
* @returns {Promise<DataIntegration>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateOrganizationDataIntegration(options) {
const { slug, ...payload } = options;
const { data } = await this.workos.put(`/data-integrations/${encodeURIComponent(slug)}/organization`, serializeUpdateDataIntegration(payload));
return deserializeDataIntegration(data);
}
/**
* Delete an organization-owned data integration
*
* Deletes the organization-owned data integration for a provider and all of its connected installations. For a custom provider, the provider definition is deleted once no user-owned root references it either. The `/organization` suffix selects the environment-level organization-owned root for the provider; it does not name a particular organization.
* @param options - The request options.
* @param options.slug - The slug identifier of the data integration.
* @example "github"
* @returns {Promise<void>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async deleteOrganizationDataIntegration(options) {
const { slug } = options;
await this.workos.delete(`/data-integrations/${encodeURIComponent(slug)}/organization`);
}
/**
* Get an access token for a connected account
*
* Fetches a valid OAuth access token for a user's connected account. WorkOS automatically handles token refresh, ensuring you always receive a valid, non-expired token.
* @param options - Object containing userId.
* @param options.provider - The identifier of the integration.
* @example "github"
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier. When `connection_owner` is `organization`, this is the user the credentials are vended on behalf of; they must be an active member of the organization.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter to scope the connection to a specific organization. Required when `connection_owner` is `organization`.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select a specific connection when the user has several for this provider.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionOwner - Which connection to vend from. `user` (the default) vends the user's own connection and requires `user_id`. `organization` vends the organization's shared connection and requires `organization_id`.
* @example "user"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. If no `connected_account_id` is supplied and several connections match, the request returns `account_selection_required`. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @returns {Promise<DataIntegrationAccessTokenResponse>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async getAccessToken(options) {
const { provider, ...payload } = options;
const { data } = await this.workos.post(`/data-integrations/${encodeURIComponent(provider)}/token`, serializeDataIntegrationsGetUserTokenRequest(payload));
return deserializeDataIntegrationAccessTokenResponse(data);
}
/**
* Get an organization connected account
*
* Retrieves an organization's [connected account](https://workos.com/docs/reference/pipes/connected-account) for a specific provider.
* @param options - Additional query options.
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select a specific connection when the organization has several for this provider.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async getOrganizationConnectedAccount(options) {
const { organizationId, slug } = options;
const { data } = await this.workos.get(`/organizations/${encodeURIComponent(organizationId)}/connected_accounts/${encodeURIComponent(slug)}`, { query: {
...options.supportsMultipleConnections !== void 0 && { supports_multiple_connections: options.supportsMultipleConnections },
...options.connectedAccountId !== void 0 && { connected_account_id: options.connectedAccountId }
} });
return deserializeConnectedAccount(data);
}
/**
* Import an organization connected account
*
* Imports an organization-owned [connected account](https://workos.com/docs/reference/pipes/connected-account) by providing OAuth tokens directly. Omit `connection_intent` to create only the compatibility connection, or set it to `add` to explicitly create another connection. This creation-only endpoint does not accept `connected_account_id` or reauthorization intent.
* @param options - Object containing userId.
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.accountDisplayName - A mutable, non-unique connection label; null clears it. Not an account identifier.
* @example "Acme production"
* @param options.accountIdentifier - A developer-attested account identifier; null clears it.
* @example "workspace_123"
* @param options.accessToken - The OAuth access token for the connected account.
* @example "gho_16C7e42F292c6912E7710c838347Ae178B4a"
* @param options.refreshToken - The OAuth refresh token for the connected account.
* @example "ghr_xxxxxxxxxxxxxxxxxxxx"
* @param options.expiresAt - The ISO-8601 timestamp when the access token expires. Required when `access_token` is provided for tokens that expire.
* @example "2025-12-31T23:59:59.000Z"
* @param options.scopes - The OAuth scopes granted for this connection.
* @example ["repo","user:email"]
* @param options.state - Explicitly set the state of the connected account. When omitted, the state is derived from the token combination provided.
* @example "connected"
* @param options.userId - The [User](https://workos.com/docs/reference/authkit/user) identifier of the organization member on whose behalf the connected account is being imported or updated. The user must be an active member of the organization.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionIntent - Set to `add` to create another connected account. Omit this field for permanent compatibility behavior.
* @example "add"
* @returns {Promise<ConnectedAccount>}
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createOrganizationConnectedAccount(options) {
const { organizationId, slug, ...payload } = options;
const { data } = await this.workos.post(`/organizations/${encodeURIComponent(organizationId)}/connected_accounts/${encodeURIComponent(slug)}`, serializeCreateOrganizationConnectedAccount(payload));
return deserializeConnectedAccount(data);
}
/**
* Update an organization connected account
*
* Updates an organization's [connected account](https://workos.com/docs/reference/pipes/connected-account) tokens, scopes, or state for a specific provider.
* @param options - Object containing userId.
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.supportsMultipleConnections - Accepted for compatibility; does not change update targeting. Omit intent and selector to update the compatibility connection, or supply `connected_account_id` to update an exact connection.
* @example true
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select the connection to update.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionIntent - Set to `reauthorize` with `connected_account_id` to update one exact connection. The intent may be omitted when supplying an ID. Omit both for permanent compatibility behavior.
* @example "reauthorize"
* @param options.accountDisplayName - A mutable, non-unique connection label; null clears it. Not an account identifier.
* @example "Acme production"
* @param options.accountIdentifier - A developer-attested account identifier; null clears it.
* @example "workspace_123"
* @param options.accessToken - The OAuth access token for the connected account.
* @example "gho_16C7e42F292c6912E7710c838347Ae178B4a"
* @param options.refreshToken - The OAuth refresh token for the connected account.
* @example "ghr_xxxxxxxxxxxxxxxxxxxx"
* @param options.expiresAt - The ISO-8601 timestamp when the access token expires. Required when `access_token` is provided for tokens that expire.
* @example "2025-12-31T23:59:59.000Z"
* @param options.scopes - The OAuth scopes granted for this connection.
* @example ["repo","user:email"]
* @param options.state - Explicitly set the state of the connected account. When omitted, the state is derived from the token combination provided.
* @example "connected"
* @param options.userId - The [User](https://workos.com/docs/reference/authkit/user) identifier of the organization member on whose behalf the connected account is being imported or updated. The user must be an active member of the organization.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateOrganizationConnectedAccount(options) {
const { organizationId, slug, supportsMultipleConnections, connectedAccountId, connectionIntent, ...payload } = options;
const { data } = await this.workos.put(`/organizations/${encodeURIComponent(organizationId)}/connected_accounts/${encodeURIComponent(slug)}`, serializeOrganizationConnectedAccount(payload), { query: {
...options.supportsMultipleConnections !== void 0 && { supports_multiple_connections: options.supportsMultipleConnections },
...options.connectedAccountId !== void 0 && { connected_account_id: options.connectedAccountId },
...options.connectionIntent !== void 0 && { connection_intent: options.connectionIntent }
} });
return deserializeConnectedAccount(data);
}
/**
* List providers for an organization
*
* Retrieves the organization-owned providers configured for your environment and the organization's [connected account](https://workos.com/docs/reference/pipes/connected-account) information for each. Providers owned by individual users are not included.
* @param options - Additional query options.
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier to list providers and connected accounts for.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @returns {Promise<DataIntegrationsListResponse>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async listOrganizationDataProviders(options) {
const { organizationId } = options;
const { data } = await this.workos.get(`/organizations/${encodeURIComponent(organizationId)}/data_providers`, { query: { ...options.supportsMultipleConnections !== void 0 && { supports_multiple_connections: options.supportsMultipleConnections } } });
return deserializeDataIntegrationsListResponse(data);
}
/**
* Get a connected account
*
* Retrieves a user's [connected account](https://workos.com/docs/reference/pipes/connected-account) for a specific provider.
* @param options - Additional query options.
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter if the connection is scoped to an organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select a specific connection when the user has several for this provider.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async getUserConnectedAccount(options) {
const { userId, slug } = options;
const { data } = await this.workos.get(`/user_management/users/${encodeURIComponent(userId)}/connected_accounts/${encodeURIComponent(slug)}`, { query: {
...options.organizationId !== void 0 && { organization_id: options.organizationId },
...options.supportsMultipleConnections !== void 0 && { supports_multiple_connections: options.supportsMultipleConnections },
...options.connectedAccountId !== void 0 && { connected_account_id: options.connectedAccountId }
} });
return deserializeConnectedAccount(data);
}
/**
* Import a connected account
*
* Imports a [connected account](https://workos.com/docs/reference/pipes/connected-account) for a user by providing OAuth tokens directly. Use this to migrate existing connections or set up connections without going through the OAuth flow.
* @param options - The request body.
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter if the connection is scoped to an organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.accountDisplayName - A mutable, non-unique connection label; null clears it. Not an account identifier.
* @example "Acme production"
* @param options.accountIdentifier - A developer-attested account identifier; null clears it.
* @example "workspace_123"
* @param options.accessToken - The OAuth access token for the connected account.
* @example "gho_16C7e42F292c6912E7710c838347Ae178B4a"
* @param options.refreshToken - The OAuth refresh token for the connected account.
* @example "ghr_xxxxxxxxxxxxxxxxxxxx"
* @param options.expiresAt - The ISO-8601 timestamp when the access token expires. Required when `access_token` is provided for tokens that expire.
* @example "2025-12-31T23:59:59.000Z"
* @param options.scopes - The OAuth scopes granted for this connection.
* @example ["repo","user:email"]
* @param options.state - Explicitly set the state of the connected account. When omitted, the state is derived from the token combination provided.
* @example "connected"
* @param options.connectionIntent - Set to `add` to create another connected account. Omit this field for permanent compatibility behavior.
* @example "add"
* @returns {Promise<ConnectedAccount>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createUserConnectedAccount(options) {
const { userId, slug, organizationId, ...payload } = options;
const { data } = await this.workos.post(`/user_management/users/${encodeURIComponent(userId)}/connected_accounts/${encodeURIComponent(slug)}`, serializeCreateConnectedAccount(payload), { query: { ...options.organizationId !== void 0 && { organization_id: options.organizationId } } });
return deserializeConnectedAccount(data);
}
/**
* Update a connected account
*
* Updates a user's [connected account](https://workos.com/docs/reference/pipes/connected-account) tokens, scopes, or state for a specific provider.
* @param options - The request body.
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.slug - The slug identifier of the provider (e.g., `github`, `slack`, `notion`).
* @example "github"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter if the connection is scoped to an organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.supportsMultipleConnections - Accepted for compatibility; does not change update targeting. Omit intent and selector to update the compatibility connection, or supply `connected_account_id` to update an exact connection.
* @example true
* @param options.connectedAccountId - A [connected account](https://workos.com/docs/reference/pipes/connected-account) identifier. Use this to select the connection to update.
* @example "data_installation_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.connectionIntent - Set to `reauthorize` with `connected_account_id` to update one exact connection. The intent may be omitted when supplying an ID. Omit both for permanent compatibility behavior.
* @example "reauthorize"
* @param options.accountDisplayName - A mutable, non-unique connection label; null clears it. Not an account identifier.
* @example "Acme production"
* @param options.accountIdentifier - A developer-attested account identifier; null clears it.
* @example "workspace_123"
* @param options.accessToken - The OAuth access token for the connected account.
* @example "gho_16C7e42F292c6912E7710c838347Ae178B4a"
* @param options.refreshToken - The OAuth refresh token for the connected account.
* @example "ghr_xxxxxxxxxxxxxxxxxxxx"
* @param options.expiresAt - The ISO-8601 timestamp when the access token expires. Required when `access_token` is provided for tokens that expire.
* @example "2025-12-31T23:59:59.000Z"
* @param options.scopes - The OAuth scopes granted for this connection.
* @example ["repo","user:email"]
* @param options.state - Explicitly set the state of the connected account. When omitted, the state is derived from the token combination provided.
* @example "connected"
* @returns {Promise<ConnectedAccount>}
* @throws {BadRequestException} 400
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateUserConnectedAccount(options) {
const { userId, slug, organizationId, supportsMultipleConnections, connectedAccountId, connectionIntent, ...payload } = options;
const { data } = await this.workos.put(`/user_management/users/${encodeURIComponent(userId)}/connected_accounts/${encodeURIComponent(slug)}`, serializeConnectedAccountInput(payload), { query: {
...options.organizationId !== void 0 && { organization_id: options.organizationId },
...options.supportsMultipleConnections !== void 0 && { supports_multiple_connections: options.supportsMultipleConnections },
...options.connectedAccountId !== void 0 && { connected_account_id: options.connectedAccountId },
...options.connectionIntent !== void 0 && { connection_intent: options.connectionIntent }
} });
return deserializeConnectedAccount(data);
}
/**
* List providers for a user
*
* Retrieves a list of available providers and the user's connection status for each. Returns all providers configured for your environment, along with the user's [connected account](https://workos.com/docs/reference/pipes/connected-account) information where applicable.
* @param options - Additional query options.
* @param options.userId - A [User](https://workos.com/docs/reference/authkit/user) identifier to list providers and connected accounts for.
* @example "user_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.organizationId - An [Organization](https://workos.com/docs/reference/organization) identifier. Optional parameter to filter connections for a specific organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.supportsMultipleConnections - Set to `true` to use the plural connection contract. When omitted or `false`, only the compatibility connection is considered.
* @example true
* @returns {Promise<DataIntegrationsListResponse>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async listUserDataProviders(options) {
const { userId } = options;
const { data } = await this.workos.get(`/user_management/users/${encodeURIComponent(userId)}/data_providers`, { query: {
...options.organizationId !== void 0 && { organization_id: options.organizationId },
...options.supportsMultipleConnections !== void 0 && { supports_multiple_connections: options.supportsMultipleConnections }
} });
return deserializeDataIntegrationsListResponse(data);
}
};
// src/radar/serializers/radar-standalone-response.serializer.ts
const deserializeRadarStandaloneResponse = (response) => ({
verdict: response.verdict,
reason: response.reason,
attemptId: response.attempt_id,
control: response.control,
blocklistType: response.blocklist_type
});
// src/radar/serializers/radar-list-entry-already-present-response.serializer.ts
const deserializeRadarListEntryAlreadyPresentResponse = (response) => ({ message: response.message });
// src/radar/serializers/radar-standalone-assess-request.serializer.ts
const serializeRadarStandaloneAssessRequest = (model) => ({
ip_address: model.ipAddress,
user_agent: model.userAgent,
email: model.email,
auth_method: model.authMethod,
action: model.action
});
// src/radar/serializers/radar-standalone-update-radar-attempt-request.serializer.ts
const serializeRadarStandaloneUpdateRadarAttemptRequest = (model) => ({
challenge_status: model.challengeStatus,
attempt_status: model.attemptStatus
});
// src/radar/serializers/radar-standalone-update-radar-list-request.serializer.ts
const serializeRadarStandaloneUpdateRadarListRequest = (model) => ({ entry: model.entry });
// src/radar/serializers/radar-standalone-delete-radar-list-entry-request.serializer.ts
const serializeRadarStandaloneDeleteRadarListEntryRequest = (model) => ({ entry: model.entry });
// src/radar/radar.ts
var Radar = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Create an attempt
*
* Assess a request for risk using the Radar engine and receive a verdict.
* @param options - Object containing ipAddress, userAgent, email, authMethod, action.
* @param options.ipAddress - The IP address of the request to assess.
* @example "49.78.240.97"
* @param options.userAgent - The user agent string of the request to assess.
* @example "Mozilla/5.0"
* @param options.email - The email address of the user making the request.
* @example "user@example.com"
* @param options.authMethod - The authentication method being used.
* @example "Password"
* @param options.action - The action being performed.
* @example "sign-in"
* @returns {Promise<RadarStandaloneResponse>}
* @throws {BadRequestException} 400
*/
async createAttempt(options) {
const payload = options;
const { data } = await this.workos.post("/radar/attempts", serializeRadarStandaloneAssessRequest(payload));
return deserializeRadarStandaloneResponse(data);
}
/**
* Update a Radar attempt
*
* You may optionally inform Radar that an authentication attempt or challenge was successful using this endpoint. Some Radar controls depend on tracking recent successful attempts, such as impossible travel.
* @param options - The request body.
* @param options.id - The unique identifier of the Radar attempt to update.
* @example "radar_att_01HZBC6N1EB1ZY7KG32X"
* @param options.challengeStatus - Set to `"success"` to mark the challenge as completed.
* @example "success"
* @param options.attemptStatus - Set to `"success"` to mark the authentication attempt as successful.
* @example "success"
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async updateAttempt(options) {
const { id, ...payload } = options;
await this.workos.put(`/radar/attempts/${encodeURIComponent(id)}`, serializeRadarStandaloneUpdateRadarAttemptRequest(payload));
}
/**
* Add an entry to a Radar list
*
* Add an entry to a Radar list.
* @param options - Object containing entry.
* @param options.type - The type of the Radar list (e.g. ip_address, domain, email).
* @example "ip_address"
* @param options.action - The list action indicating whether to add the entry to the allow or block list.
* @example "block"
* @param options.entry - The value to add to the list. Must match the format of the list type (e.g. a valid IP address for `ip_address`, a valid email for `email`).
* @example "198.51.100.42"
* @returns {Promise<RadarListEntryAlreadyPresentResponse | null>}
* @throws {BadRequestException} 400
*/
async addListEntry(options) {
const { type, action, ...payload } = options;
const { data } = await this.workos.post(`/radar/lists/${encodeURIComponent(type)}/${encodeURIComponent(action)}`, serializeRadarStandaloneUpdateRadarListRequest(payload));
if (!data) return null;
return deserializeRadarListEntryAlreadyPresentResponse(data);
}
/**
* Remove an entry from a Radar list
*
* Remove an entry from a Radar list.
* @param options - Object containing entry.
* @param options.type - The type of the Radar list (e.g. ip_address, domain, email).
* @example "ip_address"
* @param options.action - The list action indicating whether to remove the entry from the allow or block list.
* @example "block"
* @param options.entry - The value to remove from the list. Must match an existing entry.
* @example "198.51.100.42"
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async removeListEntry(options) {
const { type, action, ...payload } = options;
await this.workos.deleteWithBody(`/radar/lists/${encodeURIComponent(type)}/${encodeURIComponent(action)}`, serializeRadarStandaloneDeleteRadarListEntryRequest(payload));
}
};
// src/admin-portal/admin-portal.ts
var AdminPortal = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Generate a Portal Link
*
* Generate a Portal Link scoped to an Organization.
* @param payload - Object containing organization. Pass `externalUserId`
* for every admin you may later need to deprovision; only links generated
* with one can be revoked via `revokeLink`.
* @returns {Promise<{ link: string; }>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async generateLink({ intent, organization, returnUrl, successUrl, intentOptions, itContactEmails, externalUserId }) {
const { data } = await this.workos.post("/portal/generate_link", {
intent,
organization,
return_url: returnUrl,
success_url: successUrl,
intent_options: intentOptions ? { sso: {
bookmark_slug: intentOptions.sso.bookmarkSlug,
provider_type: intentOptions.sso.providerType
} } : void 0,
it_contact_emails: itContactEmails,
external_user_id: externalUserId
});
return data;
}
/**
* Revoke Portal Links
*
* Revokes every Portal Link generated for the given organization with the
* given `externalUserId`, and immediately ends any Admin Portal sessions that
* were started from those links. Use this when an admin is deprovisioned from
* your application: unopened links stop working, and their already-open
* portal sessions are ended. Only links that were generated with an
* `externalUserId` can be revoked, so pass one to `generateLink` for every
* admin you may later need to deprovision.
* @param payload - Object containing organization and externalUserId.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async revokeLink({ organization, externalUserId }) {
await this.workos.post("/portal/revoke_link", {
organization,
external_user_id: externalUserId
});
}
};
// src/common/utils/query-string.ts
/**
* Converts options to a query string.
* - Arrays: scope=read&scope=write (repeat format)
* - Objects: params[key]=value (bracket notation)
* - Encoding: RFC1738 (space as +)
* - Keys sorted alphabetically
*/
function toQueryString(options) {
const params = [];
const sortedKeys = Object.keys(options).sort((a, b) => a.localeCompare(b));
for (const key of sortedKeys) {
const value = options[key];
if (value === void 0) continue;
if (Array.isArray(value)) for (const item of value) params.push([key, String(item)]);
else if (typeof value === "object" && value !== null) {
const sortedSubKeys = Object.keys(value).sort((a, b) => a.localeCompare(b));
for (const subKey of sortedSubKeys) {
const subValue = value[subKey];
if (subValue !== void 0) params.push([`${key}[${subKey}]`, String(subValue)]);
}
} else params.push([key, String(value)]);
}
return params.map(([key, value]) => {
return `${encodeRFC1738(key)}=${encodeRFC1738(value)}`;
}).join("&");
}
function encodeRFC1738(str) {
return encodeURIComponent(str).replace(/%20/g, "+").replace(/[!'*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
}
// src/sso/sso.ts
var SSO = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* List Connections
*
* Get a list of all of your existing connections matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Connection, SerializedListConnectionsOptions>>}
* @throws 403 response from the API.
* @throws {UnprocessableEntityException} 422
*/
async listConnections(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/connections", deserializeConnection, options ? serializeListConnectionsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/connections", deserializeConnection, params), options ? serializeListConnectionsOptions(options) : void 0);
}
/**
* Delete a Connection
*
* Permanently deletes an existing connection. It cannot be undone.
* @param id - Unique identifier for the Connection.
*
* @example
* "conn_01E4ZCR3C56J083X43JQXF3JK5"
*
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async deleteConnection(id) {
await this.workos.delete(`/connections/${encodePathParameter(id)}`);
}
getAuthorizationUrl(options) {
const { codeChallenge, codeChallengeMethod, connection, clientId, domainHint, loginHint, organization, provider, providerQueryParams, providerScopes, redirectUri, state } = options;
if (!provider && !connection && !organization) throw new TypeError(`Incomplete arguments. Need to specify either a 'connection', 'organization', or 'provider'.`);
const query = toQueryString({
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
connection,
organization,
domain_hint: domainHint,
login_hint: loginHint,
provider,
provider_query_params: providerQueryParams,
provider_scopes: providerScopes,
client_id: clientId,
redirect_uri: redirectUri,
response_type: "code",
state
});
return `${this.workos.baseURL}/sso/authorize?${query}`;
}
/**
* Generates an authorization URL with PKCE parameters automatically generated.
* Use this for public clients (CLI apps, Electron, mobile) that cannot
* securely store a client secret.
*
* @returns Object containing url, state, and codeVerifier
*
* @example
* ```typescript
* const { url, state, codeVerifier } = await workos.sso.getAuthorizationUrlWithPKCE({
* connection: 'conn_123',
* clientId: 'client_123',
* redirectUri: 'myapp://callback',
* });
*
* // Store state and codeVerifier securely, then redirect user to url
* // After callback, exchange the code:
* const { profile, accessToken } = await workos.sso.getProfileAndToken({
* code: authorizationCode,
* codeVerifier,
* clientId: 'client_123',
* });
* ```
*/
async getAuthorizationUrlWithPKCE(options) {
const { connection, clientId, domainHint, loginHint, organization, provider, providerQueryParams, providerScopes, redirectUri } = options;
if (!provider && !connection && !organization) throw new TypeError(`Incomplete arguments. Need to specify either a 'connection', 'organization', or 'provider'.`);
const pkce = await this.workos.pkce.generate();
const state = this.workos.pkce.generateCodeVerifier(43);
const query = toQueryString({
code_challenge: pkce.codeChallenge,
code_challenge_method: "S256",
connection,
organization,
domain_hint: domainHint,
login_hint: loginHint,
provider,
provider_query_params: providerQueryParams,
provider_scopes: providerScopes,
client_id: clientId,
redirect_uri: redirectUri,
response_type: "code",
state
});
return {
url: `${this.workos.baseURL}/sso/authorize?${query}`,
state,
codeVerifier: pkce.codeVerifier
};
}
/**
* Get a Connection
*
* Get the details of an existing connection.
* @param id - Unique identifier for the Connection.
*
* @example
* "conn_01E4ZCR3C56J083X43JQXF3JK5"
*
* @returns {Promise<Connection>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async getConnection(id) {
const { data } = await this.workos.get(`/connections/${encodePathParameter(id)}`);
return deserializeConnection(data);
}
/**
* Exchange an authorization code for a profile and access token.
*
* Auto-detects public vs confidential client mode:
* - If codeVerifier is provided: Uses PKCE flow (public client)
* - If no codeVerifier: Uses client_secret from API key (confidential client)
* - If both: Uses both client_secret AND codeVerifier (confidential client with PKCE)
*
* Using PKCE with confidential clients is recommended by OAuth 2.1 for defense
* in depth and provides additional CSRF protection on the authorization flow.
*
* @throws Error if neither codeVerifier nor API key is available
*/
async getProfileAndToken({ code, clientId, codeVerifier }) {
if (codeVerifier !== void 0 && codeVerifier.trim() === "") throw new TypeError("codeVerifier cannot be an empty string. Generate a valid PKCE pair using workos.pkce.generate().");
const hasApiKey = !!this.workos.key;
const hasPKCE = !!codeVerifier;
if (!hasPKCE && !hasApiKey) throw new TypeError("getProfileAndToken requires either a codeVerifier (for public clients) or an API key configured on the WorkOS instance (for confidential clients).");
const form = new URLSearchParams({
client_id: clientId,
grant_type: "authorization_code",
code
});
if (hasPKCE) form.set("code_verifier", codeVerifier);
if (hasApiKey) form.set("client_secret", this.workos.key);
const { data } = await this.workos.post("/sso/token", form, { skipApiKeyCheck: !hasApiKey });
return deserializeProfileAndToken(data);
}
/**
* Get a User Profile
*
* Exchange an access token for a user's [Profile](https://workos.com/docs/reference/sso/profile). Because this profile is returned in the [Get a Profile and Token endpoint](https://workos.com/docs/reference/sso/profile/get-profile-and-token) your application usually does not need to call this endpoint. It is available for any authentication flows that require an additional endpoint to retrieve a user's profile.
* @returns {Promise<Profile<CustomAttributesType>>}
* @throws {UnauthorizedException} 401
* @throws {NotFoundException} 404
*/
async getProfile({ accessToken }) {
const { data } = await this.workos.get("/sso/profile", { accessToken });
return deserializeProfile(data);
}
/**
* Logout Authorize
*
* Generate a logout token and URL for RP-initiated Single Logout. Redirect the user to `logoutUrl` to sign them out of the identity provider.
* @param options - The profile to log out.
* @returns {Promise<AuthorizeLogout>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async authorizeLogout(options) {
const { data } = await this.workos.post("/sso/logout/authorize", serializeAuthorizeLogoutOptions(options));
return deserializeAuthorizeLogout(data);
}
};
// src/multi-factor-auth/serializers/challenge.serializer.ts
const deserializeChallenge = (challenge) => ({
object: challenge.object,
id: challenge.id,
createdAt: new Date(challenge.created_at),
updatedAt: new Date(challenge.updated_at),
expiresAt: challenge.expires_at != null ? new Date(challenge.expires_at) : void 0,
code: challenge.code,
authenticationFactorId: challenge.authentication_factor_id
});
// src/multi-factor-auth/serializers/factor.serializer.ts
const deserializeFactor = (factor) => ({
object: factor.object,
id: factor.id,
createdAt: new Date(factor.created_at),
updatedAt: new Date(factor.updated_at),
type: factor.type,
...factor.sms ? { sms: deserializeSms(factor.sms) } : {},
...factor.totp ? { totp: deserializeTotp(factor.totp) } : {}
});
const deserializeFactorWithSecrets = (factor) => ({
object: factor.object,
id: factor.id,
createdAt: new Date(factor.created_at),
updatedAt: new Date(factor.updated_at),
type: factor.type,
...factor.sms ? { sms: deserializeSms(factor.sms) } : {},
...factor.totp ? { totp: deserializeTotpWithSecrets(factor.totp) } : {}
});
// src/multi-factor-auth/serializers/verify-response.serializer.ts
const deserializeVerifyResponse = (verifyResponse) => ({
challenge: deserializeChallenge(verifyResponse.challenge),
valid: verifyResponse.valid
});
// src/multi-factor-auth/multi-factor-auth.ts
var MultiFactorAuth = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Delete Factor
*
* Permanently deletes an Authentication Factor. It cannot be undone.
* @param id - The unique ID of the Factor.
*
* @example
* "auth_factor_01FVYZ5QM8N98T9ME5BCB2BBMJ"
*
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteFactor(id) {
await this.workos.delete(`/auth/factors/${encodePathParameter(id)}`);
}
/**
* Get Factor
*
* Gets an Authentication Factor.
* @param id - The unique ID of the Factor.
*
* @example
* "auth_factor_01FVYZ5QM8N98T9ME5BCB2BBMJ"
*
* @returns {Promise<Factor>}
* @throws {NotFoundException} 404
*/
async getFactor(id) {
const { data } = await this.workos.get(`/auth/factors/${encodePathParameter(id)}`);
return deserializeFactor(data);
}
/**
* Enroll Factor
*
* Enrolls an Authentication Factor to be used as an additional factor of authentication. The returned ID should be used to create an authentication Challenge.
* @param options - Object containing type.
* @returns {Promise<FactorWithSecrets>}
* @throws {UnprocessableEntityException} 422
*/
async enrollFactor(options) {
const { data } = await this.workos.post("/auth/factors/enroll", {
type: options.type,
...(() => {
switch (options.type) {
case "sms": return { phone_number: options.phoneNumber };
case "totp": return {
totp_issuer: options.issuer,
totp_user: options.user
};
default: return {};
}
})()
});
return deserializeFactorWithSecrets(data);
}
/**
* Challenge Factor
*
* Creates a Challenge for an Authentication Factor.
* @param options - The request body.
* @returns {Promise<Challenge>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async challengeFactor(options) {
const { data } = await this.workos.post(`/auth/factors/${encodePathParameter(options.authenticationFactorId)}/challenge`, { sms_template: "smsTemplate" in options ? options.smsTemplate : void 0 });
return deserializeChallenge(data);
}
/**
* Verify Challenge
*
* Verifies an Authentication Challenge.
* @param options - Object containing code.
* @returns {Promise<VerifyResponse>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async verifyChallenge(options) {
const { data } = await this.workos.post(`/auth/challenges/${encodePathParameter(options.authenticationChallengeId)}/verify`, { code: options.code });
return deserializeVerifyResponse(data);
}
/**
* Enroll an authentication factor
*
* Enrolls a user in a new [authentication factor](https://workos.com/docs/reference/authkit/mfa/authentication-factor).
* @param payload - Object containing type.
* @returns {Promise<{authenticationFactor: UMFactorWithSecrets; authenticationChallenge: Challenge}>}
* @throws {UnprocessableEntityException} 422
*/
async createUserAuthFactor(payload) {
const { data } = await this.workos.post(`/user_management/users/${encodePathParameter(payload.userId)}/auth_factors`, serializeEnrollAuthFactorOptions(payload));
return {
authenticationFactor: deserializeFactorWithSecrets$1(data.authentication_factor),
authenticationChallenge: deserializeChallenge(data.authentication_challenge)
};
}
/**
* List authentication factors
*
* Lists the [authentication factors](https://workos.com/docs/reference/authkit/mfa/authentication-factor) for a user.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<UMFactor, PaginationOptions>>}
* @throws {UnprocessableEntityException} 422
*/
async listUserAuthFactors(options) {
const { userId, ...restOfOptions } = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/auth_factors`, deserializeFactor$1, restOfOptions), (params) => fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/auth_factors`, deserializeFactor$1, params), restOfOptions);
}
};
// src/audit-logs/serializers/audit-log-export.serializer.ts
const deserializeAuditLogExport = (auditLogExport) => ({
object: auditLogExport.object,
id: auditLogExport.id,
state: auditLogExport.state,
url: auditLogExport.url,
createdAt: new Date(auditLogExport.created_at),
updatedAt: new Date(auditLogExport.updated_at)
});
// src/audit-logs/serializers/audit-log-export-options.serializer.ts
const serializeAuditLogExportOptions = (options) => ({
actions: options.actions,
actor_names: options.actorNames,
actor_ids: options.actorIds,
organization_id: options.organizationId,
range_end: options.rangeEnd.toISOString(),
range_start: options.rangeStart.toISOString(),
targets: options.targets
});
// src/audit-logs/serializers/create-audit-log-event-options.serializer.ts
const serializeCreateAuditLogEventOptions = (event) => ({
action: event.action,
version: event.version,
occurred_at: event.occurredAt.toISOString(),
actor: event.actor,
targets: event.targets,
context: {
location: event.context.location,
user_agent: event.context.userAgent
},
metadata: event.metadata
});
// src/audit-logs/serializers/create-audit-log-schema-options.serializer.ts
function serializeMetadata(metadata) {
if (!metadata) return {};
const serializedMetadata = {};
Object.keys(metadata).forEach((key) => {
serializedMetadata[key] = { type: metadata[key] };
});
return serializedMetadata;
}
const serializeCreateAuditLogSchemaOptions = (schema) => ({
actor: { metadata: {
type: "object",
properties: serializeMetadata(schema.actor?.metadata)
} },
targets: schema.targets.map((target) => {
return {
type: target.type,
metadata: target.metadata ? {
type: "object",
properties: serializeMetadata(target.metadata)
} : void 0
};
}),
metadata: schema.metadata ? {
type: "object",
properties: serializeMetadata(schema.metadata)
} : void 0
});
// src/audit-logs/serializers/create-audit-log-schema.serializer.ts
function deserializeMetadata(metadata) {
if (!metadata || !metadata.properties) return {};
const deserializedMetadata = {};
Object.keys(metadata.properties).forEach((key) => {
if (metadata.properties) deserializedMetadata[key] = metadata.properties[key].type;
});
return deserializedMetadata;
}
const deserializeAuditLogSchema = (auditLogSchema) => ({
object: auditLogSchema.object,
version: auditLogSchema.version,
targets: auditLogSchema.targets.map((target) => ({
type: target.type,
metadata: target.metadata ? deserializeMetadata(target.metadata) : void 0
})),
actor: auditLogSchema.actor ? { metadata: deserializeMetadata(auditLogSchema.actor.metadata) } : void 0,
metadata: auditLogSchema.metadata ? deserializeMetadata(auditLogSchema.metadata) : void 0,
createdAt: new Date(auditLogSchema.created_at)
});
// src/audit-logs/serializers/audit-logs-retention.serializer.ts
const deserializeAuditLogsRetention = (response) => ({ retentionPeriodInDays: response.retention_period_in_days ?? null });
// src/audit-logs/serializers/update-audit-logs-retention.serializer.ts
const serializeUpdateAuditLogsRetention = (model) => ({ retention_period: model.retentionPeriod });
// src/audit-logs/audit-logs.ts
var AuditLogs = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Get Retention
*
* Get the configured event retention period for the given Organization.
* @param options - The request options.
* @param options.id - Unique identifier of the Organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @returns {Promise<AuditLogsRetention>}
* @throws {NotFoundException} 404
*/
async getOrganizationAuditLogsRetention(options) {
const { id } = options;
const { data } = await this.workos.get(`/organizations/${encodeURIComponent(id)}/audit_logs_retention`);
return deserializeAuditLogsRetention(data);
}
/**
* Set Retention
*
* Set the event retention period for the given Organization.
* @param options - Object containing retentionPeriod.
* @param options.id - Unique identifier of the Organization.
* @example "org_01EHZNVPK3SFK441A1RGBFSHRT"
* @param options.retentionPeriod - The period Audit Log events will be retained. Valid values are `1_MONTH` through `11_MONTHS` in one-month increments and `1_YEAR` through `10_YEARS` in one-year increments.
* @example "1_MONTH"
* @returns {Promise<AuditLogsRetention>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updateOrganizationAuditLogsRetention(options) {
const { id, ...payload } = options;
const { data } = await this.workos.put(`/organizations/${encodeURIComponent(id)}/audit_logs_retention`, serializeUpdateAuditLogsRetention(payload));
return deserializeAuditLogsRetention(data);
}
/**
* Create Event
*
* Create an Audit Log Event.
*
* This API supports idempotency which guarantees that performing the same operation multiple times will have the same result as if the operation were performed only once. This is handy in situations where you may need to retry a request due to a failure or prevent accidental duplicate requests from creating more than one resource.
*
* To achieve idempotency, you can add `Idempotency-Key` request header to a Create Event request with a unique string as the value. Each subsequent request matching this unique string will return the same response. We suggest using [v4 UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier) for idempotency keys to avoid collisions.
*
* Idempotency keys expire after 24 hours. The API will generate a new response if you submit a request with an expired key.
* @param payload - Object containing organizationId, event.
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
* @throws {RateLimitExceededException} 429
*/
async createEvent(organization, event, options = {}) {
const optionsWithIdempotency = {
...options,
idempotencyKey: options.idempotencyKey || `workos-node-${globalThis.crypto.randomUUID()}`
};
await this.workos.post("/audit_logs/events", {
event: serializeCreateAuditLogEventOptions(event),
organization_id: organization
}, optionsWithIdempotency);
}
/**
* Create Export
*
* Create an Audit Log Export. Exports are scoped to a single organization within a specified date range.
* @param payload - Object containing organizationId, rangeStart, rangeEnd.
* @returns {Promise<AuditLogExport>}
* @throws {BadRequestException} 400
*/
async createExport(options) {
const { data } = await this.workos.post("/audit_logs/exports", serializeAuditLogExportOptions(options));
return deserializeAuditLogExport(data);
}
/**
* Get Export
*
* Get an Audit Log Export. The URL will expire after 10 minutes. If the export is needed again at a later time, refetching the export will regenerate the URL.
* @param auditLogExportId - The unique ID of the Audit Log Export.
*
* @example
* "audit_log_export_01GBZK5MP7TD1YCFQHFR22180V"
*
* @returns {Promise<AuditLogExport>}
* @throws {NotFoundException} 404
*/
async getExport(auditLogExportId) {
const { data } = await this.workos.get(`/audit_logs/exports/${encodePathParameter(auditLogExportId)}`);
return deserializeAuditLogExport(data);
}
/**
* Create Schema
*
* Creates a new Audit Log schema used to validate the payload of incoming Audit Log Events. If the `action` does not exist, it will also be created.
* @param payload - Object containing targets.
* @returns {Promise<AuditLogSchema>}
* @throws {UnprocessableEntityException} 422
*/
async createSchema(schema, options = {}) {
const { data } = await this.workos.post(`/audit_logs/actions/${encodePathParameter(schema.action)}/schemas`, serializeCreateAuditLogSchemaOptions(schema), options);
return deserializeAuditLogSchema(data);
}
async listSchemas(action, options) {
const endpoint = `/audit_logs/actions/${encodePathParameter(action)}/schemas`;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeAuditLogSchema, options), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeAuditLogSchema, params), options);
}
};
// node_modules/uint8array-extras/index.js
const objectToString = Object.prototype.toString;
const uint8ArrayStringified = "[object Uint8Array]";
function isType(value, typeConstructor, typeStringified) {
if (!value) return false;
if (value.constructor === typeConstructor) return true;
return objectToString.call(value) === typeStringified;
}
function isUint8Array(value) {
return isType(value, Uint8Array, uint8ArrayStringified);
}
function assertUint8Array(value) {
if (!isUint8Array(value)) throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof value}\``);
}
new globalThis.TextDecoder("utf8");
function assertString(value) {
if (typeof value !== "string") throw new TypeError(`Expected \`string\`, got \`${typeof value}\``);
}
new globalThis.TextEncoder();
function base64ToBase64Url(base64) {
return base64.replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
}
function base64UrlToBase64(base64url) {
const base64 = base64url.replaceAll("-", "+").replaceAll("_", "/");
const padding = (4 - base64.length % 4) % 4;
return base64 + "=".repeat(padding);
}
const MAX_BLOCK_SIZE = 65535;
function uint8ArrayToBase64$1(array, { urlSafe = false } = {}) {
assertUint8Array(array);
let base64 = "";
for (let index = 0; index < array.length; index += MAX_BLOCK_SIZE) {
const chunk = array.subarray(index, index + MAX_BLOCK_SIZE);
base64 += globalThis.btoa(String.fromCodePoint.apply(void 0, chunk));
}
return urlSafe ? base64ToBase64Url(base64) : base64;
}
function base64ToUint8Array$1(base64String) {
assertString(base64String);
return Uint8Array.from(globalThis.atob(base64UrlToBase64(base64String)), (x) => x.codePointAt(0));
}
const byteToHexLookupTable = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0"));
function uint8ArrayToHex(array) {
assertUint8Array(array);
let hexString = "";
for (let index = 0; index < array.length; index++) hexString += byteToHexLookupTable[array[index]];
return hexString;
}
// node_modules/iron-webcrypto/index.js
function losslessJsonStringify(data) {
try {
if (isJson(data)) {
let stringified = JSON.stringify(data);
if (stringified) return stringified;
}
} catch {}
throw Error("Data is not JSON serializable");
}
function jsonParse(string) {
try {
return JSON.parse(string);
} catch (err) {
throw Error("Failed parsing sealed object JSON: " + err.message);
}
}
function isJson(val) {
let stack = [], seen = /* @__PURE__ */ new WeakSet(), check = (val$1) => val$1 === null || typeof val$1 == "string" || typeof val$1 == "boolean" ? !0 : typeof val$1 == "number" ? Number.isFinite(val$1) : typeof val$1 == "object" ? seen.has(val$1) ? !0 : (seen.add(val$1), stack.push(val$1), !0) : !1;
if (!check(val)) return !1;
for (; stack.length;) {
let obj = stack.pop();
if (Array.isArray(obj)) {
let i$1 = obj.length;
for (; i$1--;) if (!check(obj[i$1])) return !1;
continue;
}
let proto = Reflect.getPrototypeOf(obj);
if (proto !== null && proto !== Object.prototype) return !1;
let keys = Reflect.ownKeys(obj), i = keys.length;
for (; i--;) {
let key = keys[i];
if (typeof key != "string" || Reflect.getOwnPropertyDescriptor(obj, key)?.enumerable === !1) return !1;
let val$1 = obj[key];
if (val$1 !== void 0 && !check(val$1)) return !1;
}
}
return !0;
}
const enc = /* @__PURE__ */ new TextEncoder();
const dec = /* @__PURE__ */ new TextDecoder();
const jsBase64Enabled = /* @__PURE__ */ (() => typeof Uint8Array.fromBase64 == "function" && typeof Uint8Array.prototype.toBase64 == "function" && typeof Uint8Array.prototype.toHex == "function")();
function b64ToU8(str) {
return jsBase64Enabled ? Uint8Array.fromBase64(str, { alphabet: "base64url" }) : base64ToUint8Array$1(str);
}
function u8ToB64(arr) {
return arr = arr instanceof ArrayBuffer ? new Uint8Array(arr) : arr, jsBase64Enabled ? arr.toBase64({
alphabet: "base64url",
omitPadding: !0
}) : uint8ArrayToBase64$1(arr, { urlSafe: !0 });
}
function u8ToHex(arr) {
return arr = arr instanceof ArrayBuffer ? new Uint8Array(arr) : arr, jsBase64Enabled ? arr.toHex() : uint8ArrayToHex(arr);
}
const defaults = /* @__PURE__ */ Object.freeze({
encryption: /* @__PURE__ */ Object.freeze({
algorithm: "aes-256-cbc",
saltBits: 256,
iterations: 1,
minPasswordlength: 32
}),
integrity: /* @__PURE__ */ Object.freeze({
algorithm: "sha256",
saltBits: 256,
iterations: 1,
minPasswordlength: 32
}),
ttl: 0,
timestampSkewSec: 60,
localtimeOffsetMsec: 0
});
const algorithms = /* @__PURE__ */ Object.freeze({
"aes-128-ctr": /* @__PURE__ */ Object.freeze({
keyBits: 128,
ivBits: 128,
name: "AES-CTR"
}),
"aes-256-cbc": /* @__PURE__ */ Object.freeze({
keyBits: 256,
ivBits: 128,
name: "AES-CBC"
}),
sha256: /* @__PURE__ */ Object.freeze({
keyBits: 256,
ivBits: void 0,
name: "SHA-256"
})
});
function randomBits(bits) {
return crypto.getRandomValues(new Uint8Array(bits / 8));
}
async function generateKey(password, options) {
if (!password || !password.length) throw Error("Empty password");
if (!options || typeof options != "object") throw Error("Bad options");
let algorithm = algorithms[options.algorithm];
if (!algorithm) throw Error("Unknown algorithm: " + options.algorithm);
let isHmac = algorithm.name === "SHA-256", id = isHmac ? {
name: "HMAC",
hash: algorithm.name,
length: algorithm.keyBits
} : {
name: algorithm.name,
length: algorithm.keyBits
}, usages = isHmac ? ["sign", "verify"] : ["encrypt", "decrypt"], iv = options.iv || (algorithm.ivBits ? randomBits(algorithm.ivBits) : void 0);
if (typeof password == "string") {
if (password.length < options.minPasswordlength) throw Error("Password string too short (min " + options.minPasswordlength + " characters required)");
let salt = options.salt;
if (!salt) {
if (!options.saltBits) throw Error("Missing salt and saltBits options");
salt = u8ToHex(randomBits(options.saltBits));
}
let baseKey = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", !1, ["deriveKey"]), algorithm$1 = {
name: "PBKDF2",
salt: enc.encode(salt),
iterations: options.iterations,
hash: "SHA-1"
};
return {
key: await crypto.subtle.deriveKey(algorithm$1, baseKey, id, !1, usages),
iv,
salt
};
}
if (password.length < algorithm.keyBits / 8) throw Error("Key buffer (password) too small");
return {
key: await crypto.subtle.importKey("raw", password.slice(), id, !1, usages),
iv,
salt: ""
};
}
function getEncryptParams(algorithm, key, data) {
return [
algorithm === "aes-128-ctr" ? {
name: "AES-CTR",
counter: key.iv,
length: 128
} : {
name: "AES-CBC",
iv: key.iv
},
key.key,
typeof data == "string" ? enc.encode(data) : data.slice()
];
}
async function encrypt(password, options, data) {
let key = await generateKey(password, options), encrypted = await crypto.subtle.encrypt(...getEncryptParams(options.algorithm, key, data));
return {
encrypted: new Uint8Array(encrypted),
key
};
}
async function decrypt(password, options, data) {
let key = await generateKey(password, options), decrypted = await crypto.subtle.decrypt(...getEncryptParams(options.algorithm, key, data));
return dec.decode(decrypted);
}
async function hmacWithPassword(password, options, data) {
let key = await generateKey(password, options);
return {
digest: u8ToB64(await crypto.subtle.sign("HMAC", key.key, enc.encode(data))),
salt: key.salt
};
}
function normalizePassword(password) {
let normalized = typeof password == "string" || password instanceof Uint8Array ? {
encryption: password,
integrity: password
} : password && typeof password == "object" ? "secret" in password ? {
id: password.id,
encryption: password.secret,
integrity: password.secret
} : {
id: password.id,
encryption: password.encryption,
integrity: password.integrity
} : void 0;
if (!normalized || !normalized.encryption || normalized.encryption.length === 0 || !normalized.integrity || normalized.integrity.length === 0) throw Error("Empty password");
return normalized;
}
async function seal(object, password, options) {
let now = Date.now() + (options.localtimeOffsetMsec || 0), { id = "", encryption, integrity } = normalizePassword(password);
if (id && !/^\w+$/.test(id)) throw Error("Invalid password id");
let { encrypted, key } = await encrypt(encryption, options.encryption, (options.encode || losslessJsonStringify)(object)), expiration = options.ttl ? now + options.ttl : "", macBaseString = "Fe26.2*" + id + "*" + key.salt + "*" + u8ToB64(key.iv) + "*" + u8ToB64(encrypted) + "*" + expiration, mac = await hmacWithPassword(integrity, options.integrity, macBaseString);
return macBaseString + "*" + mac.salt + "*" + mac.digest;
}
async function unseal(sealed, password, options) {
let now = Date.now() + (options.localtimeOffsetMsec || 0), parts = sealed.split("*");
if (parts.length !== 8) throw Error("Incorrect number of sealed components");
let [prefix, passwordId, encryptionSalt, ivB64, encryptedB64, expiration, hmacSalt, hmacDigestB64] = parts;
if (prefix !== "Fe26.2") throw Error("Wrong mac prefix");
if (expiration) {
if (!/^[1-9]\d*$/.test(expiration)) throw Error("Invalid expiration");
if (Number.parseInt(expiration, 10) <= now - options.timestampSkewSec * 1e3) throw Error("Expired seal");
}
let pass;
if (typeof password == "string" || password instanceof Uint8Array) pass = password;
else if (typeof password == "object" && password) {
let passwordIdKey = passwordId || "default";
if (pass = password[passwordIdKey], !pass) throw Error("Cannot find password: " + passwordIdKey);
}
pass = normalizePassword(pass);
let key = await generateKey(pass.integrity, {
...options.integrity,
salt: hmacSalt
}), macBaseString = prefix + "*" + passwordId + "*" + encryptionSalt + "*" + ivB64 + "*" + encryptedB64 + "*" + expiration;
if (!await crypto.subtle.verify("HMAC", key.key, b64ToU8(hmacDigestB64), enc.encode(macBaseString))) throw Error("Bad hmac value");
let decryptedString = await decrypt(pass.encryption, {
...options.encryption,
salt: encryptionSalt,
iv: b64ToU8(ivB64)
}, b64ToU8(encryptedB64));
return (options.decode || jsonParse)(decryptedString);
}
// src/common/crypto/seal.ts
const VERSION_DELIMITER = "~";
const CURRENT_MAJOR_VERSION = 2;
function parseSeal(seal) {
const [sealWithoutVersion = "", tokenVersionAsString] = seal.split(VERSION_DELIMITER);
return {
sealWithoutVersion,
tokenVersion: tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10)
};
}
async function sealData(data, { password }) {
return `${await seal(data, {
id: "1",
secret: password
}, {
...defaults,
ttl: 0,
encode: JSON.stringify
})}${VERSION_DELIMITER}${CURRENT_MAJOR_VERSION}`;
}
async function unsealData(encryptedData, { password }) {
const { sealWithoutVersion, tokenVersion } = parseSeal(encryptedData);
const passwordMap = { 1: password };
let data;
try {
data = await unseal(sealWithoutVersion, passwordMap, {
...defaults,
ttl: 0
}) ?? {};
} catch (error) {
if (error instanceof Error && /^(Expired seal|Bad hmac value|Cannot find password|Incorrect number of sealed components|Wrong mac prefix)/.test(error.message)) return {};
throw error;
}
if (tokenVersion === 2) return data;
else if (tokenVersion !== null) return data.persistent ?? data;
return data;
}
// src/user-management/serializers/session-cookie-data.serializer.ts
const toDate = (value) => value instanceof Date ? value : new Date(value);
const deserializeSessionCookieData = (data) => {
if (!data.user) return data;
return {
...data,
user: {
...data.user,
createdAt: toDate(data.user.createdAt),
updatedAt: toDate(data.user.updatedAt),
lastSignInAt: data.user.lastSignInAt != null ? toDate(data.user.lastSignInAt) : null
}
};
};
// src/common/utils/env.ts
let detectedRuntime = null;
/**
* Detect the current runtime environment.
* This function checks for various runtime environments such as Node.js, Deno, Bun, Cloudflare Workers, Fastly, and Edge Light.
* It returns a string representing the detected runtime and caches the result for future calls.
* @returns The detected runtime environment as a string.
*/
function detectRuntime() {
if (detectedRuntime) return detectedRuntime;
const global = globalThis;
if (typeof global.Deno !== "undefined") detectedRuntime = "deno";
else if (typeof global.Bun !== "undefined" || typeof process !== "undefined" && process.versions?.bun || typeof navigator !== "undefined" && navigator.userAgent?.includes("Bun")) detectedRuntime = "bun";
else if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare")) detectedRuntime = "cloudflare";
else if (typeof process !== "undefined" && process.release?.name === "node") detectedRuntime = "node";
else if (typeof global !== "undefined" && "fastly" in global) detectedRuntime = "fastly";
else if (typeof global !== "undefined" && "EdgeRuntime" in global) detectedRuntime = "edge-light";
else detectedRuntime = "other";
return detectedRuntime;
}
function getEnvironmentVariable(key) {
const runtime = detectRuntime();
const global = globalThis;
try {
switch (runtime) {
case "node":
case "bun":
case "edge-light": return process.env[key];
case "deno": return global.Deno.env.get(key);
case "cloudflare": return global.env?.[key] ?? global[key] ?? (typeof process !== "undefined" ? process.env?.[key] : void 0);
case "fastly": return global[key];
default: return process?.env?.[key] ?? global.env?.[key] ?? global[key];
}
} catch {
return;
}
}
/**
* Get an environment variable value, trying to access it in different runtimes.
* @param key - The name of the environment variable.
* @param defaultValue - The default value to return if the variable is not found.
* @return The value of the environment variable or the default value.
*/
function getEnv(key, defaultValue) {
return getEnvironmentVariable(key) ?? defaultValue;
}
// src/user-management/interfaces/authenticate-with-session-cookie.interface.ts
let AuthenticateWithSessionCookieFailureReason = /* @__PURE__ */ function(AuthenticateWithSessionCookieFailureReason) {
AuthenticateWithSessionCookieFailureReason["INVALID_JWT"] = "invalid_jwt";
AuthenticateWithSessionCookieFailureReason["INVALID_SESSION_COOKIE"] = "invalid_session_cookie";
AuthenticateWithSessionCookieFailureReason["NO_SESSION_COOKIE_PROVIDED"] = "no_session_cookie_provided";
return AuthenticateWithSessionCookieFailureReason;
}({});
// src/user-management/interfaces/revoke-session-options.interface.ts
const serializeRevokeSessionOptions = (options) => ({ session_id: options.sessionId });
// src/user-management/serializers/authenticate-with-email-verification.serializer.ts
const serializeAuthenticateWithEmailVerificationOptions = (options) => ({
grant_type: "urn:workos:oauth:grant-type:email-verification:code",
client_id: options.clientId,
client_secret: options.clientSecret,
pending_authentication_token: options.pendingAuthenticationToken,
code: options.code,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/authenticate-with-organization-selection-options.serializer.ts
const serializeAuthenticateWithOrganizationSelectionOptions = (options) => ({
grant_type: "urn:workos:oauth:grant-type:organization-selection",
client_id: options.clientId,
client_secret: options.clientSecret,
pending_authentication_token: options.pendingAuthenticationToken,
organization_id: options.organizationId,
ip_address: options.ipAddress,
user_agent: options.userAgent
});
// src/user-management/serializers/create-organization-membership-options.serializer.ts
const serializeCreateOrganizationMembershipOptions = (options) => ({
organization_id: options.organizationId,
user_id: options.userId,
role_slug: options.roleSlug,
role_slugs: options.roleSlugs
});
// src/user-management/serializers/identity.serializer.ts
const normalizeProvider = (provider) => {
if (provider === "GithubOAuth") return "GitHubOAuth";
return provider;
};
const deserializeIdentities = (identities) => {
return identities.map((identity) => {
return {
idpId: identity.idp_id,
type: identity.type,
provider: normalizeProvider(identity.provider)
};
});
};
// src/user-management/serializers/list-invitations-options.serializer.ts
const serializeListInvitationsOptions = (options) => ({
email: options.email,
organization_id: options.organizationId,
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
});
// src/user-management/serializers/list-organization-memberships-options.serializer.ts
const serializeListOrganizationMembershipsOptions = (options) => ({
user_id: options.userId,
organization_id: options.organizationId,
statuses: options.statuses?.join(","),
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
});
// src/user-management/serializers/list-users-options.serializer.ts
const serializeListUsersOptions = (options) => ({
email: options.email,
organization_id: options.organizationId,
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
});
// src/user-management/serializers/resend-invitation-options.serializer.ts
const serializeResendInvitationOptions = (options) => ({ locale: options.locale });
// src/user-management/interfaces/refresh-and-seal-session-data.interface.ts
let RefreshSessionFailureReason = /* @__PURE__ */ function(RefreshSessionFailureReason) {
RefreshSessionFailureReason["INVALID_SESSION_COOKIE"] = "invalid_session_cookie";
RefreshSessionFailureReason["NO_SESSION_COOKIE_PROVIDED"] = "no_session_cookie_provided";
RefreshSessionFailureReason["INVALID_GRANT"] = "invalid_grant";
RefreshSessionFailureReason["MFA_ENROLLMENT"] = "mfa_enrollment";
RefreshSessionFailureReason["SSO_REQUIRED"] = "sso_required";
RefreshSessionFailureReason["RATE_LIMIT_EXCEEDED"] = "rate_limit_exceeded";
RefreshSessionFailureReason["TIMEOUT"] = "timeout";
RefreshSessionFailureReason["SERVER_ERROR"] = "server_error";
RefreshSessionFailureReason["NETWORK_ERROR"] = "network_error";
return RefreshSessionFailureReason;
}({});
// src/user-management/serializers/send-invitation-options.serializer.ts
const serializeSendInvitationOptions = (options) => ({
email: options.email,
organization_id: options.organizationId,
expires_in_days: options.expiresInDays,
inviter_user_id: options.inviterUserId,
role_slug: options.roleSlug,
locale: options.locale
});
// src/user-management/serializers/update-organization-membership-options.serializer.ts
const serializeUpdateOrganizationMembershipOptions = (options) => ({
role_slug: options.roleSlug,
role_slugs: options.roleSlugs
});
// src/user-management/serializers/create-waitlist-entry-options.serializer.ts
const serializeCreateWaitlistEntryOptions = (options) => ({
email: options.email,
additional_fields: options.additionalFields,
send_confirmation_email: options.sendConfirmationEmail
});
// src/user-management/serializers/list-waitlist-entries-options.serializer.ts
const serializeListWaitlistEntriesOptions = (options) => ({
state: options.state,
email: options.email,
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
});
// src/user-management/session.ts
var CookieSession = class {
userManagement;
cookiePassword;
sessionData;
constructor(userManagement, sessionData, cookiePassword) {
if (!cookiePassword) throw new Error("cookiePassword is required");
this.userManagement = userManagement;
this.cookiePassword = cookiePassword;
this.sessionData = sessionData;
}
/**
* Authenticates a user with a session cookie.
*
* @returns An object indicating whether the authentication was successful or not. If successful, it will include the user's session data.
*/
async authenticate() {
if (!this.sessionData) return {
authenticated: false,
reason: "no_session_cookie_provided"
};
const session = deserializeSessionCookieData(await unsealData(this.sessionData, { password: this.cookiePassword }));
if (!session.accessToken) return {
authenticated: false,
reason: "invalid_session_cookie"
};
const claims = await this.userManagement.verifyAccessToken(session.accessToken);
if (!claims) return {
authenticated: false,
reason: "invalid_jwt"
};
const { sid: sessionId, org_id: organizationId, role, roles, permissions, entitlements, feature_flags: featureFlags } = claims;
return {
authenticated: true,
sessionId,
organizationId,
role,
roles,
permissions,
entitlements,
featureFlags,
user: session.user,
authenticationMethod: session.authenticationMethod,
impersonator: session.impersonator,
accessToken: session.accessToken
};
}
/**
* Refreshes the user's session.
*
* @param options - Optional options for refreshing the session.
* @param options.cookiePassword - The password to use for the new session cookie.
* @param options.organizationId - The organization ID to use for the new session cookie.
* @returns An object indicating whether the refresh was successful or not. If successful, it will include the new sealed session data.
*/
async refresh(options = {}) {
const { decodeJwt } = await getJose();
const session = deserializeSessionCookieData(await unsealData(this.sessionData, { password: this.cookiePassword }));
if (!session.refreshToken || !session.user) return {
authenticated: false,
reason: "invalid_session_cookie",
retryable: false
};
const { org_id: organizationIdFromUserManagementAccessToken } = decodeJwt(session.accessToken);
try {
const cookiePassword = options.cookiePassword ?? this.cookiePassword;
const authenticationResponse = await this.userManagement.authenticateWithRefreshToken({
clientId: this.userManagement.clientId,
refreshToken: session.refreshToken,
organizationId: options.organizationId ?? organizationIdFromUserManagementAccessToken,
session: {
sealSession: true,
cookiePassword
}
});
if (options.cookiePassword) this.cookiePassword = options.cookiePassword;
this.sessionData = authenticationResponse.sealedSession;
const { sid: sessionId, org_id: organizationId, role, roles, permissions, entitlements, feature_flags: featureFlags } = decodeJwt(authenticationResponse.accessToken);
return {
authenticated: true,
sealedSession: authenticationResponse.sealedSession,
session: authenticationResponse,
authenticationMethod: authenticationResponse.authenticationMethod,
sessionId,
organizationId,
role,
roles,
permissions,
entitlements,
featureFlags,
user: authenticationResponse.user,
impersonator: authenticationResponse.impersonator
};
} catch (error) {
const terminalReason = classifyTerminalRefreshError(error);
if (terminalReason) return {
authenticated: false,
reason: terminalReason,
retryable: false
};
const retryableFailure = classifyRetryableRefreshError(error);
if (retryableFailure) return retryableFailure;
throw error;
}
}
/**
* Gets the URL to redirect the user to for logging out.
*
* Works for sessions whose access token has expired. The sealed cookie is
* already authenticated by its encryption, so the session ID is read from
* the access token without verifying it.
*
* @returns The URL to redirect the user to for logging out.
*/
async getLogoutUrl({ returnTo } = {}) {
if (!this.sessionData) throw new Error(`Failed to extract session ID for logout URL: no_session_cookie_provided`);
const { accessToken } = await unsealData(this.sessionData, { password: this.cookiePassword });
if (!accessToken) throw new Error(`Failed to extract session ID for logout URL: invalid_session_cookie`);
const { decodeJwt } = await getJose();
const { sid: sessionId } = decodeJwt(accessToken);
return this.userManagement.getLogoutUrl({
sessionId,
returnTo
});
}
};
/**
* Classifies an error thrown while refreshing as a terminal authentication
* failure — the session is over and the user must re-authenticate — returning
* the matching failure reason, or `null` when the error is not a recognized
* terminal failure (and may still be retryable or should be rethrown).
*/
function classifyTerminalRefreshError(error) {
if (error instanceof OauthException && error.error === "invalid_grant") return "invalid_grant";
if (error instanceof AuthenticationException) {
const code = error.code;
if (code === "mfa_enrollment") return "mfa_enrollment";
if (code === "sso_required") return "sso_required";
}
return null;
}
function classifyRetryableRefreshError(error) {
if (error instanceof RateLimitExceededException) return {
authenticated: false,
reason: "rate_limit_exceeded",
retryable: true,
retryAfter: error.retryAfter ?? void 0,
error
};
const status = getErrorStatus(error);
if (status === 429) return {
authenticated: false,
reason: "rate_limit_exceeded",
retryable: true,
error
};
if (status === 408) return {
authenticated: false,
reason: "timeout",
retryable: true,
error
};
if (status !== void 0 && status >= 500) return {
authenticated: false,
reason: "server_error",
retryable: true,
error
};
if (isNetworkError(error)) return {
authenticated: false,
reason: "network_error",
retryable: true,
error
};
return null;
}
function getErrorStatus(error) {
if (error instanceof OauthException || error instanceof GenericServerException) return error.status;
}
function isNetworkError(error) {
return error instanceof TypeError || error instanceof Error && error.cause instanceof TypeError;
}
// src/user-management/user-management.ts
var UserManagement = class UserManagement {
workos;
_jwks;
clientId;
issuer;
constructor(workos) {
this.workos = workos;
this.clientId = workos.clientId;
this.issuer = workos.options.issuer;
}
/**
* Resolve clientId from method options or fall back to constructor-provided value.
* @throws TypeError if clientId is not available from either source
*/
resolveClientId(clientId) {
const resolved = clientId ?? this.clientId;
if (!resolved) throw new TypeError("clientId is required. Provide it in method options or when initializing WorkOS.");
return resolved;
}
async getJWKS() {
const { createRemoteJWKSet } = await getJose();
if (!this.clientId) return;
this._jwks ??= createRemoteJWKSet(new URL(this.getJwksUrl(this.clientId)), { cooldownDuration: 3e5 });
return this._jwks;
}
/**
* Loads a sealed session using the provided session data and cookie password.
*
* @param options - The options for loading the sealed session.
* @param options.sessionData - The sealed session data.
* @param options.cookiePassword - The password used to encrypt the session data.
* @returns The session class.
*/
loadSealedSession(options) {
return new CookieSession(this, options.sessionData, options.cookiePassword);
}
/**
* Get a user
*
* Get the details of an existing user.
* @param userId - The unique ID of the user.
* @returns {Promise<User>}
* @throws {NotFoundException} 404
*/
async getUser(userId) {
const { data } = await this.workos.get(`/user_management/users/${encodePathParameter(userId)}`);
return deserializeUser(data);
}
/**
* Get a user by external ID
*
* Get the details of an existing user by an [external identifier](https://workos.com/docs/authkit/metadata/external-identifiers).
* @param externalId - The external ID of the user.
*
* @example
* "f1ffa2b2-c20b-4d39-be5c-212726e11222"
*
* @returns {Promise<User>}
* @throws {NotFoundException} 404
*/
async getUserByExternalId(externalId) {
const { data } = await this.workos.get(`/user_management/users/external_id/${encodePathParameter(externalId)}`);
return deserializeUser(data);
}
/**
* List users
*
* Get a list of all of your existing users matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<User, SerializedListUsersOptions>>}
* @throws {UnprocessableEntityException} 422
*/
async listUsers(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/user_management/users", deserializeUser, options ? serializeListUsersOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/user_management/users", deserializeUser, params), options ? serializeListUsersOptions(options) : void 0);
}
/**
* Create a user
*
* Create a new user in the current environment.
* @param payload - Object containing email.
* @returns {Promise<CreateUserResponse>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createUser(payload) {
const { data } = await this.workos.post("/user_management/users", serializeCreateUserOptions(payload));
const { radar_auth_attempt_id, ...userResponse } = data;
return {
...deserializeUser(userResponse),
...radar_auth_attempt_id ? { radarAuthAttemptId: radar_auth_attempt_id } : void 0
};
}
/** Authenticate with magic auth. */
async authenticateWithMagicAuth(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithMagicAuthOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/** Authenticate with password. */
async authenticateWithPassword(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithPasswordOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/**
* Exchange an authorization code for tokens.
*
* Auto-detects public vs confidential client mode:
* - If codeVerifier is provided: Uses PKCE flow (public client)
* - If no codeVerifier: Uses client_secret from API key (confidential client)
* - If both: Uses both client_secret AND codeVerifier (confidential client with PKCE)
*
* Using PKCE with confidential clients is recommended by OAuth 2.1 for defense
* in depth and provides additional CSRF protection on the authorization flow.
*
* @throws Error if neither codeVerifier nor API key is available
*/
async authenticateWithCode(payload) {
const { session, clientId, codeVerifier, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
if (codeVerifier !== void 0 && codeVerifier.trim() === "") throw new TypeError("codeVerifier cannot be an empty string. Generate a valid PKCE pair using workos.pkce.generate().");
const hasApiKey = !!this.workos.key;
if (!!!codeVerifier && !hasApiKey) throw new TypeError("authenticateWithCode requires either a codeVerifier (for public clients) or an API key configured on the WorkOS instance (for confidential clients).");
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithCodeOptions({
...remainingPayload,
clientId: resolvedClientId,
codeVerifier,
clientSecret: hasApiKey ? this.workos.key : void 0
}), { skipApiKeyCheck: !hasApiKey });
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/**
* Exchange an authorization code for tokens using PKCE (public client flow).
* Use this instead of authenticateWithCode() when the client cannot securely
* store a client_secret (browser, mobile, CLI, desktop apps).
*
* @param payload.clientId - Your WorkOS client ID
* @param payload.code - The authorization code from the OAuth callback
* @param payload.codeVerifier - The PKCE code verifier used to generate the code challenge
*/
async authenticateWithCodeAndVerifier(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithCodeAndVerifierOptions({
...remainingPayload,
clientId: resolvedClientId
}), { skipApiKeyCheck: true });
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/**
* Refresh an access token using a refresh token.
* Automatically detects public client mode - if no API key is configured,
* omits client_secret from the request.
*/
async authenticateWithRefreshToken(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const isPublicClient = !this.workos.key;
const body = isPublicClient ? serializeAuthenticateWithRefreshTokenPublicClientOptions({
...remainingPayload,
clientId: resolvedClientId
}) : serializeAuthenticateWithRefreshTokenOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
});
const { data } = await this.workos.post("/user_management/authenticate", body, { skipApiKeyCheck: isPublicClient });
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/** Authenticate with totp. */
async authenticateWithTotp(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithTotpOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/** Authenticate with email verification. */
async authenticateWithEmailVerification(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithEmailVerificationOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/** Authenticate with organization selection. */
async authenticateWithOrganizationSelection(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithOrganizationSelectionOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/** Send a Radar SMS challenge. */
async sendRadarSmsChallenge(payload) {
const { data } = await this.workos.post("/user_management/radar_challenges", serializeSendRadarSmsChallengeOptions(payload));
return {
verificationId: data.verification_id,
phoneNumber: data.phone_number
};
}
/** Authenticate with Radar SMS challenge. */
async authenticateWithRadarSmsChallenge(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithRadarSmsChallengeOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
/** Authenticate with Radar email challenge. */
async authenticateWithRadarEmailChallenge(payload) {
const { session, clientId, ...remainingPayload } = payload;
const resolvedClientId = this.resolveClientId(clientId);
const { data } = await this.workos.post("/user_management/authenticate", serializeAuthenticateWithRadarEmailChallengeOptions({
...remainingPayload,
clientId: resolvedClientId,
clientSecret: this.workos.key
}));
return this.prepareAuthenticationResponse({
authenticationResponse: deserializeAuthenticationResponse(data),
session
});
}
async authenticateWithSessionCookie({ sessionData, cookiePassword = getEnv("WORKOS_COOKIE_PASSWORD") }) {
if (!cookiePassword) throw new Error("Cookie password is required");
if (!sessionData) return {
authenticated: false,
reason: "no_session_cookie_provided"
};
const session = deserializeSessionCookieData(await unsealData(sessionData, { password: cookiePassword }));
if (!session.accessToken) return {
authenticated: false,
reason: "invalid_session_cookie"
};
const claims = await this.verifyAccessToken(session.accessToken);
if (!claims) return {
authenticated: false,
reason: "invalid_jwt"
};
const { sid: sessionId, org_id: organizationId, role, roles, permissions, entitlements, feature_flags: featureFlags } = claims;
return {
authenticated: true,
sessionId,
organizationId,
role,
roles,
user: session.user,
permissions,
entitlements,
featureFlags,
accessToken: session.accessToken,
authenticationMethod: session.authenticationMethod
};
}
/**
* Verify an access token and return its claims.
*
* Checks the token's signature against the environment's JWKS and its
* expiry, plus the issuer when one was configured on the client, and that
* the payload carries the claims of a WorkOS user access token. Tokens the
* environment signed for another purpose, such as agent or widget session
* tokens, are rejected. Resolves to `null` when the token fails any of
* those checks, is not a JWT, or was signed by a key the JWKS does not
* have. Errors that are not JWT validation failures, such as a network
* error while fetching the JWKS, propagate.
*
* @param accessToken - The access token to verify, for example from an `Authorization: Bearer` header.
* @returns {Promise<AccessTokenClaims | null>} The token's claims, or `null` when the token is invalid.
* @throws {Error} When no client ID was provided when initializing WorkOS.
*/
async verifyAccessToken(accessToken) {
const payload = await this.verifyJwt(accessToken);
if (payload === null || !UserManagement.hasRequiredAccessTokenClaims(payload)) return null;
return payload;
}
/**
* Several token families are signed with an environment's key pair, so a
* valid signature alone does not prove a token is a user access token. This
* mirrors how the API identifies one: `sid` and `auth_time` are always
* minted together on user access tokens, agent tokens classify themselves
* with a `sub_profile` other than `user`, and widget session tokens carry
* `sub_type`. The registered claims `AccessTokenClaims` guarantees are
* checked too, so a token is rejected rather than returned with missing
* values.
*
* Consent tokens for interactive Connect grants also mint `sid` and
* `auth_time`. The API excludes those by resolving `sid` to a live
* session, which cannot be done offline here.
*/
static hasRequiredAccessTokenClaims(payload) {
return typeof payload.sub === "string" && typeof payload.sid === "string" && typeof payload.iss === "string" && typeof payload.exp === "number" && typeof payload.iat === "number" && typeof payload.auth_time === "number" && (payload.sub_profile === void 0 || payload.sub_profile === "user") && payload.sub_type === void 0;
}
/**
* Verify a JWT's signature, expiry and, when configured, issuer against the
* environment's JWKS. Resolves to the payload, or `null` when jose rejects
* the token; errors that are not JWT validation failures propagate.
*/
async verifyJwt(accessToken) {
const jwks = await this.getJWKS();
const { jwtVerify } = await getJose();
if (!jwks) throw new Error("Must provide clientId to initialize JWKS");
try {
const { payload } = await jwtVerify(accessToken, jwks, this.issuer ? { issuer: this.issuer } : void 0);
return payload;
} catch (e) {
if (UserManagement.isJwtValidationError(e)) return null;
throw e;
}
}
/**
* Whether a jose error means the presented token is invalid, as opposed to
* a failure to verify it at all. Network errors, JWKS timeouts and crypto
* failures propagate so they surface as errors rather than as rejected
* tokens.
*/
static isJwtValidationError(e) {
if (!(e instanceof Error) || !("code" in e) || typeof e.code !== "string") return false;
return e.code.startsWith("ERR_JWT_") || e.code.startsWith("ERR_JWS_") || e.code === "ERR_JWKS_NO_MATCHING_KEY" || e.code === "ERR_JWKS_MULTIPLE_MATCHING_KEYS" || e.code === "ERR_JOSE_NOT_SUPPORTED" || e.code === "ERR_JOSE_ALG_NOT_ALLOWED";
}
async prepareAuthenticationResponse({ authenticationResponse, session }) {
if (session?.sealSession) {
if (!this.workos.key) throw new Error("Session sealing requires server-side usage with an API key. Public clients should store tokens directly (e.g., secure storage on mobile, keychain on desktop).");
return {
...authenticationResponse,
sealedSession: await this.sealSessionDataFromAuthenticationResponse({
authenticationResponse,
cookiePassword: session.cookiePassword
})
};
}
return authenticationResponse;
}
async sealSessionDataFromAuthenticationResponse({ authenticationResponse, cookiePassword }) {
if (!cookiePassword) throw new Error("Cookie password is required");
const { decodeJwt } = await getJose();
const { org_id: organizationIdFromAccessToken } = decodeJwt(authenticationResponse.accessToken);
return sealData({
organizationId: organizationIdFromAccessToken,
user: authenticationResponse.user,
accessToken: authenticationResponse.accessToken,
refreshToken: authenticationResponse.refreshToken,
authenticationMethod: authenticationResponse.authenticationMethod,
impersonator: authenticationResponse.impersonator
}, { password: cookiePassword });
}
async getSessionFromCookie({ sessionData, cookiePassword = getEnv("WORKOS_COOKIE_PASSWORD") }) {
if (!cookiePassword) throw new Error("Cookie password is required");
if (sessionData) return deserializeSessionCookieData(await unsealData(sessionData, { password: cookiePassword }));
}
/**
* Get an email verification code
*
* Get the details of an existing email verification code that can be used to send an email to a user for verification.
* @returns {Promise<EmailVerification>}
* @throws {NotFoundException} 404
*/
async getEmailVerification(emailVerificationId) {
const { data } = await this.workos.get(`/user_management/email_verification/${encodePathParameter(emailVerificationId)}`);
return deserializeEmailVerification(data);
}
/**
* Send verification email
*
* Sends an email that contains a one-time code used to verify a user’s email address.
* @returns {Promise<{ user: User; }>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {RateLimitExceededException} 429
*/
async sendVerificationEmail({ userId }) {
const { data } = await this.workos.post(`/user_management/users/${encodePathParameter(userId)}/email_verification/send`, {});
return { user: deserializeUser(data.user) };
}
/**
* Get Magic Auth code details
*
* Get the details of an existing [Magic Auth](https://workos.com/docs/reference/authkit/magic-auth) code that can be used to send an email to a user for authentication.
* @returns {Promise<MagicAuth>}
* @throws {NotFoundException} 404
*/
async getMagicAuth(magicAuthId) {
const { data } = await this.workos.get(`/user_management/magic_auth/${encodePathParameter(magicAuthId)}`);
return deserializeMagicAuth(data);
}
/**
* Create a Magic Auth code
*
* Creates a one-time authentication code that can be sent to the user's email address. The code expires in 10 minutes. To verify the code, [authenticate the user with Magic Auth](https://workos.com/docs/reference/authkit/authentication/magic-auth).
* @param options - Object containing email.
* @returns {Promise<CreateMagicAuthResponse>}
* @throws {BadRequestException} 400
* @throws {UnprocessableEntityException} 422
* @throws {RateLimitExceededException} 429
*/
async createMagicAuth(options) {
const { data } = await this.workos.post("/user_management/magic_auth", serializeCreateMagicAuthOptions({ ...options }));
const { radar_auth_attempt_id, ...magicAuthResponse } = data;
return {
...deserializeMagicAuth(magicAuthResponse),
...radar_auth_attempt_id ? { radarAuthAttemptId: radar_auth_attempt_id } : void 0
};
}
/**
* Verify email
*
* Verifies an email address using the one-time code received by the user.
* @param options - Object containing code.
* @returns {Promise<{ user: User; }>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async verifyEmail({ code, userId }) {
const { data } = await this.workos.post(`/user_management/users/${encodePathParameter(userId)}/email_verification/confirm`, { code });
return { user: deserializeUser(data.user) };
}
/**
* Get a password reset token
*
* Get the details of an existing password reset token that can be used to reset a user's password.
* @returns {Promise<PasswordReset>}
* @throws {NotFoundException} 404
*/
async getPasswordReset(passwordResetId) {
const { data } = await this.workos.get(`/user_management/password_reset/${encodePathParameter(passwordResetId)}`);
return deserializePasswordReset(data);
}
async createPasswordReset(options) {
const { data } = await this.workos.post("/user_management/password_reset", serializeCreatePasswordResetOptions({ ...options }));
return deserializePasswordReset(data);
}
/**
* Reset the password
*
* Sets a new password using the `token` query parameter from the link that
* the user received. Successfully resetting the password will verify a
* user's email, if it hasn't been verified yet.
* @param payload - Object containing the reset token and new password.
* @returns {Promise<{ user: User; }>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
* @throws {RateLimitExceededException} 429
*/
async resetPassword(payload) {
const { data } = await this.workos.post("/user_management/password_reset/confirm", serializeResetPasswordOptions(payload));
return { user: deserializeUser(data.user) };
}
/**
* Update a user
*
* Updates properties of a user. The omitted properties will be left unchanged.
* @param payload - The request body.
* @returns {Promise<User>}
* @throws {BadRequestException} 400
* @throws {UnprocessableEntityException} 422
*/
async updateUser(payload) {
const { data } = await this.workos.put(`/user_management/users/${encodePathParameter(payload.userId)}`, serializeUpdateUserOptions(payload));
return deserializeUser(data);
}
/**
* List sessions
*
* Get a list of all active sessions for a specific user.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Session, SerializedListSessionsOptions>>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listSessions(userId, options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/sessions`, deserializeSession, options ? serializeListSessionsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/sessions`, deserializeSession, params), options ? serializeListSessionsOptions(options) : void 0);
}
/**
* List authorized applications
*
* Get a list of Connect applications that the user has authorized.
* @param userId - The ID of the user.
* @param options - Pagination options.
* @returns {Promise<AutoPaginatable<AuthorizedConnectApplication>>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listAuthorizedApplications(userId, options) {
const path = `/user_management/users/${encodePathParameter(userId)}/authorized_applications`;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, path, deserializeAuthorizedConnectApplication, options), (params) => fetchAndDeserialize(this.workos, path, deserializeAuthorizedConnectApplication, params), options);
}
/**
* Delete an authorized application
*
* Removes a user's authorization without deleting the Connect application.
* @param userId - The ID of the user.
* @param applicationId - The ID or client ID of the application.
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteAuthorizedApplication(userId, applicationId) {
await this.workos.delete(`/user_management/users/${encodePathParameter(userId)}/authorized_applications/${encodePathParameter(applicationId)}`);
}
/**
* Delete a user
*
* Permanently deletes a user in the current environment. It cannot be undone.
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteUser(userId) {
await this.workos.delete(`/user_management/users/${encodePathParameter(userId)}`);
}
/**
* List API keys for a user
*
* Get a list of API keys owned by a specific user.
* @param userId - Unique identifier of the user.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<UserApiKey, SerializedListUserApiKeysOptions>>}
* @throws {NotFoundException} 404
*/
async listUserApiKeys(userId, options) {
const serializedOptions = options ? serializeListUserApiKeysOptions(options) : void 0;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/api_keys`, deserializeUserApiKey, serializedOptions), (params) => fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/api_keys`, deserializeUserApiKey, params), serializedOptions);
}
/**
* Create an API key for a user
*
* Create a new API key owned by a user. The user must have an active membership in the specified organization.
* @param userId - Unique identifier of the user.
* @param options - Object containing the API key properties.
* @returns {Promise<UserApiKeyWithValue>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createUserApiKey(userId, options, requestOptions = {}) {
const { data } = await this.workos.post(`/user_management/users/${encodePathParameter(userId)}/api_keys`, serializeCreateUserApiKeyOptions(options), requestOptions);
return deserializeUserApiKeyWithValue(data);
}
/**
* Get user identities
*
* Get a list of identities associated with the user. A user can have multiple associated identities after going through [identity linking](https://workos.com/docs/authkit/identity-linking). Currently only OAuth identities are supported. More provider types may be added in the future.
* @returns {Promise<Identity[]>}
* @throws {NotFoundException} 404
*/
async getUserIdentities(userId) {
if (!userId) throw new TypeError(`Incomplete arguments. Need to specify 'userId'.`);
const { data } = await this.workos.get(`/user_management/users/${encodePathParameter(userId)}/identities`);
return deserializeIdentities(data);
}
/**
* Get an organization membership
*
* Get the details of an existing organization membership.
* @returns {Promise<OrganizationMembership>}
* @throws {NotFoundException} 404
*/
async getOrganizationMembership(organizationMembershipId) {
const { data } = await this.workos.get(`/user_management/organization_memberships/${encodePathParameter(organizationMembershipId)}`);
return deserializeOrganizationMembership(data);
}
/**
* List organization memberships
*
* Get a list of all organization memberships matching the criteria specified. At least one of `user_id` or `organization_id` must be provided. By default only active memberships are returned. Use the `statuses` parameter to filter by other statuses.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<OrganizationMembership, SerializedListOrganizationMembershipsOptions>>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listOrganizationMemberships(options) {
const serializedOptions = serializeListOrganizationMembershipsOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/user_management/organization_memberships", deserializeOrganizationMembership, serializedOptions), (params) => fetchAndDeserialize(this.workos, "/user_management/organization_memberships", deserializeOrganizationMembership, params), serializedOptions);
}
/**
* Create an organization membership
*
* Creates a new `active` organization membership for the given organization and user.
*
* Calling this API with an organization and user that match an `inactive` organization membership will activate the membership with the specified role(s).
* @param options - Object containing userId, organizationId.
* @returns {Promise<OrganizationMembership>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createOrganizationMembership(options) {
const { data } = await this.workos.post("/user_management/organization_memberships", serializeCreateOrganizationMembershipOptions(options));
return deserializeOrganizationMembership(data);
}
/**
* Update an organization membership
*
* Update the details of an existing organization membership.
* @param options - The request body.
* @returns {Promise<OrganizationMembership>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updateOrganizationMembership(organizationMembershipId, options) {
const { data } = await this.workos.put(`/user_management/organization_memberships/${encodePathParameter(organizationMembershipId)}`, serializeUpdateOrganizationMembershipOptions(options));
return deserializeOrganizationMembership(data);
}
/**
* Delete an organization membership
*
* Permanently deletes an existing organization membership. It cannot be undone.
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteOrganizationMembership(organizationMembershipId) {
await this.workos.delete(`/user_management/organization_memberships/${encodePathParameter(organizationMembershipId)}`);
}
/**
* Deactivate an organization membership
*
* Deactivates an `active` organization membership. Emits an [organization_membership.updated](https://workos.com/docs/events/organization-membership) event upon successful deactivation.
*
* - Deactivating an `inactive` membership is a no-op and does not emit an event.
* - Deactivating a `pending` membership returns an error. This membership should be [deleted](https://workos.com/docs/reference/authkit/organization-membership/delete) instead.
*
* See the [membership management documentation](https://workos.com/docs/authkit/users-organizations/organizations/membership-management) for additional details.
* @returns {Promise<OrganizationMembership>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async deactivateOrganizationMembership(organizationMembershipId) {
const { data } = await this.workos.put(`/user_management/organization_memberships/${encodePathParameter(organizationMembershipId)}/deactivate`, {});
return deserializeOrganizationMembership(data);
}
/**
* Reactivate an organization membership
*
* Reactivates an `inactive` organization membership, retaining the pre-existing role(s). Emits an [organization_membership.updated](https://workos.com/docs/events/organization-membership) event upon successful reactivation.
*
* - Reactivating an `active` membership is a no-op and does not emit an event.
* - Reactivating a `pending` membership returns an error. The user needs to [accept the invitation](https://workos.com/docs/authkit/invitations) instead.
*
* See the [membership management documentation](https://workos.com/docs/authkit/users-organizations/organizations/membership-management) for additional details.
* @returns {Promise<OrganizationMembership>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async reactivateOrganizationMembership(organizationMembershipId) {
const { data } = await this.workos.put(`/user_management/organization_memberships/${encodePathParameter(organizationMembershipId)}/reactivate`, {});
return deserializeOrganizationMembership(data);
}
async listGroupsForOrganizationMembership(options) {
const { organizationMembershipId, ...paginationOptions } = options;
const endpoint = `/user_management/organization_memberships/${encodePathParameter(organizationMembershipId)}/groups`;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeGroup, paginationOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeGroup, params), paginationOptions);
}
async getInvitation(invitationId) {
const { data } = await this.workos.get(`/user_management/invitations/${encodePathParameter(invitationId)}`);
return deserializeInvitation(data);
}
/**
* Find an invitation by token
*
* Retrieve an existing invitation using the token.
* @returns {Promise<Invitation>}
* @throws {NotFoundException} 404
*/
async findInvitationByToken(invitationToken) {
const { data } = await this.workos.get(`/user_management/invitations/by_token/${encodePathParameter(invitationToken)}`);
return deserializeInvitation(data);
}
/**
* List invitations
*
* Get a list of all of invitations matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Invitation, SerializedListInvitationsOptions>>}
* @throws {UnprocessableEntityException} 422
*/
async listInvitations(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/user_management/invitations", deserializeInvitation, options ? serializeListInvitationsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/user_management/invitations", deserializeInvitation, params), options ? serializeListInvitationsOptions(options) : void 0);
}
/**
* Send an invitation
*
* Sends an invitation email to the recipient.
* @param payload - Object containing email.
* @returns {Promise<Invitation>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async sendInvitation(payload) {
const { data } = await this.workos.post("/user_management/invitations", serializeSendInvitationOptions({ ...payload }));
return deserializeInvitation(data);
}
/**
* Accept an invitation
*
* Accepts an invitation and, if linked to an organization, activates the user's membership in that organization.
* @returns {Promise<Invitation>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async acceptInvitation(invitationId) {
const { data } = await this.workos.post(`/user_management/invitations/${encodePathParameter(invitationId)}/accept`, null);
return deserializeInvitation(data);
}
/**
* Revoke an invitation
*
* Revokes an existing invitation.
* @returns {Promise<Invitation>}
* @throws {BadRequestException} 400
*/
async revokeInvitation(invitationId) {
const { data } = await this.workos.post(`/user_management/invitations/${encodePathParameter(invitationId)}/revoke`, null);
return deserializeInvitation(data);
}
/**
* Resend an invitation
*
* Resends an invitation email to the recipient. The invitation must be in a pending state.
* @param options - The request body.
* @returns {Promise<Invitation>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async resendInvitation(invitationId, options) {
const { data } = await this.workos.post(`/user_management/invitations/${encodePathParameter(invitationId)}/resend`, options ? serializeResendInvitationOptions(options) : {});
return deserializeInvitation(data);
}
/**
* List waitlists
*
* Get a list of the waitlists in the environment. All waitlists are
* returned in a single response — this endpoint is not paginated.
* @returns {Promise<List<Waitlist>>}
*/
async listWaitlists() {
const { data } = await this.workos.get("/user_management/waitlists");
return deserializeList(data, deserializeWaitlist);
}
/**
* Get a waitlist
*
* Get the details of an existing waitlist. The literal id `default`
* is accepted and resolves to the environment's default waitlist.
* @returns {Promise<Waitlist>}
* @throws {NotFoundException} 404
*/
async getWaitlist(waitlistId) {
const { data } = await this.workos.get(`/user_management/waitlists/${encodePathParameter(waitlistId)}`);
return deserializeWaitlist(data);
}
/**
* List waitlist entries
*
* Get a list of the entries on a waitlist matching the criteria specified.
* The literal id `default` is accepted and resolves to the environment's
* default waitlist.
* @param waitlistId - The unique ID of the waitlist.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<WaitlistEntry, SerializedListWaitlistEntriesOptions>>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listWaitlistEntries(waitlistId, options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/user_management/waitlists/${encodePathParameter(waitlistId)}/entries`, deserializeWaitlistEntry, options ? serializeListWaitlistEntriesOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, `/user_management/waitlists/${encodePathParameter(waitlistId)}/entries`, deserializeWaitlistEntry, params), options ? serializeListWaitlistEntriesOptions(options) : void 0);
}
/**
* Create a waitlist entry
*
* Add an email address to a waitlist. Adding an email address that is
* already on the waitlist returns the existing entry unchanged. The
* literal id `default` is accepted and resolves to the environment's
* default waitlist.
* @param waitlistId - The unique ID of the waitlist.
* @param payload - Object containing email and optional fields.
* @returns {Promise<WaitlistEntry>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createWaitlistEntry(waitlistId, payload) {
const { data } = await this.workos.post(`/user_management/waitlists/${encodePathParameter(waitlistId)}/entries`, serializeCreateWaitlistEntryOptions(payload));
return deserializeWaitlistEntry(data);
}
/**
* Approve a waitlist entry
*
* Approve a waitlist entry, create an invitation for its email address,
* and send the invitation email.
* @returns {Promise<WaitlistEntry>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async approveWaitlistEntry(waitlistEntryId) {
const { data } = await this.workos.post(`/user_management/waitlist_entries/${encodePathParameter(waitlistEntryId)}/approve`, null);
return deserializeWaitlistEntry(data);
}
/**
* Deny a waitlist entry
*
* Deny a pending waitlist entry.
* @returns {Promise<WaitlistEntry>}
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async denyWaitlistEntry(waitlistEntryId) {
const { data } = await this.workos.post(`/user_management/waitlist_entries/${encodePathParameter(waitlistEntryId)}/deny`, null);
return deserializeWaitlistEntry(data);
}
/**
* Delete a waitlist entry
*
* Remove the entry from the waitlist. Its email address can join again
* unless a user with that email now exists in the environment. Deleting
* the entry does not revoke an invitation created by approving it.
* @returns {Promise<void>}
* @throws {NotFoundException} 404
*/
async deleteWaitlistEntry(waitlistEntryId) {
await this.workos.delete(`/user_management/waitlist_entries/${encodePathParameter(waitlistEntryId)}`);
}
/**
* Revoke Session
*
* Revoke a [user session](https://workos.com/docs/reference/authkit/session).
* @param payload - Object containing sessionId.
* @returns {Promise<void>}
* @throws {BadRequestException} 400
*/
async revokeSession(payload) {
await this.workos.post("/user_management/sessions/revoke", serializeRevokeSessionOptions(payload));
}
/**
* Generate an OAuth 2.0 authorization URL.
*
* For public clients (browser, mobile, CLI), include PKCE parameters:
* - Generate PKCE using workos.pkce.generate()
* - Pass codeChallenge and codeChallengeMethod here
* - Store codeVerifier and pass to authenticateWithCode() later
*
* Or use getAuthorizationUrlWithPKCE() which handles PKCE automatically.
*/
getAuthorizationUrl(options) {
const { claimNonce, connectionId, codeChallenge, codeChallengeMethod, clientId, domainHint, invitationToken, loginHint, maxAge, organizationId, provider, providerQueryParams, providerScopes, prompt, redirectUri, state, screenHint } = options;
const resolvedClientId = this.resolveClientId(clientId);
if (!provider && !connectionId && !organizationId) throw new TypeError(`Incomplete arguments. Need to specify either a 'connectionId', 'organizationId', or 'provider'.`);
if (provider !== "authkit" && screenHint) throw new TypeError(`'screenHint' is only supported for 'authkit' provider`);
const query = toQueryString({
claim_nonce: claimNonce,
connection_id: connectionId,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
organization_id: organizationId,
domain_hint: domainHint,
invitation_token: invitationToken,
login_hint: loginHint,
max_age: maxAge?.toString(),
provider,
provider_query_params: providerQueryParams,
provider_scopes: providerScopes,
prompt,
client_id: resolvedClientId,
redirect_uri: redirectUri,
response_type: "code",
state,
screen_hint: screenHint
});
return `${this.workos.baseURL}/user_management/authorize?${query}`;
}
/**
* Generate an OAuth 2.0 authorization URL with automatic PKCE.
*
* This method generates PKCE parameters internally and returns them along with
* the authorization URL. Use this for public clients (CLI apps, Electron, mobile)
* that cannot securely store a client secret.
*
* @returns Object containing url, state, and codeVerifier
*
* @example
* ```typescript
* const { url, state, codeVerifier } = await workos.userManagement.getAuthorizationUrlWithPKCE({
* provider: 'authkit',
* clientId: 'client_123',
* redirectUri: 'myapp://callback',
* });
*
* // Store state and codeVerifier securely, then redirect user to url
* // After callback, exchange the code:
* const response = await workos.userManagement.authenticateWithCode({
* code: authorizationCode,
* codeVerifier,
* clientId: 'client_123',
* });
* ```
*/
async getAuthorizationUrlWithPKCE(options) {
const { clientId, connectionId, domainHint, loginHint, maxAge, organizationId, provider, providerQueryParams, providerScopes, prompt, redirectUri, screenHint } = options;
const resolvedClientId = this.resolveClientId(clientId);
if (!provider && !connectionId && !organizationId) throw new TypeError(`Incomplete arguments. Need to specify either a 'connectionId', 'organizationId', or 'provider'.`);
if (provider !== "authkit" && screenHint) throw new TypeError(`'screenHint' is only supported for 'authkit' provider`);
const pkce = await this.workos.pkce.generate();
const state = this.workos.pkce.generateCodeVerifier(43);
const query = toQueryString({
connection_id: connectionId,
code_challenge: pkce.codeChallenge,
code_challenge_method: "S256",
organization_id: organizationId,
domain_hint: domainHint,
login_hint: loginHint,
max_age: maxAge?.toString(),
provider,
provider_query_params: providerQueryParams,
provider_scopes: providerScopes,
prompt,
client_id: resolvedClientId,
redirect_uri: redirectUri,
response_type: "code",
state,
screen_hint: screenHint
});
return {
url: `${this.workos.baseURL}/user_management/authorize?${query}`,
state,
codeVerifier: pkce.codeVerifier
};
}
/**
* Logout
*
* Logout a user from the current [session](https://workos.com/docs/reference/authkit/session).
* @param options.sessionId - The ID of the session to revoke. This can be extracted from the `sid` claim of the access token.
*
* @example
* "session_01H93ZY4F80QPBEZ1R5B2SHQG8"
*
* @param options.returnTo - The URL to redirect the user to after session revocation.
*
* @example
* "https://example.com"
*
* @returns {string}
* @throws {UnprocessableEntityException} 422
*/
getLogoutUrl(options) {
const { sessionId, returnTo } = options;
if (!sessionId) throw new TypeError(`Incomplete arguments. Need to specify 'sessionId'.`);
const url = new URL("/user_management/sessions/logout", this.workos.baseURL);
url.searchParams.set("session_id", sessionId);
if (returnTo) url.searchParams.set("return_to", returnTo);
return url.toString();
}
getJwksUrl(clientId) {
if (!clientId) throw new TypeError("clientId must be a valid clientId");
return `${this.workos.baseURL}/sso/jwks/${clientId}`;
}
};
// src/feature-flags/create-rule-with-targets-error.ts
/** A rule was created, but adding one of its targets failed. */
var CreateRuleWithTargetsError = class extends Error {
rule;
targets;
failedTargetId;
name = "CreateRuleWithTargetsError";
constructor(rule, targets, failedTargetId, cause) {
super("The rule was created, but adding a target failed.", { cause });
this.rule = rule;
this.targets = targets;
this.failedTargetId = failedTargetId;
}
};
// src/feature-flags/event-emitter.ts
/**
* Minimal, runtime-agnostic, typed event emitter.
*
* Replaces eventemitter3 so the SDK carries no event dependency and works in
* edge runtimes where `node:events` is not available. Generic over an event
* map (`{ eventName: [arg1, arg2, ...] }`) for compile-time-checked event
* names and payloads.
*
* Unlike eventemitter3, an unhandled `'error'` event throws instead of being
* silently dropped — matching Node's `EventEmitter` so failures are never
* swallowed.
*/
var EventEmitter = class {
handlers = /* @__PURE__ */ new Map();
on(event, fn) {
return this.add(event, fn, false);
}
once(event, fn) {
return this.add(event, fn, true);
}
off(event, fn) {
this.remove(event, (h) => h.fn !== fn);
return this;
}
emit(event, ...args) {
const list = this.handlers.get(event);
if (!list || list.length === 0) {
if (event === "error") throw args[0] instanceof Error ? args[0] : new Error(String(args[0]));
return false;
}
for (const h of [...list]) {
if (h.once) this.remove(event, (existing) => existing !== h);
h.fn(...args);
}
return true;
}
listenerCount(event) {
return this.handlers.get(event)?.length ?? 0;
}
removeAllListeners(event) {
if (event === void 0) this.handlers.clear();
else this.handlers.delete(event);
return this;
}
addListener(event, fn) {
return this.on(event, fn);
}
removeListener(event, fn) {
return this.off(event, fn);
}
listeners(event) {
return (this.handlers.get(event) ?? []).map((h) => h.fn);
}
eventNames() {
return [...this.handlers.keys()];
}
add(event, fn, once) {
const list = this.handlers.get(event) ?? [];
list.push({
fn,
once
});
this.handlers.set(event, list);
return this;
}
remove(event, keep) {
const list = this.handlers.get(event);
if (!list) return;
const next = list.filter(keep);
if (next.length) this.handlers.set(event, next);
else this.handlers.delete(event);
}
};
// src/feature-flags/in-memory-store.ts
var InMemoryStore = class {
flags = {};
swap(newFlags) {
this.flags = { ...newFlags };
}
get(slug) {
return Object.hasOwn(this.flags, slug) ? this.flags[slug] : void 0;
}
getAll() {
return { ...this.flags };
}
get size() {
return Object.keys(this.flags).length;
}
};
// src/feature-flags/evaluator.ts
const TARGET_TYPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
const TARGET_ID_PATTERN = /^[A-Za-z0-9._:-]{1,255}$/;
const LEGACY_KEY_TO_TARGET_TYPE = /* @__PURE__ */ new Map([["userId", "user"], ["organizationId", "organization"]]);
const isEvaluationResource = (value) => typeof value === "object" && value !== null && "id" in value && typeof value.id === "string";
var Evaluator = class {
store;
logger;
constructor(store, logger) {
this.store = store;
this.logger = logger;
}
isEnabled(flagKey, context = {}, defaultValue = false) {
return this.evaluate(this.store.get(flagKey), this.normalizeContext(context), defaultValue);
}
getAllFlags(context = {}) {
const normalizedContext = this.normalizeContext(context);
const flags = this.store.getAll();
return Object.fromEntries(Object.entries(flags).map(([slug, flag]) => [slug, this.evaluate(flag, normalizedContext, false)]));
}
evaluate(entry, normalizedContext, defaultValue) {
if (!entry) return defaultValue;
if (!entry.enabled) return this.servedValue(entry.off_value, defaultValue);
for (const rule of entry.rules) {
if (rule.kind !== "conditions" || !rule.conditions?.length) continue;
if (rule.conditions.every((condition) => {
if (condition.operator !== "one_of" || !condition.target_type || !Array.isArray(condition.values)) return false;
const id = normalizedContext.get(condition.target_type);
return id !== void 0 && condition.values.includes(id);
})) return this.servedValue(rule.value, defaultValue);
}
return this.servedValue(entry.default_value, defaultValue);
}
servedValue(value, defaultValue) {
return typeof value === "boolean" ? value : defaultValue;
}
/**
* Reduces either context form to target type → ID pairs. Evaluation must
* never throw in application code, so every invalid piece of context
* degrades to "matches no targets" with a logged warning instead of an
* error.
*/
normalizeContext(context) {
const normalized = /* @__PURE__ */ new Map();
if (typeof context !== "object" || context === null || Array.isArray(context)) {
this.logger?.warn("Ignoring invalid evaluation context");
return normalized;
}
const record = context;
const legacyEntries = [];
const typedKeys = [];
for (const [key, value] of Object.entries(record)) {
if (value === void 0 || value === null) continue;
const legacyTargetType = LEGACY_KEY_TO_TARGET_TYPE.get(key);
if (legacyTargetType) {
if (typeof value === "string" && value !== "") legacyEntries.push([legacyTargetType, value]);
continue;
}
typedKeys.push(key);
}
const resourceShapedKeys = typedKeys.filter((key) => typeof record[key] === "object");
if (legacyEntries.length > 0 && resourceShapedKeys.length > 0) {
this.logger?.warn("Evaluation context mixes legacy keys (userId/organizationId) with typed target keys; no targets will match", { keys: Object.keys(record) });
return normalized;
}
if (legacyEntries.length > 0) {
for (const [targetType, targetId] of legacyEntries) normalized.set(targetType, targetId);
return normalized;
}
for (const key of typedKeys) {
if (!TARGET_TYPE_PATTERN.test(key)) {
this.logger?.warn(`Ignoring invalid target type in evaluation context: ${key}`);
continue;
}
const value = record[key];
if (!isEvaluationResource(value)) {
this.logger?.warn(`Ignoring target type with a missing or invalid resource id in evaluation context: ${key}`);
continue;
}
const { id } = value;
if (!TARGET_ID_PATTERN.test(id) || id === "." || id === "..") {
this.logger?.warn(`Ignoring invalid target id in evaluation context for type: ${key}`);
continue;
}
normalized.set(key, id);
}
return normalized;
}
};
// src/feature-flags/payload.ts
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isCondition(value) {
return isRecord(value) && typeof value.operator === "string" && (value.target_type === void 0 || typeof value.target_type === "string") && (value.operator !== "one_of" || Array.isArray(value.values));
}
function isRule(value) {
return isRecord(value) && typeof value.id === "string" && typeof value.kind === "string" && (value.conditions === void 0 || Array.isArray(value.conditions) && value.conditions.every(isCondition));
}
function isEntry(value) {
return isRecord(value) && typeof value.slug === "string" && typeof value.enabled === "boolean" && "default_value" in value && "off_value" in value && Array.isArray(value.rules) && value.rules.every(isRule);
}
/** Validate a payload before swapping the store. One invalid entry rejects the
* whole payload, so the store never holds a partial snapshot and the last good
* one stays intact; bootstrap callers can still be ready. */
function parseFlagPollResponse(response) {
if (!isRecord(response) || response.version !== 2 || !isRecord(response.flags)) return;
const entries = [];
for (const [slug, entry] of Object.entries(response.flags)) {
if (!isEntry(entry)) return void 0;
entries.push([slug, entry]);
}
return {
version: 2,
flags: Object.fromEntries(entries)
};
}
// src/feature-flags/runtime-client.ts
const DEFAULT_POLLING_INTERVAL_MS = 3e4;
const MIN_POLLING_INTERVAL_MS = 5e3;
const MIN_DELAY_MS = 1e3;
const DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
const JITTER_FACTOR = .1;
const INITIAL_RETRY_MS = 1e3;
const MAX_RETRY_MS = 6e4;
const BACKOFF_MULTIPLIER = 2;
var FeatureFlagsRuntimeClient = class extends EventEmitter {
workos;
store;
evaluator;
pollingIntervalMs;
requestTimeoutMs;
logger;
closed = false;
initialized = false;
consecutiveErrors = 0;
warnedUnobservedError = false;
pollTimer = null;
pollAbortController = null;
readyResolve = null;
readyReject = null;
readyPromise;
stats = {
pollCount: 0,
pollErrorCount: 0,
lastPollAt: null,
lastSuccessfulPollAt: null,
cacheAge: null,
flagCount: 0
};
constructor(workos, options = {}) {
super();
this.workos = workos;
this.pollingIntervalMs = Math.max(MIN_POLLING_INTERVAL_MS, options.pollingIntervalMs ?? DEFAULT_POLLING_INTERVAL_MS);
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
this.logger = options.logger;
this.store = new InMemoryStore();
this.evaluator = new Evaluator(this.store, this.logger);
this.readyPromise = new Promise((resolve, reject) => {
this.readyResolve = resolve;
this.readyReject = reject;
});
this.readyPromise.catch(() => {});
if (options.bootstrapFlags !== void 0) {
const bootstrap = parseFlagPollResponse(options.bootstrapFlags);
if (bootstrap) this.store.swap(bootstrap.flags);
else this.logger?.warn("Ignoring bootstrapFlags: expected a v2 flag payload ({ version: 2, flags }). Flags will load on the first successful poll.");
this.stats.flagCount = this.store.size;
this.resolveReady();
}
setTimeout(() => this.poll(), 0);
}
async waitUntilReady(options) {
if (!options?.timeoutMs) return this.readyPromise;
let timeoutId;
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error("waitUntilReady timed out")), options.timeoutMs);
});
timeoutPromise.catch(() => {});
return Promise.race([this.readyPromise, timeoutPromise]).finally(() => {
clearTimeout(timeoutId);
});
}
close() {
this.closed = true;
this.pollAbortController?.abort();
if (this.pollTimer) {
clearTimeout(this.pollTimer);
this.pollTimer = null;
}
this.removeAllListeners();
}
isEnabled(flagKey, context, defaultValue) {
return this.evaluator.isEnabled(flagKey, context, defaultValue);
}
getAllFlags(context) {
return this.evaluator.getAllFlags(context);
}
getFlag(flagKey) {
return this.store.get(flagKey);
}
getStats() {
return {
...this.stats,
cacheAge: this.stats.lastSuccessfulPollAt ? Date.now() - this.stats.lastSuccessfulPollAt.getTime() : null
};
}
resolveReady() {
if (this.readyResolve) {
this.readyResolve();
this.readyResolve = null;
}
}
async poll() {
if (this.closed) return;
const previousFlags = this.store.getAll();
try {
this.stats.pollCount++;
this.stats.lastPollAt = /* @__PURE__ */ new Date();
const data = parseFlagPollResponse(await this.fetchWithTimeout());
if (!data) throw new Error("Feature flag poll returned a payload this SDK can't read; keeping the last good flags");
this.store.swap(data.flags);
this.stats.lastSuccessfulPollAt = /* @__PURE__ */ new Date();
this.stats.flagCount = this.store.size;
this.consecutiveErrors = 0;
if (this.initialized) this.emitChanges(previousFlags, data.flags);
this.initialized = true;
this.resolveReady();
this.logger?.debug("Poll successful", { flagCount: this.store.size });
} catch (error) {
if (this.closed) return;
const err = error instanceof Error ? error : new Error(String(error));
this.consecutiveErrors++;
this.stats.pollErrorCount++;
if (this.listenerCount("error") > 0) this.emit("error", err);
else if (!this.logger) {
if (err instanceof UnauthorizedException) this.workos.emitWarning(`Feature flag sync stopped after a 401 and no 'error' listener or logger is attached; keeping the last good flags. Recreate the client with a valid API key to resume. ${err.message}`);
else if (!this.warnedUnobservedError) {
this.warnedUnobservedError = true;
this.workos.emitWarning(`Feature flag sync failed and no 'error' listener or logger is attached; keeping the last good flags and retrying. ${err.message}`);
}
}
this.logger?.error("Poll failed", err);
if (err instanceof UnauthorizedException) {
this.emit("failed", err);
if (!this.initialized && this.readyReject) {
this.readyReject(err);
this.readyReject = null;
}
return;
}
}
this.scheduleNextPoll();
}
async fetchWithTimeout() {
this.pollAbortController = new AbortController();
const { signal } = this.pollAbortController;
const timeoutId = setTimeout(() => {
this.pollAbortController?.abort(/* @__PURE__ */ new Error("Request timed out"));
}, this.requestTimeoutMs);
const fetchPromise = this.workos.get("/sdk/feature-flags?payload_version=2", { signal }).then(({ data }) => data);
const abortPromise = new Promise((_, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
});
return Promise.race([fetchPromise, abortPromise]).finally(() => {
clearTimeout(timeoutId);
});
}
scheduleNextPoll() {
if (this.closed) return;
let baseDelay = this.pollingIntervalMs;
if (this.consecutiveErrors > 0) {
const backoff = Math.min(INITIAL_RETRY_MS * Math.pow(BACKOFF_MULTIPLIER, this.consecutiveErrors - 1), MAX_RETRY_MS);
baseDelay = Math.max(baseDelay, backoff);
}
const jitter = 1 + (Math.random() * 2 - 1) * JITTER_FACTOR;
const delay = Math.max(MIN_DELAY_MS, baseDelay * jitter);
this.pollTimer = setTimeout(() => this.poll(), delay);
}
emitChanges(previous, current) {
if (!previous || !current) return;
const allKeys = /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(current)]);
for (const key of allKeys) {
const prev = Object.hasOwn(previous, key) ? previous[key] : void 0;
const curr = Object.hasOwn(current, key) ? current[key] : void 0;
if (this.hasEntryChanged(prev, curr)) this.emit("change", {
key,
previous: prev ?? null,
current: curr ?? null
});
}
}
hasEntryChanged(a, b) {
if (!a || !b) return a !== b;
const signature = (entry) => JSON.stringify([
entry.enabled,
entry.default_value,
entry.off_value,
entry.rules.map((rule) => [
rule.id,
rule.kind,
rule.value,
rule.conditions?.map((condition) => JSON.stringify([
condition.operator,
condition.target_type,
Array.isArray(condition.values) ? [...new Set(condition.values)].sort() : condition.values
])).sort()
])
]);
return signature(a) !== signature(b);
}
};
// src/feature-flags/feature-flags.ts
var FeatureFlags = class {
workos;
constructor(workos) {
this.workos = workos;
}
/** Append an empty rule to a flag. Duplicate target type/value pairs return 409. */
async createFlagRule(options) {
const { data } = await this.workos.post("/flag_rules", {
flag_slug: options.flagSlug,
target_type: options.targetType,
value: options.value
});
return deserializeFlagRule(data);
}
/** List a flag's rules in evaluation order. */
async listFlagRules(options) {
const fetchPage = async ({ limit, before, after }) => {
const { data } = await this.workos.get("/flag_rules", { query: {
flag_slug: options.flagSlug,
limit,
before,
after
} });
return deserializeList(data, deserializeFlagRule);
};
return new AutoPaginatable(await fetchPage(options), fetchPage, options);
}
/** Get a rule in the current environment. */
async getFlagRule(id) {
const { data } = await this.workos.get(`/flag_rules/${encodePathParameter(id)}`);
return deserializeFlagRule(data);
}
/** Delete a rule and all its target memberships. */
async deleteFlagRule(id) {
await this.workos.delete(`/flag_rules/${encodePathParameter(id)}`);
}
/** Add a membership to a rule. The rule supplies the target type and value. */
async createFlagTarget(options) {
const { data } = await this.workos.post("/flag_targets", {
rule_id: options.ruleId,
target_id: options.targetId
});
return deserializeFlagTarget(data);
}
/** Get a membership, or a legacy target while the compatibility contract is enabled. */
async getFlagTarget(id) {
const { data } = await this.workos.get(`/flag_targets/${encodePathParameter(id)}`);
return deserializeFlagTargetResource(data);
}
/** List targets with combined filters; the team's contract selects their shape. */
async listFlagTargets(options = {}) {
const fetchPage = async ({ limit, before, after }) => {
const { data } = await this.workos.get("/flag_targets", { query: {
rule_id: options.ruleId,
flag_slug: options.flagSlug,
target_type: options.targetType,
target_id: options.targetId,
order: options.order ?? "desc",
limit,
before,
after
} });
return deserializeList(data, deserializeFlagTargetResource);
};
return new AutoPaginatable(await fetchPage(options), fetchPage, options);
}
/** Delete a membership by its flag_target ID, not the targeted entity's ID. */
async deleteFlagTarget(id) {
await this.workos.delete(`/flag_targets/${encodePathParameter(id)}`);
}
/**
* Create a rule, then add its targets sequentially in input order.
* This is not atomic: on failure, the rule and completed memberships remain.
* A CreateRuleWithTargetsError exposes the rule, confirmed targets, failed
* target ID, and original error. No later targets are attempted.
*/
async createRuleWithTargets(options) {
const rule = await this.createFlagRule(options);
const targets = [];
for (const targetId of options.targetIds) try {
targets.push(await this.createFlagTarget({
ruleId: rule.id,
targetId
}));
} catch (cause) {
throw new CreateRuleWithTargetsError(rule, targets, targetId, cause);
}
return {
rule,
targets
};
}
/**
* List feature flags
*
* Get a list of all of your existing feature flags matching the criteria specified.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<FeatureFlag>>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listFeatureFlags(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/feature-flags", deserializeFeatureFlag, options), (params) => fetchAndDeserialize(this.workos, "/feature-flags", deserializeFeatureFlag, params), options);
}
/**
* Get a feature flag
*
* Get the details of an existing feature flag by its slug.
* @param slug - A unique key to reference the Feature Flag.
*
* @example
* "advanced-analytics"
*
* @returns {Promise<FeatureFlag>}
* @throws {NotFoundException} 404
*/
async getFeatureFlag(slug) {
const { data } = await this.workos.get(`/feature-flags/${encodePathParameter(slug)}`);
return deserializeFeatureFlag(data);
}
/**
* Enable a feature flag
*
* Enables a feature flag in the current environment.
* @param slug - A unique key to reference the Feature Flag.
*
* @example
* "advanced-analytics"
*
* @returns {Promise<FeatureFlag>}
* @throws {NotFoundException} 404
*/
async enableFeatureFlag(slug) {
const { data } = await this.workos.put(`/feature-flags/${encodePathParameter(slug)}/enable`, {});
return deserializeFeatureFlag(data);
}
/**
* Disable a feature flag
*
* Disables a feature flag in the current environment.
* @param slug - A unique key to reference the Feature Flag.
*
* @example
* "advanced-analytics"
*
* @returns {Promise<FeatureFlag>}
* @throws {NotFoundException} 404
*/
async disableFeatureFlag(slug) {
const { data } = await this.workos.put(`/feature-flags/${encodePathParameter(slug)}/disable`, {});
return deserializeFeatureFlag(data);
}
/**
* Add a feature flag target
*
* @deprecated For rule-based targeting, use createFlagRule and createFlagTarget.
* This compatibility helper remains supported.
*
* Enables a feature flag for a specific target in the current environment. Currently, supported targets include users and organizations.
* @params options - Object containing slug and targetId.
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async addFlagTarget(options) {
const { slug, targetId } = options;
await this.workos.post(`/feature-flags/${encodePathParameter(slug)}/targets/${encodePathParameter(targetId)}`, {});
}
/**
* Remove a feature flag target
*
* @deprecated For rule-based targeting, use deleteFlagTarget with a membership ID.
* This compatibility helper remains supported.
*
* Removes a target from the feature flag's target list in the current environment. Currently, supported targets include users and organizations.
* @params options - Object containing slug and targetId.
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async removeFlagTarget(options) {
const { slug, targetId } = options;
await this.workos.delete(`/feature-flags/${encodePathParameter(slug)}/targets/${encodePathParameter(targetId)}`);
}
/**
* List enabled feature flags for an organization
*
* Get a list of all enabled feature flags for an organization.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<FeatureFlag>>}
* @throws {NotFoundException} 404
*/
async listOrganizationFeatureFlags(options) {
const { organizationId, ...paginationOptions } = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/organizations/${encodePathParameter(organizationId)}/feature-flags`, deserializeFeatureFlag, paginationOptions), (params) => fetchAndDeserialize(this.workos, `/organizations/${encodePathParameter(organizationId)}/feature-flags`, deserializeFeatureFlag, params), paginationOptions);
}
/**
* List enabled feature flags for a user
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Flag>>}
* @throws {NotFoundException} 404
*/
async listUserFeatureFlags(options) {
const { userId, ...paginationOptions } = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/feature-flags`, deserializeFeatureFlag, paginationOptions), (params) => fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/feature-flags`, deserializeFeatureFlag, params), paginationOptions);
}
createRuntimeClient(options) {
return new FeatureFlagsRuntimeClient(this.workos, options);
}
};
// src/groups/groups.ts
var Groups = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* List Group members
*
* Get a list of organization memberships in a group.
* @param options - Pagination and filter options.
* @param options.organizationId - Unique identifier of the Organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.groupId - Unique identifier of the Group.
* @example "group_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<AutoPaginatable<AuthorizationOrganizationMembership>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async listOrganizationMemberships(options) {
const { organizationId, groupId, ...paginationOptions } = options;
const endpoint = `/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(groupId)}/organization-memberships`;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationOrganizationMembership, paginationOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationOrganizationMembership, params), paginationOptions);
}
/**
* List groups
*
* Get a paginated list of groups within an organization.
* @param options - Pagination and filter options.
* @param options.organizationId - The ID of the organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @returns {Promise<AutoPaginatable<Group, PaginationOptions>>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async listGroups(options) {
const { organizationId, ...paginationOptions } = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/organizations/${encodeURIComponent(organizationId)}/groups`, deserializeGroup, paginationOptions), (params) => fetchAndDeserialize(this.workos, `/organizations/${encodeURIComponent(organizationId)}/groups`, deserializeGroup, params), paginationOptions);
}
/**
* Create a group
*
* Create a new group within an organization.
* @param options - Object containing name.
* @param options.organizationId - The ID of the organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.name - The name of the Group.
* @example "Engineering"
* @param options.description - An optional description of the Group.
* @example "The engineering team"
* @returns {Promise<Group>}
* @throws {BadRequestException} 400
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createGroup(options) {
const { organizationId, ...payload } = options;
const { data } = await this.workos.post(`/organizations/${encodeURIComponent(organizationId)}/groups`, serializeCreateGroup(payload));
return deserializeGroup(data);
}
/**
* Get a group
*
* Retrieve a group by its ID within an organization.
* @param options - The request options.
* @param options.organizationId - The ID of the organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.groupId - The ID of the group.
* @example "group_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<Group>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async getGroup(options) {
const { organizationId, groupId } = options;
const { data } = await this.workos.get(`/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(groupId)}`);
return deserializeGroup(data);
}
/**
* Update a group
*
* Update an existing group. Only the fields provided in the request body will be updated.
* @param options - The request body.
* @param options.organizationId - The ID of the organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.groupId - The ID of the group.
* @example "group_01HXYZ123456789ABCDEFGHIJ"
* @param options.name - The name of the Group.
* @example "Engineering"
* @param options.description - An optional description of the Group.
* @example "The engineering team"
* @returns {Promise<Group>}
* @throws {BadRequestException} 400
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updateGroup(options) {
const { organizationId, groupId, ...payload } = options;
const { data } = await this.workos.patch(`/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(groupId)}`, serializeUpdateGroup(payload));
return deserializeGroup(data);
}
/**
* Delete a group
*
* Delete a group from an organization.
* @param options - The request options.
* @param options.organizationId - The ID of the organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.groupId - The ID of the group.
* @example "group_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<void>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async deleteGroup(options) {
const { organizationId, groupId } = options;
await this.workos.delete(`/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(groupId)}`);
}
/**
* Add a member to a Group
*
* Add an organization membership to a group.
* @param options - Object containing organizationMembershipId.
* @param options.organizationId - Unique identifier of the Organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.groupId - Unique identifier of the Group.
* @example "group_01HXYZ123456789ABCDEFGHIJ"
* @param options.organizationMembershipId - The ID of the Organization Membership to add to the group.
* @example "om_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<Group>}
* @throws {BadRequestException} 400
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async addOrganizationMembership(options) {
const { organizationId, groupId, ...payload } = options;
const { data } = await this.workos.post(`/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(groupId)}/organization-memberships`, serializeCreateGroupMembership(payload));
return deserializeGroup(data);
}
/**
* Remove a member from a Group
*
* Remove an organization membership from a group.
* @param options - The request options.
* @param options.organizationId - Unique identifier of the Organization.
* @example "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
* @param options.groupId - Unique identifier of the Group.
* @example "group_01HXYZ123456789ABCDEFGHIJ"
* @param options.omId - Unique identifier of the Organization Membership.
* @example "om_01HXYZ123456789ABCDEFGHIJ"
* @returns {Promise<void>}
* @throws {AuthorizationException} 403
* @throws {NotFoundException} 404
*/
async removeOrganizationMembership(options) {
const { organizationId, groupId, organizationMembershipId } = options;
await this.workos.delete(`/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(groupId)}/organization-memberships/${encodeURIComponent(organizationMembershipId)}`);
}
};
// src/widgets/serializers/widget-session-token-response.serializer.ts
const deserializeWidgetSessionTokenResponse = (response) => ({ token: response.token });
// src/widgets/serializers/widget-session-token.serializer.ts
const serializeGetTokenOptions = (model) => ({
organization_id: model.organizationId,
user_id: model.userId,
scopes: model.scopes
});
// src/widgets/widgets.ts
var Widgets = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Generate a widget token
*
* Generate a widget token scoped to an organization and user with the specified scopes.
* @param options - The request options.
* @returns {Promise<WidgetSessionTokenResponse>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async createToken(options) {
const payload = options;
const { data } = await this.workos.post("/widgets/token", serializeGetTokenOptions(payload));
return deserializeWidgetSessionTokenResponse(data);
}
};
// src/authorization/serializers/environment-role.serializer.ts
const deserializeEnvironmentRole = (role) => ({
object: role.object,
id: role.id,
name: role.name,
slug: role.slug,
description: role.description,
permissions: role.permissions,
resourceTypeSlug: role.resource_type_slug,
type: role.type,
createdAt: new Date(role.created_at),
updatedAt: new Date(role.updated_at)
});
// src/authorization/serializers/create-environment-role-options.serializer.ts
const serializeCreateEnvironmentRoleOptions = (options) => ({
slug: options.slug,
name: options.name,
description: options.description,
resource_type_slug: options.resourceTypeSlug
});
// src/authorization/serializers/update-environment-role-options.serializer.ts
const serializeUpdateEnvironmentRoleOptions = (options) => ({
name: options.name,
description: options.description
});
// src/authorization/serializers/create-organization-role-options.serializer.ts
const serializeCreateOrganizationRoleOptions = (options) => ({
slug: options.slug,
name: options.name,
description: options.description,
resource_type_slug: options.resourceTypeSlug
});
// src/authorization/serializers/update-organization-role-options.serializer.ts
const serializeUpdateOrganizationRoleOptions = (options) => ({
name: options.name,
description: options.description
});
// src/authorization/serializers/create-permission-options.serializer.ts
const serializeCreatePermissionOptions = (options) => ({
slug: options.slug,
name: options.name,
description: options.description,
resource_type_slug: options.resourceTypeSlug
});
// src/authorization/serializers/update-permission-options.serializer.ts
const serializeUpdatePermissionOptions = (options) => ({
name: options.name,
description: options.description
});
// src/authorization/serializers/authorization-resource.serializer.ts
const deserializeAuthorizationResource = (resource) => ({
object: resource.object,
id: resource.id,
externalId: resource.external_id,
name: resource.name,
description: resource.description,
resourceTypeSlug: resource.resource_type_slug,
organizationId: resource.organization_id,
parentResourceId: resource.parent_resource_id,
createdAt: new Date(resource.created_at),
updatedAt: new Date(resource.updated_at)
});
// src/authorization/serializers/create-authorization-resource-options.serializer.ts
const serializeCreateResourceOptions = (options) => ({
organization_id: options.organizationId,
resource_type_slug: options.resourceTypeSlug,
external_id: options.externalId,
name: options.name,
...options.description !== void 0 && { description: options.description },
..."parentResourceId" in options && { parent_resource_id: options.parentResourceId },
..."parentResourceExternalId" in options && {
parent_resource_external_id: options.parentResourceExternalId,
parent_resource_type_slug: options.parentResourceTypeSlug
}
});
// src/authorization/serializers/update-authorization-resource-options.serializer.ts
const serializeUpdateResourceOptions = (options) => ({
...options.name !== void 0 && { name: options.name },
...options.description !== void 0 && { description: options.description }
});
// src/authorization/serializers/update-authorization-resource-by-external-id-options.serializer.ts
const serializeUpdateResourceByExternalIdOptions = (options) => ({
...options.name !== void 0 && { name: options.name },
...options.description !== void 0 && { description: options.description }
});
// src/authorization/serializers/list-authorization-resources-options.serializer.ts
const serializeListAuthorizationResourcesOptions = (options) => ({
...options.organizationId && { organization_id: options.organizationId },
...options.resourceTypeSlug && { resource_type_slug: options.resourceTypeSlug },
...options.parentResourceId && { parent_resource_id: options.parentResourceId },
...options.parentResourceTypeSlug && { parent_resource_type_slug: options.parentResourceTypeSlug },
...options.parentExternalId && { parent_external_id: options.parentExternalId },
...serializePaginationOptions(options)
});
// src/authorization/serializers/authorization-check-options.serializer.ts
const serializeAuthorizationCheckOptions = (options) => ({
permission_slug: options.permissionSlug,
..."resourceId" in options && { resource_id: options.resourceId },
..."resourceExternalId" in options && {
resource_external_id: options.resourceExternalId,
resource_type_slug: options.resourceTypeSlug
}
});
// src/authorization/serializers/list-resources-for-membership-options.serializer.ts
const serializeListResourcesForMembershipOptions = (options) => ({
permission_slug: options.permissionSlug,
...serializePaginationOptions(options),
..."parentResourceId" in options && { parent_resource_id: options.parentResourceId },
..."parentResourceExternalId" in options && {
parent_resource_type_slug: options.parentResourceTypeSlug,
parent_resource_external_id: options.parentResourceExternalId
}
});
// src/authorization/serializers/list-memberships-for-resource-options.serializer.ts
const serializeListMembershipsForResourceOptions = (options) => ({
permission_slug: options.permissionSlug,
...options.assignment && { assignment: options.assignment },
...serializePaginationOptions(options)
});
// src/authorization/serializers/role-assignment.serializer.ts
const deserializeRoleAssignment = (response) => ({
object: response.object,
id: response.id,
organizationMembershipId: response.organization_membership_id,
role: response.role,
resource: {
id: response.resource.id,
externalId: response.resource.external_id,
resourceTypeSlug: response.resource.resource_type_slug
},
source: {
type: response.source.type,
groupRoleAssignmentId: response.source.group_role_assignment_id
},
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/authorization/serializers/list-role-assignments-options.serializer.ts
const serializeListRoleAssignmentsOptions = (options) => ({
...options.resourceId && { resource_id: options.resourceId },
...options.resourceExternalId && { resource_external_id: options.resourceExternalId },
...options.resourceTypeSlug && { resource_type_slug: options.resourceTypeSlug },
...serializePaginationOptions(options)
});
// src/authorization/serializers/list-role-assignments-for-resource-options.serializer.ts
const serializeListRoleAssignmentsForResourceOptions = (options) => ({
...options.roleSlug && { role_slug: options.roleSlug },
...serializePaginationOptions(options)
});
// src/authorization/serializers/assign-role-options.serializer.ts
const serializeAssignRoleOptions = (options) => ({
role_slug: options.roleSlug,
..."resourceId" in options && { resource_id: options.resourceId },
..."resourceExternalId" in options && {
resource_external_id: options.resourceExternalId,
resource_type_slug: options.resourceTypeSlug
}
});
// src/authorization/serializers/remove-role-options.serializer.ts
const serializeRemoveRoleOptions = (options) => ({
role_slug: options.roleSlug,
..."resourceId" in options && { resource_id: options.resourceId },
..."resourceExternalId" in options && {
resource_external_id: options.resourceExternalId,
resource_type_slug: options.resourceTypeSlug
}
});
// src/authorization/serializers/group-role-assignment.serializer.ts
const deserializeGroupRoleAssignment = (response) => ({
object: response.object,
id: response.id,
groupId: response.group_id,
role: response.role,
resource: {
id: response.resource.id,
externalId: response.resource.external_id,
resourceTypeSlug: response.resource.resource_type_slug
},
createdAt: new Date(response.created_at),
updatedAt: new Date(response.updated_at)
});
// src/authorization/serializers/create-group-role-assignment-options.serializer.ts
const serializeCreateGroupRoleAssignmentOptions = (options) => ({
role_slug: options.roleSlug,
..."resourceId" in options && { resource_id: options.resourceId },
..."resourceExternalId" in options && {
resource_external_id: options.resourceExternalId,
resource_type_slug: options.resourceTypeSlug
}
});
// src/authorization/serializers/remove-group-role-assignments-options.serializer.ts
const serializeRemoveGroupRoleAssignmentsOptions = (options) => ({
role_slug: options.roleSlug,
..."resourceId" in options && { resource_id: options.resourceId },
..."resourceExternalId" in options && {
resource_external_id: options.resourceExternalId,
resource_type_slug: options.resourceTypeSlug
}
});
// src/authorization/serializers/replace-group-role-assignments-options.serializer.ts
const serializeEntry = (entry) => ({
role_slug: entry.roleSlug,
..."resourceId" in entry && { resource_id: entry.resourceId },
..."resourceExternalId" in entry && {
resource_external_id: entry.resourceExternalId,
resource_type_slug: entry.resourceTypeSlug
}
});
const serializeReplaceGroupRoleAssignmentsOptions = (options) => ({ role_assignments: options.roleAssignments.map(serializeEntry) });
// src/authorization/serializers/list-effective-permissions-options.serializer.ts
const serializeListEffectivePermissionsOptions = (options) => ({ ...serializePaginationOptions(options) });
// src/authorization/authorization.ts
var Authorization = class {
workos;
constructor(workos) {
this.workos = workos;
}
/**
* Create an environment role
*
* Create a new environment role.
* @param options - Object containing slug, name.
* @returns {Promise<EnvironmentRole>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createEnvironmentRole(options) {
const { data } = await this.workos.post("/authorization/roles", serializeCreateEnvironmentRoleOptions(options));
return deserializeEnvironmentRole(data);
}
/**
* List environment roles
*
* List all environment roles in priority order.
* @returns {Promise<EnvironmentRoleList>}
* @throws 403 response from the API.
*/
async listEnvironmentRoles() {
const { data } = await this.workos.get("/authorization/roles");
return {
object: "list",
data: data.data.map(deserializeEnvironmentRole)
};
}
/**
* Get an environment role
*
* Get an environment role by its slug.
* @param slug - The slug of the environment role.
*
* @example
* "admin"
*
* @returns {Promise<EnvironmentRole>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async getEnvironmentRole(slug) {
const { data } = await this.workos.get(`/authorization/roles/${encodePathParameter(slug)}`);
return deserializeEnvironmentRole(data);
}
/**
* Update an environment role
*
* Update an existing environment role.
* @param slug - The slug of the environment role.
*
* @example
* "admin"
*
* @param options - The request body.
* @returns {Promise<EnvironmentRole>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updateEnvironmentRole(slug, options) {
const { data } = await this.workos.patch(`/authorization/roles/${encodePathParameter(slug)}`, serializeUpdateEnvironmentRoleOptions(options));
return deserializeEnvironmentRole(data);
}
/**
* Set permissions for an environment role
*
* Replace all permissions on an environment role with the provided list.
* @param slug - The slug of the environment role.
*
* @example
* "admin"
*
* @param options - Object containing permissions.
* @returns {Promise<EnvironmentRole>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async setEnvironmentRolePermissions(slug, options) {
const { data } = await this.workos.put(`/authorization/roles/${encodePathParameter(slug)}/permissions`, { permissions: options.permissions });
return deserializeEnvironmentRole(data);
}
/**
* Add a permission to an environment role
*
* Add a single permission to an environment role. If the permission is already assigned to the role, this operation has no effect.
* @param slug - The slug of the environment role.
*
* @example
* "admin"
*
* @param options - Object containing slug.
* @returns {Promise<EnvironmentRole>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async addEnvironmentRolePermission(slug, options) {
const { data } = await this.workos.post(`/authorization/roles/${encodePathParameter(slug)}/permissions`, { slug: options.permissionSlug });
return deserializeEnvironmentRole(data);
}
/**
* Create a custom role
*
* Create a new custom role for this organization.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param options - Object containing name.
* @returns {Promise<OrganizationRole>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createOrganizationRole(organizationId, options) {
const { data } = await this.workos.post(`/authorization/organizations/${encodePathParameter(organizationId)}/roles`, serializeCreateOrganizationRoleOptions(options));
return deserializeOrganizationRole(data);
}
/**
* List custom roles
*
* Get a list of all roles that apply to an organization. This includes both environment roles and custom roles, returned in priority order.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @returns {Promise<RoleList>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async listOrganizationRoles(organizationId) {
const { data } = await this.workos.get(`/authorization/organizations/${encodePathParameter(organizationId)}/roles`);
return {
object: "list",
data: data.data.map(deserializeRole)
};
}
/**
* Get a custom role
*
* Retrieve a role that applies to an organization by its slug. This can return either an environment role or a custom role.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param slug - The slug of the role.
*
* @example
* "org-billing-admin"
*
* @returns {Promise<Role>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async getOrganizationRole(organizationId, slug) {
const { data } = await this.workos.get(`/authorization/organizations/${encodePathParameter(organizationId)}/roles/${encodePathParameter(slug)}`);
return deserializeRole(data);
}
/**
* Update a custom role
*
* Update an existing custom role. Only the fields provided in the request body will be updated.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param slug - The slug of the role.
*
* @example
* "org-billing-admin"
*
* @param options - The request body.
* @returns {Promise<OrganizationRole>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updateOrganizationRole(organizationId, slug, options) {
const { data } = await this.workos.patch(`/authorization/organizations/${encodePathParameter(organizationId)}/roles/${encodePathParameter(slug)}`, serializeUpdateOrganizationRoleOptions(options));
return deserializeOrganizationRole(data);
}
/**
* Delete a custom role
*
* Delete an existing custom role.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param slug - The slug of the role.
*
* @example
* "org-admin"
*
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async deleteOrganizationRole(organizationId, slug) {
await this.workos.delete(`/authorization/organizations/${encodePathParameter(organizationId)}/roles/${encodePathParameter(slug)}`);
}
/**
* Set permissions for a custom role
*
* Replace all permissions on a custom role with the provided list.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param slug - The slug of the role.
*
* @example
* "org-admin"
*
* @param options - Object containing permissions.
* @returns {Promise<Role>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async setOrganizationRolePermissions(organizationId, slug, options) {
const { data } = await this.workos.put(`/authorization/organizations/${encodePathParameter(organizationId)}/roles/${encodePathParameter(slug)}/permissions`, { permissions: options.permissions });
return deserializeOrganizationRole(data);
}
/**
* Add a permission to a custom role
*
* Add a single permission to a custom role. If the permission is already assigned to the role, this operation has no effect.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param slug - The slug of the role.
*
* @example
* "org-admin"
*
* @param options - Object containing slug.
* @returns {Promise<Role>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async addOrganizationRolePermission(organizationId, slug, options) {
const { data } = await this.workos.post(`/authorization/organizations/${encodePathParameter(organizationId)}/roles/${encodePathParameter(slug)}/permissions`, { slug: options.permissionSlug });
return deserializeOrganizationRole(data);
}
/**
* Remove a permission from a custom role
*
* Remove a single permission from a custom role by its slug.
* @param organizationId - The ID of the organization.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param slug - The slug of the role.
*
* @example
* "org-admin"
*
* @param permissionSlug - The slug of the permission to remove.
*
* @example
* "documents:read"
*
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async removeOrganizationRolePermission(organizationId, slug, options) {
await this.workos.delete(`/authorization/organizations/${encodePathParameter(organizationId)}/roles/${encodePathParameter(slug)}/permissions/${encodePathParameter(options.permissionSlug)}`);
}
/**
* Create a permission
*
* Create a new permission in your WorkOS environment. The permission can then be assigned to environment roles and custom roles.
* @param options - Object containing slug, name.
* @returns {Promise<Permission>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createPermission(options) {
const { data } = await this.workos.post("/authorization/permissions", serializeCreatePermissionOptions(options));
return deserializePermission(data);
}
/**
* List permissions
*
* Get a list of all permissions in your WorkOS environment.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Permission, PaginationOptions>>}
* @throws {NotFoundException} 404
*/
async listPermissions(options) {
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/authorization/permissions", deserializePermission, options), (params) => fetchAndDeserialize(this.workos, "/authorization/permissions", deserializePermission, params), options);
}
/**
* Get a permission
*
* Retrieve a permission by its unique slug.
* @param slug - A unique key to reference the permission. Must be lowercase and contain only letters, numbers, hyphens, underscores, colons, periods, and asterisks.
*
* @example
* "documents:read"
*
* @returns {Promise<Permission>}
* @throws {NotFoundException} 404
*/
async getPermission(slug) {
const { data } = await this.workos.get(`/authorization/permissions/${encodePathParameter(slug)}`);
return deserializePermission(data);
}
/**
* Update a permission
*
* Update an existing permission. Only the fields provided in the request body will be updated.
* @param slug - A unique key to reference the permission. Must be lowercase and contain only letters, numbers, hyphens, underscores, colons, periods, and asterisks.
*
* @example
* "documents:read"
*
* @param options - The request body.
* @returns {Promise<Permission>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async updatePermission(slug, options) {
const { data } = await this.workos.patch(`/authorization/permissions/${encodePathParameter(slug)}`, serializeUpdatePermissionOptions(options));
return deserializePermission(data);
}
/**
* Delete a permission
*
* Delete an existing permission. System permissions cannot be deleted.
* @param slug - A unique key to reference the permission. Must be lowercase and contain only letters, numbers, hyphens, underscores, colons, periods, and asterisks.
*
* @example
* "documents:read"
*
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async deletePermission(slug) {
await this.workos.delete(`/authorization/permissions/${encodePathParameter(slug)}`);
}
/**
* Get a resource
*
* Retrieve the details of an authorization resource by its ID.
* @param resourceId - The ID of the authorization resource.
*
* @example
* "authz_resource_01HXYZ123456789ABCDEFGHIJ"
*
* @returns {Promise<AuthorizationResource>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async getResource(resourceId) {
const { data } = await this.workos.get(`/authorization/resources/${encodePathParameter(resourceId)}`);
return deserializeAuthorizationResource(data);
}
/**
* Create an authorization resource
*
* Create a new authorization resource.
* @param options - Object containing externalId, name, resourceTypeSlug, organizationId.
* @returns {Promise<AuthorizationResource>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createResource(options) {
const { data } = await this.workos.post("/authorization/resources", serializeCreateResourceOptions(options));
return deserializeAuthorizationResource(data);
}
/**
* Update a resource
*
* Update an existing authorization resource.
* @param options - The request body.
* @returns {Promise<AuthorizationResource>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateResource(options) {
const { data } = await this.workos.patch(`/authorization/resources/${encodePathParameter(options.resourceId)}`, serializeUpdateResourceOptions(options));
return deserializeAuthorizationResource(data);
}
/**
* Delete an authorization resource
*
* Delete an authorization resource and all its descendants.
* @param options.cascadeDelete - If true, deletes all descendant resources and role assignments. If not set and the resource has children or assignments, the request will fail.
* @default false
* @param options - Additional query options.
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async deleteResource(options) {
const { resourceId, cascadeDelete } = options;
const query = cascadeDelete !== void 0 ? { cascade_delete: cascadeDelete.toString() } : void 0;
await this.workos.delete(`/authorization/resources/${encodePathParameter(resourceId)}`, query);
}
/**
* List resources
*
* Get a paginated list of authorization resources.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<AuthorizationResource, PaginationOptions>>}
* @throws 403 response from the API.
* @throws {UnprocessableEntityException} 422
*/
async listResources(options = {}) {
const serializedOptions = serializeListAuthorizationResourcesOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/authorization/resources", deserializeAuthorizationResource, serializedOptions), (params) => fetchAndDeserialize(this.workos, "/authorization/resources", deserializeAuthorizationResource, params), serializedOptions);
}
/**
* Get a resource by external ID
*
* Retrieve the details of an authorization resource by its external ID, organization, and resource type. This is useful when you only have the external ID from your system and need to fetch the full resource details.
* @param organizationId - The ID of the organization that owns the resource.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param resourceTypeSlug - The slug of the resource type.
*
* @example
* "project"
*
* @param externalId - An identifier you provide to reference the resource in your system.
*
* @example
* "proj-456"
*
* @returns {Promise<AuthorizationResource>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async getResourceByExternalId(options) {
const { organizationId, resourceTypeSlug, externalId } = options;
const { data } = await this.workos.get(`/authorization/organizations/${encodePathParameter(organizationId)}/resources/${encodePathParameter(resourceTypeSlug)}/${encodePathParameter(externalId)}`);
return deserializeAuthorizationResource(data);
}
/**
* Update a resource by external ID
*
* Update an existing authorization resource using its external ID.
* @param organizationId - The ID of the organization that owns the resource.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param resourceTypeSlug - The slug of the resource type.
*
* @example
* "project"
*
* @param externalId - An identifier you provide to reference the resource in your system.
*
* @example
* "proj-456"
*
* @param options - The request body.
* @returns {Promise<AuthorizationResource>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async updateResourceByExternalId(options) {
const { organizationId, resourceTypeSlug, externalId } = options;
const { data } = await this.workos.patch(`/authorization/organizations/${encodePathParameter(organizationId)}/resources/${encodePathParameter(resourceTypeSlug)}/${encodePathParameter(externalId)}`, serializeUpdateResourceByExternalIdOptions(options));
return deserializeAuthorizationResource(data);
}
/**
* Delete an authorization resource by external ID
*
* Delete an authorization resource by organization, resource type, and external ID. This also deletes all descendant resources.
* @param organizationId - The ID of the organization that owns the resource.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param resourceTypeSlug - The slug of the resource type.
*
* @example
* "project"
*
* @param externalId - An identifier you provide to reference the resource in your system.
*
* @example
* "proj-456"
*
* @param options - Additional query options.
* @returns {Promise<void>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async deleteResourceByExternalId(options) {
const { organizationId, resourceTypeSlug, externalId, cascadeDelete } = options;
const query = cascadeDelete !== void 0 ? { cascade_delete: cascadeDelete.toString() } : void 0;
await this.workos.delete(`/authorization/organizations/${encodePathParameter(organizationId)}/resources/${encodePathParameter(resourceTypeSlug)}/${encodePathParameter(externalId)}`, query);
}
/**
* Check authorization
*
* Check if an organization membership has a specific permission on a resource. Supports identification by resource_id OR by resource_external_id + resource_type_slug.
* @param options - Object containing permissionSlug.
* @returns {Promise<AuthorizationCheckResult>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async check(options) {
const { data } = await this.workos.post(`/authorization/organization_memberships/${encodePathParameter(options.organizationMembershipId)}/check`, serializeAuthorizationCheckOptions(options));
return data;
}
/**
* List role assignments
*
* List all role assignments for an organization membership. This returns all roles that have been assigned to the user on resources, including organization-level and sub-resource roles.
* @param organizationMembershipId - The ID of the organization membership.
*
* @example
* "om_01HXYZ123456789ABCDEFGHIJ"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<RoleAssignment>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async listRoleAssignments(options) {
const { organizationMembershipId, ...queryOptions } = options;
const endpoint = `/authorization/organization_memberships/${encodePathParameter(organizationMembershipId)}/role_assignments`;
const serializedOptions = serializeListRoleAssignmentsOptions(queryOptions);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeRoleAssignment, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeRoleAssignment, params), serializedOptions);
}
/**
* List role assignments for a resource
*
* List all role assignments granted on a resource. This returns every role assignment scoped to the resource, regardless of which organization membership received it.
* @param resourceId - The ID of the authorization resource.
*
* @example
* "authz_resource_01HXYZ123456789ABCDEFGHIJ"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<RoleAssignment>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async listRoleAssignmentsForResource(options) {
const { resourceId, ...queryOptions } = options;
const endpoint = `/authorization/resources/${encodePathParameter(resourceId)}/role_assignments`;
const serializedOptions = serializeListRoleAssignmentsForResourceOptions(queryOptions);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeRoleAssignment, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeRoleAssignment, params), serializedOptions);
}
/**
* List role assignments for a resource by external ID
*
* List all role assignments granted on a resource identified by its external ID, organization, and resource type. This returns every role assignment scoped to the resource, regardless of which organization membership received it.
* @param organizationId - The ID of the organization that owns the resource.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param resourceTypeSlug - The slug of the resource type this resource belongs to.
*
* @example
* "project"
*
* @param externalId - An identifier you provide to reference the resource in your system.
*
* @example
* "proj-456"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<RoleAssignment>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async listResourceRoleAssignments(options) {
const { organizationId, resourceTypeSlug, externalId, ...queryOptions } = options;
const endpoint = `/authorization/organizations/${encodePathParameter(organizationId)}/resources/${encodePathParameter(resourceTypeSlug)}/${encodePathParameter(externalId)}/role_assignments`;
const serializedOptions = serializeListRoleAssignmentsForResourceOptions(queryOptions);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeRoleAssignment, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeRoleAssignment, params), serializedOptions);
}
/**
* Assign a role
*
* Assign a role to an organization membership on a specific resource.
* @param options - Object containing roleSlug.
* @returns {Promise<RoleAssignment>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async assignRole(options) {
const { data } = await this.workos.post(`/authorization/organization_memberships/${encodePathParameter(options.organizationMembershipId)}/role_assignments`, serializeAssignRoleOptions(options));
return deserializeRoleAssignment(data);
}
/**
* Remove a role assignment
*
* Remove a role assignment by role slug and resource.
* @param options - Object containing roleSlug.
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async removeRole(options) {
await this.workos.deleteWithBody(`/authorization/organization_memberships/${encodePathParameter(options.organizationMembershipId)}/role_assignments`, serializeRemoveRoleOptions(options));
}
/**
* Remove a role assignment by ID
*
* Remove a role assignment using its ID.
* @param organizationMembershipId - The ID of the organization membership.
*
* @example
* "om_01HXYZ123456789ABCDEFGHIJ"
*
* @param roleAssignmentId - The ID of the role assignment to remove.
*
* @example
* "role_assignment_01HXYZ123456789ABCDEFGH"
*
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async removeRoleAssignment(options) {
await this.workos.delete(`/authorization/organization_memberships/${encodePathParameter(options.organizationMembershipId)}/role_assignments/${encodePathParameter(options.roleAssignmentId)}`);
}
/**
* List role assignments for a group
*
* List all role assignments granted to a group. Each assignment represents a role granted to the group on a resource.
* @param options - Pagination options.
* @param options.groupId - The ID of the group.
*
* @example
* "group_01HXYZ123456789ABCDEFGHIJ"
*
* @returns {Promise<AutoPaginatable<GroupRoleAssignment>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async listGroupRoleAssignments(options) {
const { groupId, ...paginationOptions } = options;
const endpoint = `/authorization/groups/${encodePathParameter(groupId)}/role_assignments`;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeGroupRoleAssignment, paginationOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeGroupRoleAssignment, params), paginationOptions);
}
/**
* Get a group role assignment
*
* Get a specific role assignment for a group by its ID.
* @param options - Object containing groupId and roleAssignmentId.
* @param options.groupId - The ID of the group.
*
* @example
* "group_01HXYZ123456789ABCDEFGHIJ"
*
* @param options.roleAssignmentId - The ID of the group role assignment.
*
* @example
* "gra_01HXYZ123456789ABCDEFGH"
*
* @returns {Promise<GroupRoleAssignment>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async getGroupRoleAssignment(options) {
const { data } = await this.workos.get(`/authorization/groups/${encodePathParameter(options.groupId)}/role_assignments/${encodePathParameter(options.roleAssignmentId)}`);
return deserializeGroupRoleAssignment(data);
}
/**
* Assign a role to a group
*
* Assign a role to a group on a specific resource. Omit the resource fields to assign the role on the organization itself.
* @param options - Object containing groupId and roleSlug.
* @returns {Promise<GroupRoleAssignment>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createGroupRoleAssignment(options) {
const { data } = await this.workos.post(`/authorization/groups/${encodePathParameter(options.groupId)}/role_assignments`, serializeCreateGroupRoleAssignmentOptions(options));
return deserializeGroupRoleAssignment(data);
}
/**
* Remove a group role assignment
*
* Remove a specific role assignment from a group by its ID.
* @param options - Object containing groupId and roleAssignmentId.
* @param options.groupId - The ID of the group.
*
* @example
* "group_01HXYZ123456789ABCDEFGHIJ"
*
* @param options.roleAssignmentId - The ID of the group role assignment to remove.
*
* @example
* "gra_01HXYZ123456789ABCDEFGH"
*
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
*/
async removeGroupRoleAssignment(options) {
await this.workos.delete(`/authorization/groups/${encodePathParameter(options.groupId)}/role_assignments/${encodePathParameter(options.roleAssignmentId)}`);
}
/**
* Remove group role assignments by criteria
*
* Remove role assignments from a group that match the provided role and resource. Omit the resource fields to target the organization itself.
* @param options - Object containing groupId and roleSlug.
* @returns {Promise<void>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async removeGroupRoleAssignments(options) {
await this.workos.deleteWithBody(`/authorization/groups/${encodePathParameter(options.groupId)}/role_assignments`, serializeRemoveGroupRoleAssignmentsOptions(options));
}
/**
* Replace role assignments for a group
*
* Replace all of a group's role assignments with the provided list. Assignments not present in the list are removed and new ones are created. Pass an empty `roleAssignments` array to clear all assignments. Returns the resulting set of assignments.
* @param options - Object containing groupId and roleAssignments.
* @returns {Promise<List<GroupRoleAssignment>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async replaceGroupRoleAssignments(options) {
const { data } = await this.workos.put(`/authorization/groups/${encodePathParameter(options.groupId)}/role_assignments`, serializeReplaceGroupRoleAssignmentsOptions(options));
return deserializeList(data, deserializeGroupRoleAssignment);
}
/**
* List resources for organization membership
*
* Returns all child resources of a parent resource where the organization membership has a specific permission. This is useful for resource discovery—answering "What projects can this user access in this workspace?"
*
* You must provide either `parent_resource_id` or both `parent_resource_external_id` and `parent_resource_type_slug` to identify the parent resource.
* @param organizationMembershipId - The ID of the organization membership.
*
* @example
* "om_01HXYZ123456789ABCDEFGHIJ"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<AuthorizationResource>>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listResourcesForMembership(options) {
const { organizationMembershipId } = options;
const endpoint = `/authorization/organization_memberships/${encodePathParameter(organizationMembershipId)}/resources`;
const serializedOptions = serializeListResourcesForMembershipOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationResource, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationResource, params), serializedOptions);
}
/**
* List organization memberships for resource
*
* Returns all organization memberships that have a specific permission on a resource instance. This is useful for answering "Who can access this resource?".
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<BaseOrganizationMembership, PaginationOptions>>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listMembershipsForResource(options) {
const { resourceId } = options;
const endpoint = `/authorization/resources/${encodePathParameter(resourceId)}/organization_memberships`;
const serializedOptions = serializeListMembershipsForResourceOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationOrganizationMembership, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationOrganizationMembership, params), serializedOptions);
}
/**
* List memberships for a resource by external ID
*
* Returns all organization memberships that have a specific permission on a resource, using the resource's external ID. This is useful for answering "Who can access this resource?" when you only have the external ID.
* @param organizationId - The ID of the organization that owns the resource.
*
* @example
* "org_01EHZNVPK3SFK441A1RGBFSHRT"
*
* @param resourceTypeSlug - The slug of the resource type this resource belongs to.
*
* @example
* "project"
*
* @param externalId - An identifier you provide to reference the resource in your system.
*
* @example
* "proj-456"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<UserOrganizationMembershipBaseListData>>}
* @throws {BadRequestException} 400
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listMembershipsForResourceByExternalId(options) {
const { organizationId, resourceTypeSlug, externalId } = options;
const endpoint = `/authorization/organizations/${encodePathParameter(organizationId)}/resources/${encodePathParameter(resourceTypeSlug)}/${encodePathParameter(externalId)}/organization_memberships`;
const serializedOptions = serializeListMembershipsForResourceOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationOrganizationMembership, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeAuthorizationOrganizationMembership, params), serializedOptions);
}
/**
* List effective permissions for an organization membership on a resource
*
* Returns all permissions the organization membership effectively has on a resource, including permissions inherited through roles assigned to ancestor resources.
* @param organizationMembershipId - The ID of the organization membership.
*
* @example
* "om_01HXYZ123456789ABCDEFGHIJ"
*
* @param resourceId - The ID of the authorization resource.
*
* @example
* "authz_resource_01HXYZ123456789ABCDEFGHIJ"
*
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<AuthorizationPermission>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listEffectivePermissions(options) {
const { organizationMembershipId, resourceId } = options;
const endpoint = `/authorization/resources/${encodePathParameter(resourceId)}/organization_memberships/${encodePathParameter(organizationMembershipId)}/permissions`;
const serializedOptions = serializeListEffectivePermissionsOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializePermission, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializePermission, params), serializedOptions);
}
/**
* List effective permissions for an organization membership on a resource by external ID
*
* Returns all permissions the organization membership effectively has on a resource identified by its external ID, including permissions inherited through roles assigned to ancestor resources.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<Permission, PaginationOptions>>}
* @throws 403 response from the API.
* @throws {NotFoundException} 404
* @throws {UnprocessableEntityException} 422
*/
async listEffectivePermissionsByExternalId(options) {
const { organizationMembershipId, resourceTypeSlug, externalId } = options;
const endpoint = `/authorization/organization_memberships/${encodePathParameter(organizationMembershipId)}/resources/${encodePathParameter(resourceTypeSlug)}/${encodePathParameter(externalId)}/permissions`;
const serializedOptions = serializeListEffectivePermissionsOptions(options);
return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializePermission, serializedOptions), (params) => fetchAndDeserialize(this.workos, endpoint, deserializePermission, params), serializedOptions);
}
};
// src/common/utils/leb128.ts
/**
* LEB128 (Little Endian Base 128) encoding for unsigned 32-bit integers.
* Variable-length encoding: each byte stores 7 bits of data, bit 7 is continuation flag.
*/
const MAX_UINT32 = 4294967295;
const CONTINUATION_BIT = 128;
const DATA_BITS_MASK = 127;
const DATA_BITS_PER_BYTE = 7;
const MAX_BYTES_FOR_UINT32 = 5;
const FINAL_BYTE_SHIFT = 28;
const FINAL_BYTE_MAX_DATA = 15;
/**
* Encodes an unsigned 32-bit integer into LEB128 format.
*
* @param value - Unsigned 32-bit integer (0 to 4,294,967,295)
* @returns Encoded bytes (1-5 bytes depending on value)
*/
function encodeUInt32(value) {
validateUInt32(value);
if (value === 0) return new Uint8Array([0]);
const bytes = [];
do {
let byte = value & DATA_BITS_MASK;
value >>>= DATA_BITS_PER_BYTE;
if (value !== 0) byte |= CONTINUATION_BIT;
bytes.push(byte);
} while (value !== 0);
return new Uint8Array(bytes);
}
/**
* Decodes an unsigned 32-bit integer from LEB128 format.
*
* @param data - Buffer containing LEB128 encoded data
* @param offset - Starting position in buffer (default: 0)
* @returns Decoded value and index after last byte read
*/
function decodeUInt32(data, offset = 0) {
validateOffset(data, offset);
let result = 0;
let shift = 0;
let index = offset;
let bytesRead = 0;
while (index < data.length) {
const byte = data[index++];
bytesRead++;
if (bytesRead > MAX_BYTES_FOR_UINT32) throw new Error("LEB128 sequence exceeds maximum length for uint32");
if (shift === FINAL_BYTE_SHIFT && (byte & DATA_BITS_MASK) > FINAL_BYTE_MAX_DATA) throw new Error("LEB128 sequence exceeds uint32 range");
result |= (byte & DATA_BITS_MASK) << shift;
if (!hasContinuationBit(byte)) return {
value: result >>> 0,
nextIndex: index
};
shift += DATA_BITS_PER_BYTE;
}
throw new Error("Truncated LEB128 encoding");
}
function validateUInt32(value) {
if (!Number.isFinite(value)) throw new Error("Value must be a finite number");
if (!Number.isInteger(value)) throw new Error("Value must be an integer");
if (value < 0) throw new Error("Value must be non-negative");
if (value > MAX_UINT32) throw new Error(`Value must not exceed ${MAX_UINT32} (MAX_UINT32)`);
}
function validateOffset(data, offset) {
if (offset < 0 || offset >= data.length) throw new Error(`Offset ${offset} is out of bounds (buffer length: ${data.length})`);
}
function hasContinuationBit(byte) {
return (byte & CONTINUATION_BIT) !== 0;
}
// src/vault/serializers/create-data-key-response.serializer.ts
const deserializeCreateDataKeyResponse = (response) => ({
context: response.context,
dataKey: response.data_key,
encryptedKeys: response.encrypted_keys,
id: response.id
});
// src/vault/serializers/decrypt-response.serializer.ts
const deserializeDecryptResponse = (response) => ({
dataKey: response.data_key,
id: response.id
});
// src/vault/serializers/actor.serializer.ts
const deserializeActor = (response) => ({
id: response.id,
name: response.name
});
// src/vault/serializers/object-metadata.serializer.ts
const deserializeObjectMetadata = (response) => ({
context: response.context,
environmentId: response.environment_id,
id: response.id,
keyId: response.key_id,
updatedAt: new Date(response.updated_at),
updatedBy: deserializeActor(response.updated_by),
versionId: response.version_id ?? null
});
// src/vault/serializers/vault-object.serializer.ts
const deserializeVaultObject = (response) => ({
id: response.id,
metadata: deserializeObjectMetadata(response.metadata),
name: response.name,
value: response.value
});
// src/vault/serializers/object-without-value.serializer.ts
const deserializeObjectWithoutValue = (response) => ({
id: response.id,
metadata: deserializeObjectMetadata(response.metadata),
name: response.name
});
// src/vault/serializers/object-version.serializer.ts
const deserializeObjectVersion = (response) => ({
createdAt: new Date(response.created_at),
currentVersion: response.current_version,
etag: response.etag ?? "",
id: response.id,
size: response.size ?? 0
});
// src/vault/serializers/list-metadata.serializer.ts
const deserializeListMetadata = (response) => ({
after: response.after ?? null,
before: response.before ?? null
});
// src/vault/serializers/version-list-response.serializer.ts
const deserializeVersionListResponse = (response) => ({
data: response.data.map(deserializeObjectVersion),
listMetadata: deserializeListMetadata(response.list_metadata)
});
// src/vault/serializers/object-summary.serializer.ts
const deserializeObjectSummary = (response) => ({
id: response.id,
name: response.name,
updatedAt: response.updated_at != null ? new Date(response.updated_at) : null
});
// src/vault/serializers/create-data-key-request.serializer.ts
const serializeCreateDataKeyRequest = (model) => ({ context: model.context });
// src/vault/serializers/decrypt-request.serializer.ts
const serializeDecryptRequest = (model) => ({ keys: model.keys });
// src/vault/serializers/rekey-request.serializer.ts
const serializeRekeyRequest = (model) => ({
context: model.context,
encrypted_keys: model.encryptedKeys
});
// src/vault/serializers/create-object-request.serializer.ts
const serializeCreateObjectRequest = (model) => ({
key_context: model.keyContext,
name: model.name,
value: model.value
});
// src/vault/serializers/update-object-request.serializer.ts
const serializeUpdateObjectRequest = (model) => ({
value: model.value,
version_check: model.versionCheck ?? null
});
// src/common/utils/base64.ts
/**
* Cross-runtime compatible base64 encoding/decoding utilities
* that work in both Node.js and browser environments
*/
/**
* Converts a base64 string to a Uint8Array
*/
function base64ToUint8Array(base64) {
if (typeof atob === "function") {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
} else if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(base64, "base64"));
else throw new Error("No base64 decoding implementation available");
}
/**
* Converts a Uint8Array to a base64 string
*/
function uint8ArrayToBase64(bytes) {
if (typeof btoa === "function") {
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
return btoa(binary);
} else if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
else throw new Error("No base64 encoding implementation available");
}
// src/vault/vault.ts
const serializeListObjectsOptions = (options) => {
const wire = {
limit: options.limit,
before: options.before,
after: options.after,
order: options.order
};
if (options.search !== void 0) wire.search = options.search;
if (options.updatedAfter !== void 0) wire.updated_after = options.updatedAfter;
return wire;
};
var Vault = class {
workos;
constructor(workos) {
this.workos = workos;
}
async readObjectByName(options) {
const name = typeof options === "string" ? options : options.name;
const { data } = await this.workos.get(`/vault/v1/kv/name/${encodeURIComponent(name)}`);
return deserializeVaultObject(data);
}
/**
* Create a data key
*
* Generate an isolated encryption key for local encryption operations.
* @param options - Object containing context.
* @param options.context - Map of values used to determine the encryption key.
* @example {"organization_id":"org_01K8ZYT4AWJ6XP0E0S8CTBHE3P"}
* @returns {Promise<DataKeyPair>}
* @throws {BadRequestException} 400
* @throws {UnprocessableEntityException} 422
*/
async createDataKey(options) {
const payload = options;
const { data } = await this.workos.post("/vault/v1/keys/data-key", serializeCreateDataKeyRequest(payload));
const result = deserializeCreateDataKeyResponse(data);
return {
context: result.context,
dataKey: {
key: result.dataKey,
id: result.id
},
encryptedKeys: result.encryptedKeys
};
}
/**
* Decrypt a data key
*
* Decrypt a previously encrypted data key from WorkOS Vault.
* @param options - Object containing keys.
* @param options.keys - Base64-encoded encrypted data key to decrypt.
* @example "V09TLkVLTS52MQBiZjUxY2NlYy03OGI0LTUyMDAtYjM4My0zNTczMGU3MWVmNjEBATEBJGJmNjVlMzI2LTQzYTAtNGIyMC04OGM0LTA3ZmYzZGU1NDM0YwF0YmY2NWUzMjYtNDNhMC00YjIwLTg4YzQtMDdmZjNkZTU0MzRj"
* @returns {Promise<DataKey>}
* @throws {BadRequestException} 400
*/
async decryptDataKey(options) {
const payload = options;
const { data } = await this.workos.post("/vault/v1/keys/decrypt", serializeDecryptRequest(payload));
const result = deserializeDecryptResponse(data);
return {
key: result.dataKey,
id: result.id
};
}
/**
* Re-encrypt a data key
*
* Decrypt an existing data key and re-encrypt it under a new key context.
* @param options - Object containing context, encryptedKeys.
* @param options.context - Map of values used to determine the new encryption key.
* @example {"organization_id":"org_01K8ZYT4AWJ6XP0E0S8CTBHE3P"}
* @param options.encryptedKeys - Base64-encoded encrypted data key blob to re-encrypt.
* @example "V09TLkVLTS52MQBiZjUxY2NlYy03OGI0LTUyMDAtYjM4My0zNTczMGU3MWVmNjEBATEBJGJmNjVlMzI2LTQzYTAtNGIyMC04OGM0LTA3ZmYzZGU1NDM0YwF0YmY2NWUzMjYtNDNhMC00YjIwLTg4YzQtMDdmZjNkZTU0MzRj"
* @returns {Promise<CreateDataKeyResponse>}
* @throws {BadRequestException} 400
* @throws {UnprocessableEntityException} 422
*/
async createRekey(options) {
const payload = options;
const { data } = await this.workos.post("/vault/v1/keys/rekey", serializeRekeyRequest(payload));
return deserializeCreateDataKeyResponse(data);
}
/**
* List objects
*
* List all encrypted objects with cursor-based pagination.
* @param options - Pagination and filter options.
* @returns {Promise<AutoPaginatable<ObjectSummary, PaginationOptions>>}
* @throws {BadRequestException} 400
*/
async listObjects(options) {
const paginationOptions = options;
return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/vault/v1/kv", deserializeObjectSummary, options ? serializeListObjectsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, "/vault/v1/kv", deserializeObjectSummary, params), paginationOptions);
}
/**
* Create an object
*
* Encrypt and store a new key-value object.
* @param options - Object containing keyContext, name, value.
* @param options.keyContext - Map of values used to determine the encryption key.
* @example {"organization_id":"org_01K8ZYT4AWJ6XP0E0S8CTBHE3P"}
* @param options.name - Unique name for the object.
* @example "my-secret"
* @param options.value - Plaintext data to encrypt and store.
* @example "s3cr3t-v4lu3"
* @returns {Promise<ObjectMetadata>}
* @throws {BadRequestException} 400
* @throws {ConflictException} 409
* @throws {UnprocessableEntityException} 422
*/
async createObject(options) {
const payload = options;
const requestPayload = {
...payload,
keyContext: payload.context
};
const { data } = await this.workos.post("/vault/v1/kv", serializeCreateObjectRequest(requestPayload));
return deserializeObjectMetadata(data);
}
/**
* Read an object by ID
*
* Fetch and decrypt an object by its unique identifier.
* @param options - The request options.
* @param options.id - Unique identifier of the object.
* @example "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
* @returns {Promise<VaultObject>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async readObject(options) {
const { id } = options;
const { data } = await this.workos.get(`/vault/v1/kv/${encodeURIComponent(id)}`);
return deserializeVaultObject(data);
}
/**
* Update an object
*
* Update the value of an existing encrypted object.
* @param options - Object containing value.
* @param options.id - Unique identifier of the object.
* @example "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
* @param options.value - New plaintext value.
* @example "upd4t3d-v4lu3"
* @param options.versionCheck - ID of the expected current version for optimistic locking.
* @example "c3d4e5f6-7890-abcd-ef12-34567890abcd"
* @returns {Promise<VaultObject>}
* @throws {BadRequestException} 400
* @throws {ConflictException} 409
*/
async updateObject(options) {
const { id, ...payload } = options;
const { data } = await this.workos.put(`/vault/v1/kv/${encodeURIComponent(id)}`, serializeUpdateObjectRequest(payload));
return {
...deserializeObjectWithoutValue(data),
value: void 0
};
}
/**
* Delete an object
*
* Delete an encrypted object.
* @param options - Additional query options.
* @param options.id - Unique identifier of the object.
* @example "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
* @param options.versionCheck - Expected current version for optimistic locking.
* @example "c3d4e5f6-7890-abcd-ef12-34567890abcd"
* @returns {Promise<void>}
* @throws {NotFoundException} 404
* @throws {ConflictException} 409
*/
async deleteObject(options) {
const { id } = options;
await this.workos.delete(`/vault/v1/kv/${encodeURIComponent(id)}`, { ...options.versionCheck !== void 0 && { version_check: options.versionCheck } });
}
/**
* Describe an object
*
* Fetch metadata for an object without decrypting it.
* @param options - The request options.
* @param options.id - Unique identifier of the object.
* @example "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
* @returns {Promise<VaultObject>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async describeObject(options) {
const { id } = options;
const { data } = await this.workos.get(`/vault/v1/kv/${encodeURIComponent(id)}/metadata`);
return {
...deserializeObjectWithoutValue(data),
value: void 0
};
}
/**
* List object versions
*
* Retrieve all versions for a specific object.
* @param options - The request options.
* @param options.id - Unique identifier of the object.
* @example "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
* @returns {Promise<ObjectVersion[]>}
* @throws {BadRequestException} 400
* @throws {NotFoundException} 404
*/
async listObjectVersions(options) {
const { id } = options;
const { data } = await this.workos.get(`/vault/v1/kv/${encodeURIComponent(id)}/versions`);
return deserializeVersionListResponse(data).data;
}
decode(payload) {
const inputData = base64ToUint8Array(payload);
const iv = new Uint8Array(inputData.subarray(0, 12));
const tag = new Uint8Array(inputData.subarray(12, 28));
const { value: keyLen, nextIndex } = decodeUInt32(inputData, 28);
return {
iv,
tag,
keys: uint8ArrayToBase64(inputData.subarray(nextIndex, nextIndex + keyLen)),
ciphertext: new Uint8Array(inputData.subarray(nextIndex + keyLen))
};
}
async decrypt(encryptedData, associatedData) {
const decoded = this.decode(encryptedData);
const key = base64ToUint8Array((await this.decryptDataKey({ keys: decoded.keys })).key);
const aadBuffer = associatedData ? new TextEncoder().encode(associatedData) : void 0;
const decrypted = await this.workos.getCryptoProvider().decrypt(decoded.ciphertext, key, decoded.iv, decoded.tag, aadBuffer);
return new TextDecoder().decode(decrypted);
}
async encrypt(data, context, associatedData) {
const keyPair = await this.createDataKey({ context });
const encoder = new TextEncoder();
const key = base64ToUint8Array(keyPair.dataKey.key);
const keyBlob = base64ToUint8Array(keyPair.encryptedKeys);
const prefixLenBuffer = encodeUInt32(keyBlob.length);
const aadBuffer = associatedData ? encoder.encode(associatedData) : void 0;
const cryptoProvider = this.workos.getCryptoProvider();
const iv = cryptoProvider.randomBytes(12);
const { ciphertext, iv: resultIv, tag } = await cryptoProvider.encrypt(encoder.encode(data), key, iv, aadBuffer);
const resultArray = new Uint8Array(resultIv.length + tag.length + prefixLenBuffer.length + keyBlob.length + ciphertext.length);
let offset = 0;
resultArray.set(resultIv, offset);
offset += resultIv.length;
resultArray.set(tag, offset);
offset += tag.length;
resultArray.set(new Uint8Array(prefixLenBuffer), offset);
offset += prefixLenBuffer.length;
resultArray.set(keyBlob, offset);
offset += keyBlob.length;
resultArray.set(ciphertext, offset);
return uint8ArrayToBase64(resultArray);
}
};
// package.json
var version = "12.4.0";
// src/workos.ts
const DEFAULT_HOSTNAME = "api.workos.com";
const HEADER_AUTHORIZATION = "Authorization";
const HEADER_IDEMPOTENCY_KEY = "Idempotency-Key";
const HEADER_WARRANT_TOKEN = "Warrant-Token";
/** WorkOS REST API */
var WorkOS = class {
baseURL;
client;
clientId;
key;
options;
pkce;
hasApiKey;
actions;
agents = new Agents(this);
apiKeys = new ApiKeys(this);
auditLogs = new AuditLogs(this);
authorization = new Authorization(this);
directorySync = new DirectorySync(this);
connect = new Connect(this);
events = new Events(this);
featureFlags = new FeatureFlags(this);
groups = new Groups(this);
multiFactorAuth = new MultiFactorAuth(this);
organizations = new Organizations(this);
organizationDomains = new OrganizationDomains(this);
passwordless = new Passwordless(this);
pipes = new Pipes(this);
radar = new Radar(this);
adminPortal = new AdminPortal(this);
sso = new SSO(this);
userManagement;
vault = new Vault(this);
webhooks;
widgets = new Widgets(this);
/**
* Create a new WorkOS client.
*
* @param keyOrOptions - API key string, or options object
* @param maybeOptions - Options when first argument is API key
*
* @example
* // Server-side with API key (string)
* const workos = new WorkOS('sk_...');
*
* @example
* // Server-side with API key (object)
* const workos = new WorkOS({ apiKey: 'sk_...', clientId: 'client_...' });
*
* @example
* // PKCE/public client (no API key)
* const workos = new WorkOS({ clientId: 'client_...' });
*/
constructor(keyOrOptions, maybeOptions) {
if (typeof keyOrOptions === "object") {
this.key = keyOrOptions.apiKey;
this.options = keyOrOptions;
} else {
this.key = keyOrOptions;
this.options = maybeOptions ?? {};
}
if (!this.key) this.key = getEnv("WORKOS_API_KEY");
this.hasApiKey = !!this.key;
if (this.options.https === void 0) this.options.https = true;
this.clientId = this.options.clientId;
if (!this.clientId) this.clientId = getEnv("WORKOS_CLIENT_ID");
if (!this.hasApiKey && !this.clientId) throw new Error("WorkOS requires either an API key or a clientId. For server-side: new WorkOS(\"sk_...\") or new WorkOS({ apiKey: \"sk_...\" }). For PKCE/public clients: new WorkOS({ clientId: \"client_...\" })");
const protocol = this.options.https ? "https" : "http";
const apiHostname = this.options.apiHostname || DEFAULT_HOSTNAME;
const port = this.options.port;
this.baseURL = `${protocol}://${apiHostname}`;
if (port) this.baseURL = this.baseURL + `:${port}`;
this.pkce = new PKCE();
this.webhooks = this.createWebhookClient();
this.actions = this.createActionsClient();
this.userManagement = new UserManagement(this);
const userAgent = this.createUserAgent(this.options);
this.client = this.createHttpClient(this.options, userAgent);
}
createUserAgent(_options) {
return `workos-node/${version}`;
}
createWebhookClient() {
return new Webhooks(this);
}
createActionsClient() {
return new Actions(this.getCryptoProvider());
}
getCryptoProvider() {
return new SubtleCryptoProvider();
}
createHttpClient(options, userAgent) {
const headers = { "User-Agent": userAgent };
const configHeaders = options.config?.headers;
if (configHeaders && typeof configHeaders === "object" && !Array.isArray(configHeaders) && !(configHeaders instanceof Headers)) Object.assign(headers, configHeaders);
if (this.key) headers["Authorization"] = `Bearer ${this.key}`;
return new FetchHttpClient(this.baseURL, {
...options.config,
timeout: options.timeout,
maxRetries: options.maxRetries,
headers
}, options.fetchFn);
}
get version() {
return version;
}
/**
* Require API key for methods that need it.
* @param methodName - Name of the method requiring API key (for error message)
* @throws ApiKeyRequiredException if no API key was provided
*/
requireApiKey(methodName) {
if (!this.hasApiKey) throw new ApiKeyRequiredException(methodName);
}
async post(path, entity, options = {}) {
if (!options.skipApiKeyCheck) this.requireApiKey(path);
const requestHeaders = {};
if (options.idempotencyKey) requestHeaders[HEADER_IDEMPOTENCY_KEY] = options.idempotencyKey;
if (options.warrantToken) requestHeaders[HEADER_WARRANT_TOKEN] = options.warrantToken;
let res;
try {
res = await this.client.post(path, entity, {
params: options.query,
headers: requestHeaders,
maxRetries: options.maxRetries
});
} catch (error) {
this.handleHttpError({
path,
error
});
throw error;
}
return { data: await this.readResponseJSON(path, res) };
}
async get(path, options = {}) {
if (!options.skipApiKeyCheck) this.requireApiKey(path);
const requestHeaders = {};
if (options.accessToken) requestHeaders[HEADER_AUTHORIZATION] = `Bearer ${options.accessToken}`;
if (options.warrantToken) requestHeaders[HEADER_WARRANT_TOKEN] = options.warrantToken;
let res;
try {
res = await this.client.get(path, {
params: options.query,
headers: requestHeaders,
maxRetries: options.maxRetries,
signal: options.signal
});
} catch (error) {
options.signal?.throwIfAborted();
this.handleHttpError({
path,
error
});
throw error;
}
return { data: await this.readResponseJSON(path, res) };
}
async put(path, entity, options = {}) {
if (!options.skipApiKeyCheck) this.requireApiKey(path);
const requestHeaders = {};
if (options.idempotencyKey) requestHeaders[HEADER_IDEMPOTENCY_KEY] = options.idempotencyKey;
let res;
try {
res = await this.client.put(path, entity, {
params: options.query,
headers: requestHeaders,
maxRetries: options.maxRetries
});
} catch (error) {
this.handleHttpError({
path,
error
});
throw error;
}
return { data: await this.readResponseJSON(path, res) };
}
async patch(path, entity, options = {}) {
if (!options.skipApiKeyCheck) this.requireApiKey(path);
const requestHeaders = {};
if (options.idempotencyKey) requestHeaders[HEADER_IDEMPOTENCY_KEY] = options.idempotencyKey;
let res;
try {
res = await this.client.patch(path, entity, {
params: options.query,
headers: requestHeaders,
maxRetries: options.maxRetries
});
} catch (error) {
this.handleHttpError({
path,
error
});
throw error;
}
return { data: await this.readResponseJSON(path, res) };
}
async delete(path, query) {
this.requireApiKey(path);
try {
await this.client.delete(path, { params: query });
} catch (error) {
this.handleHttpError({
path,
error
});
throw error;
}
}
async deleteWithBody(path, entity) {
this.requireApiKey(path);
try {
await this.client.deleteWithBody(path, entity, {});
} catch (error) {
this.handleHttpError({
path,
error
});
throw error;
}
}
/**
* Consume a successful response body. The request deadline covers the body,
* so a stall while it is still streaming surfaces from the transport as a
* 408 `HttpClientError` and is translated like a timeout before the headers.
* Everything else (a `ParseError` for malformed JSON, a network failure
* mid-body) propagates unchanged.
*/
/** @internal */
async readResponseJSON(path, response) {
try {
return await response.toJSON();
} catch (error) {
if (error instanceof HttpClientError) this.handleHttpError({
path,
error
});
throw error;
}
}
emitWarning(warning) {
console.warn(`WorkOS: ${warning}`);
}
/** @internal */
handleHttpError({ path, error }) {
if (!(error instanceof HttpClientError)) throw new Error(`Unexpected error: ${error}`, { cause: error });
const { response } = error;
if (response) {
const { status, data, headers } = response;
const requestID = headers.get("X-Request-ID") ?? "";
const { code, error_description: errorDescription, error, errors, message } = data;
switch (status) {
case 401: throw new UnauthorizedException(requestID);
case 409: throw new ConflictException({
requestID,
message,
error,
code
});
case 422: throw new UnprocessableEntityException({
code,
error,
errors,
message,
requestID
});
case 404: throw new NotFoundException({
code,
message,
path,
requestID
});
case 429: {
const retryAfter = headers.get("Retry-After");
throw new RateLimitExceededException(data.message, requestID, retryAfter ? Number(retryAfter) : null);
}
default: if (isAuthenticationErrorData(data)) throw new AuthenticationException(status, data, requestID);
else if (error || errorDescription) throw new OauthException(status, requestID, error, errorDescription, data);
else if (code && errors) throw new BadRequestException({
code,
errors,
message,
requestID
});
else throw new GenericServerException(status, data.message, data, requestID);
}
}
}
};
// src/audit-logs/interfaces/update-audit-logs-retention-retention-period.interface.ts
const UpdateAuditLogsRetentionRetentionPeriod = {
Value1Month: "1_MONTH",
Value2Months: "2_MONTHS",
Value3Months: "3_MONTHS",
Value4Months: "4_MONTHS",
Value5Months: "5_MONTHS",
Value6Months: "6_MONTHS",
Value7Months: "7_MONTHS",
Value8Months: "8_MONTHS",
Value9Months: "9_MONTHS",
Value10Months: "10_MONTHS",
Value11Months: "11_MONTHS",
Value1Year: "1_YEAR",
Value2Years: "2_YEARS",
Value3Years: "3_YEARS",
Value4Years: "4_YEARS",
Value5Years: "5_YEARS",
Value6Years: "6_YEARS",
Value7Years: "7_YEARS",
Value8Years: "8_YEARS",
Value9Years: "9_YEARS",
Value10Years: "10_YEARS"
};
// src/common/interfaces/generate-link-intent.interface.ts
const GenerateLinkIntent = {
SSO: "sso",
DSync: "dsync",
AuditLogs: "audit_logs",
LogStreams: "log_streams",
DomainVerification: "domain_verification",
CertificateRenewal: "certificate_renewal",
BringYourOwnKey: "bring_your_own_key"
};
// src/directory-sync/interfaces/directory-user-with-groups-state.interface.ts
const DirectoryUserWithGroupsState = {
Active: "active",
Suspended: "suspended",
Inactive: "inactive"
};
// src/organizations/interfaces/domain-data.interface.ts
let DomainDataState = /* @__PURE__ */ function(DomainDataState) {
DomainDataState["Verified"] = "verified";
DomainDataState["Pending"] = "pending";
return DomainDataState;
}({});
// src/organizations/interfaces/it-contact-options.interface.ts
const ItContactIntent = {
SSO: "sso",
DirectorySync: "directory_sync",
LogStreams: "log_streams",
DomainVerification: "domain_verification",
BringYourOwnKey: "bring_your_own_key"
};
// src/organization-domains/interfaces/organization-domain.interface.ts
let OrganizationDomainState = /* @__PURE__ */ function(OrganizationDomainState) {
OrganizationDomainState["Verified"] = "verified";
OrganizationDomainState["Pending"] = "pending";
OrganizationDomainState["Unverified"] = "unverified";
OrganizationDomainState["Failed"] = "failed";
return OrganizationDomainState;
}({});
let OrganizationDomainVerificationStrategy = /* @__PURE__ */ function(OrganizationDomainVerificationStrategy) {
OrganizationDomainVerificationStrategy["Dns"] = "dns";
OrganizationDomainVerificationStrategy["Manual"] = "manual";
return OrganizationDomainVerificationStrategy;
}({});
// src/sso/interfaces/connection-type.enum.ts
let ConnectionType = /* @__PURE__ */ function(ConnectionType) {
ConnectionType["ADFSSAML"] = "ADFSSAML";
ConnectionType["AdpOidc"] = "AdpOidc";
ConnectionType["AppleOAuth"] = "AppleOAuth";
ConnectionType["Auth0SAML"] = "Auth0SAML";
ConnectionType["AzureSAML"] = "AzureSAML";
ConnectionType["CasSAML"] = "CasSAML";
ConnectionType["CleverOIDC"] = "CleverOIDC";
ConnectionType["ClassLinkSAML"] = "ClassLinkSAML";
ConnectionType["CloudflareSAML"] = "CloudflareSAML";
ConnectionType["CyberArkSAML"] = "CyberArkSAML";
ConnectionType["DuoSAML"] = "DuoSAML";
ConnectionType["EntraIdOIDC"] = "EntraIdOIDC";
ConnectionType["GenericOIDC"] = "GenericOIDC";
ConnectionType["GenericSAML"] = "GenericSAML";
ConnectionType["GitHubOAuth"] = "GitHubOAuth";
ConnectionType["GoogleOAuth"] = "GoogleOAuth";
ConnectionType["GoogleSAML"] = "GoogleSAML";
ConnectionType["JumpCloudSAML"] = "JumpCloudSAML";
ConnectionType["KeycloakSAML"] = "KeycloakSAML";
ConnectionType["LastPassSAML"] = "LastPassSAML";
ConnectionType["LoginGovOidc"] = "LoginGovOidc";
ConnectionType["MagicLink"] = "MagicLink";
ConnectionType["MicrosoftOAuth"] = "MicrosoftOAuth";
ConnectionType["MiniOrangeSAML"] = "MiniOrangeSAML";
ConnectionType["NetIqSAML"] = "NetIqSAML";
ConnectionType["OktaOIDC"] = "OktaOIDC";
ConnectionType["OktaSAML"] = "OktaSAML";
ConnectionType["OneLoginSAML"] = "OneLoginSAML";
ConnectionType["OracleSAML"] = "OracleSAML";
ConnectionType["PingFederateSAML"] = "PingFederateSAML";
ConnectionType["PingOneSAML"] = "PingOneSAML";
ConnectionType["RipplingSAML"] = "RipplingSAML";
ConnectionType["SalesforceOAuth"] = "SalesforceOAuth";
ConnectionType["SalesforceSAML"] = "SalesforceSAML";
ConnectionType["ShibbolethGenericSAML"] = "ShibbolethGenericSAML";
ConnectionType["ShibbolethSAML"] = "ShibbolethSAML";
ConnectionType["SimpleSamlPhpSAML"] = "SimpleSamlPhpSAML";
ConnectionType["VMwareSAML"] = "VMwareSAML";
return ConnectionType;
}({});
// src/factory.ts
function createWorkOS(options) {
return new WorkOS(options);
}
Object.defineProperty(exports, "Actions", {
enumerable: true,
get: function() {
return Actions;
}
});
Object.defineProperty(exports, "ApiKeyRequiredException", {
enumerable: true,
get: function() {
return ApiKeyRequiredException;
}
});
Object.defineProperty(exports, "AuthenticateWithSessionCookieFailureReason", {
enumerable: true,
get: function() {
return AuthenticateWithSessionCookieFailureReason;
}
});
Object.defineProperty(exports, "AuthenticationException", {
enumerable: true,
get: function() {
return AuthenticationException;
}
});
Object.defineProperty(exports, "AutoPaginatable", {
enumerable: true,
get: function() {
return AutoPaginatable;
}
});
Object.defineProperty(exports, "BadRequestException", {
enumerable: true,
get: function() {
return BadRequestException;
}
});
Object.defineProperty(exports, "ConflictException", {
enumerable: true,
get: function() {
return ConflictException;
}
});
Object.defineProperty(exports, "ConnectionType", {
enumerable: true,
get: function() {
return ConnectionType;
}
});
Object.defineProperty(exports, "CookieSession", {
enumerable: true,
get: function() {
return CookieSession;
}
});
Object.defineProperty(exports, "CreateRuleWithTargetsError", {
enumerable: true,
get: function() {
return CreateRuleWithTargetsError;
}
});
Object.defineProperty(exports, "DirectoryUserWithGroupsState", {
enumerable: true,
get: function() {
return DirectoryUserWithGroupsState;
}
});
Object.defineProperty(exports, "DomainDataState", {
enumerable: true,
get: function() {
return DomainDataState;
}
});
Object.defineProperty(exports, "FeatureFlagsRuntimeClient", {
enumerable: true,
get: function() {
return FeatureFlagsRuntimeClient;
}
});
Object.defineProperty(exports, "FetchHttpClient", {
enumerable: true,
get: function() {
return FetchHttpClient;
}
});
Object.defineProperty(exports, "GenerateLinkIntent", {
enumerable: true,
get: function() {
return GenerateLinkIntent;
}
});
Object.defineProperty(exports, "GenericServerException", {
enumerable: true,
get: function() {
return GenericServerException;
}
});
Object.defineProperty(exports, "ItContactIntent", {
enumerable: true,
get: function() {
return ItContactIntent;
}
});
Object.defineProperty(exports, "NoApiKeyProvidedException", {
enumerable: true,
get: function() {
return NoApiKeyProvidedException;
}
});
Object.defineProperty(exports, "NotFoundException", {
enumerable: true,
get: function() {
return NotFoundException;
}
});
Object.defineProperty(exports, "OauthException", {
enumerable: true,
get: function() {
return OauthException;
}
});
Object.defineProperty(exports, "OrganizationDomainState", {
enumerable: true,
get: function() {
return OrganizationDomainState;
}
});
Object.defineProperty(exports, "OrganizationDomainVerificationStrategy", {
enumerable: true,
get: function() {
return OrganizationDomainVerificationStrategy;
}
});
Object.defineProperty(exports, "PKCE", {
enumerable: true,
get: function() {
return PKCE;
}
});
Object.defineProperty(exports, "RateLimitExceededException", {
enumerable: true,
get: function() {
return RateLimitExceededException;
}
});
Object.defineProperty(exports, "RefreshSessionFailureReason", {
enumerable: true,
get: function() {
return RefreshSessionFailureReason;
}
});
Object.defineProperty(exports, "SignatureVerificationException", {
enumerable: true,
get: function() {
return SignatureVerificationException;
}
});
Object.defineProperty(exports, "SubtleCryptoProvider", {
enumerable: true,
get: function() {
return SubtleCryptoProvider;
}
});
Object.defineProperty(exports, "UnauthorizedException", {
enumerable: true,
get: function() {
return UnauthorizedException;
}
});
Object.defineProperty(exports, "UnprocessableEntityException", {
enumerable: true,
get: function() {
return UnprocessableEntityException;
}
});
Object.defineProperty(exports, "UpdateAuditLogsRetentionRetentionPeriod", {
enumerable: true,
get: function() {
return UpdateAuditLogsRetentionRetentionPeriod;
}
});
Object.defineProperty(exports, "Webhooks", {
enumerable: true,
get: function() {
return Webhooks;
}
});
Object.defineProperty(exports, "WorkOS", {
enumerable: true,
get: function() {
return WorkOS;
}
});
Object.defineProperty(exports, "createWorkOS", {
enumerable: true,
get: function() {
return createWorkOS;
}
});
Object.defineProperty(exports, "isAuthenticationErrorData", {
enumerable: true,
get: function() {
return isAuthenticationErrorData;
}
});
Object.defineProperty(exports, "serializeRevokeSessionOptions", {
enumerable: true,
get: function() {
return serializeRevokeSessionOptions;
}
});
//# sourceMappingURL=factory-CnNO67Ux.cjs.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.