mirror of
https://github.com/fosrl/pangolin.git
synced 2026-08-15 00:39:43 +02:00
option to send identity keys in email
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import React from "react";
|
||||
import { Body, Head, Html, Preview, Tailwind } from "@react-email/components";
|
||||
import { themeColors } from "./lib/theme";
|
||||
import {
|
||||
EmailContainer,
|
||||
EmailFooter,
|
||||
EmailGreeting,
|
||||
EmailHeading,
|
||||
EmailInfoSection,
|
||||
EmailLetterHead,
|
||||
EmailSection,
|
||||
EmailSignature,
|
||||
EmailText
|
||||
} from "./components/Email";
|
||||
|
||||
type IdentityApiKeyGeneratedProps = {
|
||||
orgName: string;
|
||||
accountLabel?: string | null;
|
||||
credential: string;
|
||||
resourceUrls: string[];
|
||||
hasMoreResources: boolean;
|
||||
};
|
||||
|
||||
export const IdentityApiKeyGenerated = ({
|
||||
orgName,
|
||||
accountLabel,
|
||||
credential,
|
||||
resourceUrls,
|
||||
hasMoreResources
|
||||
}: IdentityApiKeyGeneratedProps) => {
|
||||
const previewText = `Your personal identity key for ${orgName}`;
|
||||
|
||||
return (
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind config={themeColors}>
|
||||
<Body className="font-sans bg-gray-50">
|
||||
<EmailContainer>
|
||||
<EmailLetterHead />
|
||||
|
||||
<EmailGreeting>Hi there,</EmailGreeting>
|
||||
|
||||
<EmailText>
|
||||
This is your personal identity key for{" "}
|
||||
<strong>{orgName}</strong>. It belongs to your
|
||||
account and identifies you when you use public AI
|
||||
gateways.
|
||||
</EmailText>
|
||||
|
||||
<EmailText>
|
||||
Use it with resources your administrator has granted
|
||||
you, or that your role has access to. Treat this key
|
||||
like a password and do not share it.
|
||||
</EmailText>
|
||||
|
||||
<EmailSection>
|
||||
<EmailText>Your identity key:</EmailText>
|
||||
<div className="inline-block max-w-full">
|
||||
<div className="bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 mx-auto text-left">
|
||||
<span className="text-sm font-mono text-gray-900 break-all">
|
||||
{credential}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</EmailSection>
|
||||
|
||||
<EmailFooter>
|
||||
<EmailSignature />
|
||||
</EmailFooter>
|
||||
</EmailContainer>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
</Html>
|
||||
);
|
||||
};
|
||||
|
||||
export default IdentityApiKeyGenerated;
|
||||
@@ -42,8 +42,9 @@ export const VirtualApiKeyGenerated = ({
|
||||
|
||||
<EmailText>
|
||||
A virtual API key for <strong>{orgName}</strong> has
|
||||
been shared with you. Treat this key like a password
|
||||
and do not share it.
|
||||
been shared with you. This key grants access to the
|
||||
public AI gateways it was created for. Treat this
|
||||
key like a password and do not share it.
|
||||
</EmailText>
|
||||
|
||||
<EmailSection>
|
||||
|
||||
@@ -18,7 +18,7 @@ export function EmailLetterHead() {
|
||||
<Img
|
||||
src="https://fossorial-public-assets.s3.us-east-1.amazonaws.com/word_mark_black.png"
|
||||
alt="Pangolin Logo"
|
||||
width="180"
|
||||
width="135"
|
||||
height="auto"
|
||||
className="mx-auto"
|
||||
/>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { db, resources, users, virtualApiKeyResources } from "@server/db";
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import config from "@server/lib/config";
|
||||
import { sendEmail } from "@server/emails";
|
||||
import IdentityApiKeyGenerated from "@server/emails/templates/IdentityApiKeyGenerated";
|
||||
import VirtualApiKeyGenerated from "@server/emails/templates/VirtualApiKeyGenerated";
|
||||
import { formatVirtualApiKeyCredential } from "@server/lib/virtualApiKey";
|
||||
|
||||
@@ -60,6 +61,17 @@ async function listVirtualApiKeyGatewayUrls(params: {
|
||||
};
|
||||
}
|
||||
|
||||
export async function listOrgInferenceGatewayUrls(orgId: string): Promise<{
|
||||
urls: string[];
|
||||
hasMore: boolean;
|
||||
}> {
|
||||
return listVirtualApiKeyGatewayUrls({
|
||||
orgId,
|
||||
allResources: true,
|
||||
virtualApiKeyId: ""
|
||||
});
|
||||
}
|
||||
|
||||
export async function resolveVirtualApiKeyEmailRecipients(params: {
|
||||
sendEmail: boolean;
|
||||
sendToAttributedUser: boolean;
|
||||
@@ -125,6 +137,9 @@ export async function sendVirtualApiKeyEmails(params: {
|
||||
virtualApiKeyId: string;
|
||||
secret: string;
|
||||
allResources: boolean;
|
||||
isIdentityKey?: boolean;
|
||||
accountLabel?: string | null;
|
||||
gatewayUrls?: { urls: string[]; hasMore: boolean };
|
||||
}): Promise<void> {
|
||||
if (params.recipients.length === 0) {
|
||||
return;
|
||||
@@ -134,23 +149,35 @@ export async function sendVirtualApiKeyEmails(params: {
|
||||
params.virtualApiKeyId,
|
||||
params.secret
|
||||
);
|
||||
const { urls, hasMore } = await listVirtualApiKeyGatewayUrls({
|
||||
orgId: params.orgId,
|
||||
allResources: params.allResources,
|
||||
virtualApiKeyId: params.virtualApiKeyId
|
||||
});
|
||||
const { urls, hasMore } =
|
||||
params.gatewayUrls ??
|
||||
(await listVirtualApiKeyGatewayUrls({
|
||||
orgId: params.orgId,
|
||||
allResources: params.allResources,
|
||||
virtualApiKeyId: params.virtualApiKeyId
|
||||
}));
|
||||
const from = config.getNoReplyEmail();
|
||||
const subject = `Virtual API key for ${params.orgName}`;
|
||||
const subject = params.isIdentityKey
|
||||
? `Your identity key for ${params.orgName}`
|
||||
: `Virtual API key for ${params.orgName}`;
|
||||
|
||||
for (const to of params.recipients) {
|
||||
await sendEmail(
|
||||
VirtualApiKeyGenerated({
|
||||
orgName: params.orgName,
|
||||
keyName: params.keyName,
|
||||
credential,
|
||||
resourceUrls: urls,
|
||||
hasMoreResources: hasMore
|
||||
}),
|
||||
params.isIdentityKey
|
||||
? IdentityApiKeyGenerated({
|
||||
orgName: params.orgName,
|
||||
accountLabel: params.accountLabel,
|
||||
credential,
|
||||
resourceUrls: urls,
|
||||
hasMoreResources: hasMore
|
||||
})
|
||||
: VirtualApiKeyGenerated({
|
||||
orgName: params.orgName,
|
||||
keyName: params.keyName,
|
||||
credential,
|
||||
resourceUrls: urls,
|
||||
hasMoreResources: hasMore
|
||||
}),
|
||||
{
|
||||
to,
|
||||
from,
|
||||
|
||||
@@ -1735,6 +1735,15 @@ authenticated.get(
|
||||
virtualApiKey.listVirtualApiKeys
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/org/:orgId/virtual-api-keys/email-identity-keys",
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.getVirtualApiKey),
|
||||
virtualApiKey.emailIdentityKeysRateLimit,
|
||||
logActionAudit(ActionsEnum.getVirtualApiKey),
|
||||
virtualApiKey.emailIdentityKeys
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/my-virtual-api-keys",
|
||||
verifyOrgAccess,
|
||||
|
||||
@@ -1769,6 +1769,15 @@ authenticated.get(
|
||||
virtualApiKey.listVirtualApiKeys
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/org/:orgId/virtual-api-keys/email-identity-keys",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.getVirtualApiKey),
|
||||
virtualApiKey.emailIdentityKeysRateLimit,
|
||||
logActionAudit(ActionsEnum.getVirtualApiKey),
|
||||
virtualApiKey.emailIdentityKeys
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyApiKeyVirtualApiKeyAccess,
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, orgs, roles, userOrgRoles, userOrgs, users } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import config from "@server/lib/config";
|
||||
import { getOrCreateUserVirtualApiKey } from "@server/lib/virtualApiKey";
|
||||
import {
|
||||
sendVirtualApiKeyEmails,
|
||||
listOrgInferenceGatewayUrls
|
||||
} from "@server/lib/sendVirtualApiKeyEmail";
|
||||
import type { EmailIdentityKeysResponse } from "@server/routers/virtualApiKey/types";
|
||||
import rateLimit, { ipKeyGenerator } from "express-rate-limit";
|
||||
import { createStore } from "#dynamic/lib/rateLimitStore";
|
||||
|
||||
const EMAIL_IDENTITY_KEYS_WINDOW_MINUTES = 15;
|
||||
const EMAIL_IDENTITY_KEYS_MAX = 3;
|
||||
|
||||
export const emailIdentityKeysRateLimit = rateLimit({
|
||||
windowMs: EMAIL_IDENTITY_KEYS_WINDOW_MINUTES * 60 * 1000,
|
||||
max: EMAIL_IDENTITY_KEYS_MAX,
|
||||
keyGenerator: (req) => {
|
||||
const actor =
|
||||
req.user?.userId ||
|
||||
req.apiKey?.apiKeyId ||
|
||||
ipKeyGenerator(req.ip || "");
|
||||
const orgId =
|
||||
typeof req.params.orgId === "string" ? req.params.orgId : "";
|
||||
return `emailIdentityKeys:${actor}:${orgId}`;
|
||||
},
|
||||
handler: (_req, _res, next) => {
|
||||
const message = `You can only email identity keys ${EMAIL_IDENTITY_KEYS_MAX} times every ${EMAIL_IDENTITY_KEYS_WINDOW_MINUTES} minutes. Please try again later.`;
|
||||
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
|
||||
},
|
||||
store: createStore()
|
||||
});
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty()
|
||||
});
|
||||
|
||||
const bodySchema = z
|
||||
.strictObject({
|
||||
sendToAll: z.boolean().optional().default(false),
|
||||
userIds: z.array(z.string().nonempty()).optional().default([]),
|
||||
roleIds: z.array(z.number().int().positive()).optional().default([])
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (
|
||||
!data.sendToAll &&
|
||||
data.userIds.length === 0 &&
|
||||
data.roleIds.length === 0
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"Select at least one user or role, or send to all users",
|
||||
path: ["userIds"]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/org/{orgId}/virtual-api-keys/email-identity-keys",
|
||||
description:
|
||||
"Email identity virtual API keys to selected organization members and roles, or to all members.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: bodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function emailIdentityKeys(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!config.getRawConfig().email) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email is not configured on this server"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
const { sendToAll, userIds, roleIds } = parsedBody.data;
|
||||
|
||||
if (req.user && orgId && orgId !== req.userOrgId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have access to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
const uniqueRoleIds = [...new Set(roleIds)];
|
||||
|
||||
if (!sendToAll && uniqueRoleIds.length > 0) {
|
||||
const orgRoles = await db
|
||||
.select({ roleId: roles.roleId })
|
||||
.from(roles)
|
||||
.where(
|
||||
and(
|
||||
eq(roles.orgId, orgId),
|
||||
inArray(roles.roleId, uniqueRoleIds)
|
||||
)
|
||||
);
|
||||
|
||||
if (orgRoles.length !== uniqueRoleIds.length) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"One or more roles are invalid for this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let targetUserIds: string[] | null = null;
|
||||
if (!sendToAll) {
|
||||
let roleUserIds: string[] = [];
|
||||
if (uniqueRoleIds.length > 0) {
|
||||
const roleMembers = await db
|
||||
.select({ userId: userOrgRoles.userId })
|
||||
.from(userOrgRoles)
|
||||
.where(
|
||||
and(
|
||||
eq(userOrgRoles.orgId, orgId),
|
||||
inArray(userOrgRoles.roleId, uniqueRoleIds)
|
||||
)
|
||||
);
|
||||
roleUserIds = roleMembers.map((row) => row.userId);
|
||||
}
|
||||
|
||||
targetUserIds = [...new Set([...uniqueUserIds, ...roleUserIds])];
|
||||
if (targetUserIds.length === 0) {
|
||||
return response<EmailIdentityKeysResponse>(res, {
|
||||
data: { sent: 0, skipped: 0 },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Identity keys emailed successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const memberConditions = [eq(userOrgs.orgId, orgId)];
|
||||
if (targetUserIds) {
|
||||
memberConditions.push(inArray(users.userId, targetUserIds));
|
||||
}
|
||||
|
||||
const members = await db
|
||||
.select({ user: users })
|
||||
.from(users)
|
||||
.innerJoin(userOrgs, eq(userOrgs.userId, users.userId))
|
||||
.where(and(...memberConditions));
|
||||
|
||||
if (!sendToAll && uniqueUserIds.length > 0) {
|
||||
const foundIds = new Set(members.map((row) => row.user.userId));
|
||||
if (uniqueUserIds.some((id) => !foundIds.has(id))) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"One or more users are not members of this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const [org] = await db
|
||||
.select()
|
||||
.from(orgs)
|
||||
.where(eq(orgs.orgId, orgId))
|
||||
.limit(1);
|
||||
|
||||
const orgName = org?.name || orgId;
|
||||
const gatewayUrls = await listOrgInferenceGatewayUrls(orgId);
|
||||
let sent = 0;
|
||||
let skipped = 0;
|
||||
|
||||
for (const { user } of members) {
|
||||
if (!user.email) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const { key, secret } = await getOrCreateUserVirtualApiKey({
|
||||
orgId,
|
||||
user,
|
||||
createdByUserId: req.user?.userId ?? null
|
||||
});
|
||||
|
||||
await sendVirtualApiKeyEmails({
|
||||
recipients: [user.email],
|
||||
orgName,
|
||||
orgId,
|
||||
keyName: key.name,
|
||||
virtualApiKeyId: key.virtualApiKeyId,
|
||||
secret,
|
||||
allResources: true,
|
||||
isIdentityKey: true,
|
||||
accountLabel: user.email || user.name || user.username,
|
||||
gatewayUrls
|
||||
});
|
||||
sent += 1;
|
||||
}
|
||||
|
||||
return response<EmailIdentityKeysResponse>(res, {
|
||||
data: { sent, skipped },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Identity keys emailed successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,4 +5,5 @@ export * from "./getVirtualApiKey";
|
||||
export * from "./getMyVirtualApiKey";
|
||||
export * from "./updateVirtualApiKey";
|
||||
export * from "./deleteVirtualApiKey";
|
||||
export * from "./emailIdentityKeys";
|
||||
export * from "./types";
|
||||
|
||||
@@ -28,3 +28,8 @@ export type ListMyVirtualApiKeysResponse = {
|
||||
export type GetMyVirtualApiKeyResponse = {
|
||||
virtualApiKey: VirtualApiKeyWithResources;
|
||||
};
|
||||
|
||||
export type EmailIdentityKeysResponse = {
|
||||
sent: number;
|
||||
skipped: number;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user