@convex-dev/workos-authkit0.3.08.3 kB
import { createFunctionHandle, httpActionGeneric, internalMutationGeneric, } from "convex/server";
import { WorkOS, } from "@workos-inc/node";
import { v } from "convex/values";
import { parse } from "convex-helpers/validators";
import { vEvent } from "../component/lib.js";
const requireEnvVar = (str, onUndefined) => {
if (!str) {
onUndefined();
}
return str;
};
export class AuthKit {
component;
options;
workos;
config;
constructor(component, options) {
this.component = component;
this.options = options;
if (options?.additionalEventTypes?.length) {
console.warn("additionalEventTypes is deprecated and ignored. Select event types in your WorkOS webhook configuration and add a handler for each in events().");
}
const missingEnvVars = [];
const clientId = requireEnvVar(options?.clientId ?? process.env.WORKOS_CLIENT_ID, () => missingEnvVars.push("WORKOS_CLIENT_ID"));
const apiKey = requireEnvVar(options?.apiKey ?? process.env.WORKOS_API_KEY, () => missingEnvVars.push("WORKOS_API_KEY"));
const webhookSecret = requireEnvVar(options?.webhookSecret ?? process.env.WORKOS_WEBHOOK_SECRET, () => missingEnvVars.push("WORKOS_WEBHOOK_SECRET"));
if (missingEnvVars.length > 0) {
throw new Error(`Missing environment variables: ${missingEnvVars.join(", ")}`);
}
this.config = {
...(options ?? {}),
clientId,
apiKey,
webhookSecret,
actionSecret: options?.actionSecret ?? process.env.WORKOS_ACTION_SECRET,
webhookPath: options?.webhookPath ?? "/workos/webhook",
};
this.workos = new WorkOS(this.config.apiKey, {
clientId: this.config.clientId,
apiHostname: this.config.apiHostname,
});
}
getAuthConfigProviders = () => {
const apiBaseUrl = `https://${this.config.apiHostname ?? "api.workos.com"}`;
return [
{
type: "customJwt",
issuer: `${apiBaseUrl}/`,
algorithm: "RS256",
jwks: `https://api.workos.com/sso/jwks/${this.config.clientId}`,
applicationID: this.config.clientId,
},
{
type: "customJwt",
issuer: `${apiBaseUrl}/user_management/${this.config.clientId}`,
algorithm: "RS256",
jwks: `https://api.workos.com/sso/jwks/${this.config.clientId}`,
},
];
};
async getAuthUser(ctx) {
const identity = await ctx.auth.getUserIdentity();
if (!identity) {
return null;
}
return ctx.runQuery(this.component.lib.getAuthUser, {
id: identity.subject,
});
}
events(opts) {
return {
authKitEvent: internalMutationGeneric({
args: {
event: v.string(),
data: v.record(v.string(), v.any()),
},
returns: v.null(),
handler: async (ctx, args) => {
const handler = opts[args.event];
if (handler) {
await handler(ctx, args);
}
},
}),
};
}
actions(opts) {
return {
authKitAction: internalMutationGeneric({
args: {
action: v.record(v.string(), v.any()),
},
returns: v.record(v.string(), v.any()),
handler: async (ctx, args) => {
const resp = {
type: args.action.object === "authentication_action_context"
? "authentication"
: "user_registration",
timestamp: new Date().getTime(),
};
const allow = () => ({ ...resp, verdict: "Allow" });
const deny = (errorMessage) => ({
...resp,
verdict: "Deny",
errorMessage,
});
const responsePayload = await opts[(args.action.object === "authentication_action_context"
? "authentication"
: "userRegistration")](ctx, args.action, {
allow,
deny,
});
return responsePayload;
},
}),
};
}
utils() {
return {
backfillUsers: internalMutationGeneric({
args: {},
returns: v.null(),
handler: async (ctx) => {
const onEventHandle = this.config.authFunctions?.authKitEvent
? await createFunctionHandle(this.config.authFunctions.authKitEvent)
: undefined;
await ctx.runMutation(this.component.backfill.startBackfill, {
apiKey: this.config.apiKey,
onEventHandle,
logLevel: this.config.logLevel,
});
return null;
},
}),
};
}
registerRoutes(http) {
http.route({
path: "/workos/webhook",
method: "POST",
handler: httpActionGeneric(async (ctx, request) => {
const payload = await request.text();
const sigHeader = request.headers.get("workos-signature");
if (!sigHeader) {
throw new Error("No signature header");
}
const secret = this.config.webhookSecret;
if (!secret) {
throw new Error("webhook secret is not set");
}
const event = await this.workos.webhooks.constructEvent({
payload: JSON.parse(payload),
sigHeader: sigHeader,
secret,
});
if (this.config.logLevel === "DEBUG") {
console.log("received event", event);
}
await ctx.runMutation(this.component.lib.onWebhookEvent, {
event: parse(vEvent, event),
onEventHandle: this.config.authFunctions?.authKitEvent
? await createFunctionHandle(this.config.authFunctions.authKitEvent)
: undefined,
logLevel: this.config.logLevel,
});
return new Response("OK", { status: 200 });
}),
});
http.route({
path: "/workos/action",
method: "POST",
handler: httpActionGeneric(async (ctx, request) => {
const payload = await request.text();
const sigHeader = request.headers.get("workos-signature");
if (!sigHeader) {
throw new Error("No signature header");
}
const secret = this.config.actionSecret;
if (!secret) {
throw new Error("webhook secret is not set");
}
const action = await this.workos.actions.constructAction({
payload: JSON.parse(payload),
sigHeader: sigHeader,
secret,
});
if (this.config.logLevel === "DEBUG") {
console.log("received action", action);
}
if (!this.config.authFunctions?.authKitAction) {
throw new Error("authFunctions not set in AuthKit component configuration, or no authKitAction function exported");
}
const responsePayload = await ctx.runMutation(
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
this.config.authFunctions?.authKitAction, {
action,
});
const response = await this.workos.actions.signResponse(responsePayload,
// We check for this in the constructor
this.config.actionSecret);
return new Response(JSON.stringify(response), { status: 200 });
}),
});
}
}
//# sourceMappingURL=index.js.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.