mirror of
https://github.com/fosrl/pangolin.git
synced 2026-08-15 16:59:35 +02:00
send email upon generate virtual api key
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
import React from "react";
|
||||
import { Body, Head, Html, Preview, Tailwind } from "@react-email/components";
|
||||
import { themeColors } from "./lib/theme";
|
||||
import {
|
||||
EmailContainer,
|
||||
EmailFooter,
|
||||
EmailGreeting,
|
||||
EmailInfoSection,
|
||||
EmailLetterHead,
|
||||
EmailSection,
|
||||
EmailSignature,
|
||||
EmailText
|
||||
} from "./components/Email";
|
||||
|
||||
type VirtualApiKeyGeneratedProps = {
|
||||
orgName: string;
|
||||
keyName: string | null;
|
||||
credential: string;
|
||||
resourceUrls: string[];
|
||||
hasMoreResources: boolean;
|
||||
};
|
||||
|
||||
export const VirtualApiKeyGenerated = ({
|
||||
orgName,
|
||||
keyName,
|
||||
credential,
|
||||
resourceUrls,
|
||||
hasMoreResources
|
||||
}: VirtualApiKeyGeneratedProps) => {
|
||||
const previewText = `A virtual API key for ${orgName} has been shared with you`;
|
||||
|
||||
return (
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind config={themeColors}>
|
||||
<Body className="font-sans bg-gray-50">
|
||||
<EmailContainer>
|
||||
<EmailLetterHead />
|
||||
|
||||
<EmailGreeting>Hi there,</EmailGreeting>
|
||||
|
||||
<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.
|
||||
</EmailText>
|
||||
|
||||
<EmailSection>
|
||||
<EmailText>Your virtual API 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>
|
||||
|
||||
<EmailInfoSection
|
||||
title="Key details"
|
||||
items={[
|
||||
{
|
||||
label: "Organization",
|
||||
value: orgName
|
||||
},
|
||||
...(keyName
|
||||
? [
|
||||
{
|
||||
label: "Name",
|
||||
value: keyName
|
||||
}
|
||||
]
|
||||
: [])
|
||||
]}
|
||||
/>
|
||||
|
||||
{resourceUrls.length > 0 && (
|
||||
<>
|
||||
<EmailText>
|
||||
This key can be used to authenticate to the
|
||||
following AI gateway resources:
|
||||
</EmailText>
|
||||
<div className="px-6 pb-2">
|
||||
{resourceUrls.map((url) => (
|
||||
<p
|
||||
key={url}
|
||||
className="text-base text-gray-700 leading-relaxed"
|
||||
>
|
||||
<a
|
||||
href={url}
|
||||
className="text-primary font-medium break-all"
|
||||
>
|
||||
{url}
|
||||
</a>
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{hasMoreResources && (
|
||||
<EmailText>
|
||||
Contact your administrator to get the
|
||||
full list.
|
||||
</EmailText>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<EmailFooter>
|
||||
<EmailSignature />
|
||||
</EmailFooter>
|
||||
</EmailContainer>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
</Html>
|
||||
);
|
||||
};
|
||||
|
||||
export default VirtualApiKeyGenerated;
|
||||
@@ -0,0 +1,161 @@
|
||||
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 VirtualApiKeyGenerated from "@server/emails/templates/VirtualApiKeyGenerated";
|
||||
import { formatVirtualApiKeyCredential } from "@server/lib/virtualApiKey";
|
||||
|
||||
const EMAIL_GATEWAY_URL_LIMIT = 5;
|
||||
|
||||
async function listVirtualApiKeyGatewayUrls(params: {
|
||||
orgId: string;
|
||||
allResources: boolean;
|
||||
virtualApiKeyId: string;
|
||||
}): Promise<{ urls: string[]; hasMore: boolean }> {
|
||||
const rows = params.allResources
|
||||
? await db
|
||||
.select({
|
||||
fullDomain: resources.fullDomain,
|
||||
ssl: resources.ssl
|
||||
})
|
||||
.from(resources)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.orgId, params.orgId),
|
||||
eq(resources.mode, "inference")
|
||||
)
|
||||
)
|
||||
.orderBy(asc(resources.name))
|
||||
.limit(EMAIL_GATEWAY_URL_LIMIT + 1)
|
||||
: await db
|
||||
.select({
|
||||
fullDomain: resources.fullDomain,
|
||||
ssl: resources.ssl
|
||||
})
|
||||
.from(virtualApiKeyResources)
|
||||
.innerJoin(
|
||||
resources,
|
||||
eq(virtualApiKeyResources.resourceId, resources.resourceId)
|
||||
)
|
||||
.where(
|
||||
eq(
|
||||
virtualApiKeyResources.virtualApiKeyId,
|
||||
params.virtualApiKeyId
|
||||
)
|
||||
)
|
||||
.orderBy(asc(resources.name))
|
||||
.limit(EMAIL_GATEWAY_URL_LIMIT + 1);
|
||||
|
||||
const urls = rows
|
||||
.map((row) =>
|
||||
row.fullDomain
|
||||
? `${row.ssl ? "https" : "http"}://${row.fullDomain}`
|
||||
: null
|
||||
)
|
||||
.filter((url): url is string => Boolean(url));
|
||||
|
||||
return {
|
||||
urls: urls.slice(0, EMAIL_GATEWAY_URL_LIMIT),
|
||||
hasMore: rows.length > EMAIL_GATEWAY_URL_LIMIT
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolveVirtualApiKeyEmailRecipients(params: {
|
||||
sendEmail: boolean;
|
||||
sendToAttributedUser: boolean;
|
||||
userId: string | null | undefined;
|
||||
emails: string[];
|
||||
}): Promise<
|
||||
{ ok: true; recipients: string[] } | { ok: false; message: string }
|
||||
> {
|
||||
if (!params.sendEmail) {
|
||||
return { ok: true, recipients: [] };
|
||||
}
|
||||
|
||||
if (!config.getRawConfig().email) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Email is not configured on this server"
|
||||
};
|
||||
}
|
||||
|
||||
const recipients = new Set(
|
||||
params.emails.map((email) => email.trim().toLowerCase()).filter(Boolean)
|
||||
);
|
||||
|
||||
if (params.sendToAttributedUser) {
|
||||
if (!params.userId) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Associate a user to email the key to that user"
|
||||
};
|
||||
}
|
||||
|
||||
const [user] = await db
|
||||
.select({ email: users.email })
|
||||
.from(users)
|
||||
.where(eq(users.userId, params.userId))
|
||||
.limit(1);
|
||||
|
||||
if (!user?.email) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "The associated user does not have an email address"
|
||||
};
|
||||
}
|
||||
|
||||
recipients.add(user.email.toLowerCase());
|
||||
}
|
||||
|
||||
if (recipients.size === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Select at least one email recipient"
|
||||
};
|
||||
}
|
||||
|
||||
return { ok: true, recipients: [...recipients] };
|
||||
}
|
||||
|
||||
export async function sendVirtualApiKeyEmails(params: {
|
||||
recipients: string[];
|
||||
orgName: string;
|
||||
orgId: string;
|
||||
keyName: string | null;
|
||||
virtualApiKeyId: string;
|
||||
secret: string;
|
||||
allResources: boolean;
|
||||
}): Promise<void> {
|
||||
if (params.recipients.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const credential = formatVirtualApiKeyCredential(
|
||||
params.virtualApiKeyId,
|
||||
params.secret
|
||||
);
|
||||
const { urls, hasMore } = await listVirtualApiKeyGatewayUrls({
|
||||
orgId: params.orgId,
|
||||
allResources: params.allResources,
|
||||
virtualApiKeyId: params.virtualApiKeyId
|
||||
});
|
||||
const from = config.getNoReplyEmail();
|
||||
const subject = `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
|
||||
}),
|
||||
{
|
||||
to,
|
||||
from,
|
||||
subject
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, userOrgs, virtualApiKeys } from "@server/db";
|
||||
import { db, orgs, userOrgs, virtualApiKeys } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -18,6 +18,10 @@ import {
|
||||
} from "@server/lib/virtualApiKey";
|
||||
import type { CreateOrEditVirtualApiKeyResponse } from "@server/routers/virtualApiKey/types";
|
||||
import { createVirtualApiKeyBodySchema } from "@server/routers/virtualApiKey/validation";
|
||||
import {
|
||||
resolveVirtualApiKeyEmailRecipients,
|
||||
sendVirtualApiKeyEmails
|
||||
} from "@server/lib/sendVirtualApiKeyEmail";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty()
|
||||
@@ -78,7 +82,10 @@ export async function createVirtualApiKey(
|
||||
userId,
|
||||
allResources,
|
||||
resourceIds,
|
||||
validForSeconds
|
||||
validForSeconds,
|
||||
sendEmail: doEmail,
|
||||
sendToAttributedUser,
|
||||
emails
|
||||
} = parsedBody.data;
|
||||
|
||||
if (req.user && orgId && orgId !== req.userOrgId) {
|
||||
@@ -121,6 +128,18 @@ export async function createVirtualApiKey(
|
||||
);
|
||||
}
|
||||
|
||||
const emailRecipients = await resolveVirtualApiKeyEmailRecipients({
|
||||
sendEmail: doEmail,
|
||||
sendToAttributedUser,
|
||||
userId,
|
||||
emails
|
||||
});
|
||||
if (!emailRecipients.ok) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, emailRecipients.message)
|
||||
);
|
||||
}
|
||||
|
||||
const minted = mintVirtualApiKeySecret();
|
||||
const expiresAt = validForSeconds
|
||||
? createDate(new TimeSpan(validForSeconds, "s")).getTime()
|
||||
@@ -156,6 +175,24 @@ export async function createVirtualApiKey(
|
||||
return row;
|
||||
});
|
||||
|
||||
if (emailRecipients.recipients.length > 0) {
|
||||
const [org] = await db
|
||||
.select()
|
||||
.from(orgs)
|
||||
.where(eq(orgs.orgId, orgId))
|
||||
.limit(1);
|
||||
|
||||
await sendVirtualApiKeyEmails({
|
||||
recipients: emailRecipients.recipients,
|
||||
orgName: org?.name || orgId,
|
||||
orgId,
|
||||
keyName: created.name,
|
||||
virtualApiKeyId: created.virtualApiKeyId,
|
||||
secret: minted.secret,
|
||||
allResources: created.allResources
|
||||
});
|
||||
}
|
||||
|
||||
return response<CreateOrEditVirtualApiKeyResponse>(res, {
|
||||
data: {
|
||||
virtualApiKey: {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
orgs,
|
||||
userOrgs,
|
||||
virtualApiKeyResources,
|
||||
virtualApiKeys
|
||||
@@ -16,11 +17,16 @@ import { and, eq } from "drizzle-orm";
|
||||
import { createDate, TimeSpan } from "oslo";
|
||||
import {
|
||||
assertManualKeyResourcesInOrg,
|
||||
decryptVirtualApiKeyToken,
|
||||
replaceVirtualApiKeyResources,
|
||||
toPublicVirtualApiKey
|
||||
} from "@server/lib/virtualApiKey";
|
||||
import type { CreateOrEditVirtualApiKeyResponse } from "@server/routers/virtualApiKey/types";
|
||||
import { updateVirtualApiKeyBodySchema } from "@server/routers/virtualApiKey/validation";
|
||||
import {
|
||||
resolveVirtualApiKeyEmailRecipients,
|
||||
sendVirtualApiKeyEmails
|
||||
} from "@server/lib/sendVirtualApiKeyEmail";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
virtualApiKeyId: z.string().nonempty()
|
||||
@@ -146,6 +152,20 @@ export async function updateVirtualApiKey(
|
||||
}
|
||||
}
|
||||
|
||||
const nextUserId =
|
||||
body.userId !== undefined ? body.userId : existing.userId;
|
||||
const emailRecipients = await resolveVirtualApiKeyEmailRecipients({
|
||||
sendEmail: body.sendEmail,
|
||||
sendToAttributedUser: body.sendToAttributedUser,
|
||||
userId: nextUserId,
|
||||
emails: body.emails
|
||||
});
|
||||
if (!emailRecipients.ok) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, emailRecipients.message)
|
||||
);
|
||||
}
|
||||
|
||||
const updates: Partial<typeof virtualApiKeys.$inferInsert> = {};
|
||||
|
||||
if (body.name !== undefined) {
|
||||
@@ -192,6 +212,24 @@ export async function updateVirtualApiKey(
|
||||
return row;
|
||||
});
|
||||
|
||||
if (emailRecipients.recipients.length > 0) {
|
||||
const [org] = await db
|
||||
.select()
|
||||
.from(orgs)
|
||||
.where(eq(orgs.orgId, existing.orgId))
|
||||
.limit(1);
|
||||
|
||||
await sendVirtualApiKeyEmails({
|
||||
recipients: emailRecipients.recipients,
|
||||
orgName: org?.name || existing.orgId,
|
||||
orgId: existing.orgId,
|
||||
keyName: updated.name,
|
||||
virtualApiKeyId: updated.virtualApiKeyId,
|
||||
secret: decryptVirtualApiKeyToken(updated.token),
|
||||
allResources: updated.allResources
|
||||
});
|
||||
}
|
||||
|
||||
const resourceRows = await db
|
||||
.select({ resourceId: virtualApiKeyResources.resourceId })
|
||||
.from(virtualApiKeyResources)
|
||||
|
||||
@@ -4,6 +4,43 @@ export const virtualApiKeyResourceIdsSchema = z
|
||||
.array(z.coerce.number().int().positive())
|
||||
.optional();
|
||||
|
||||
const virtualApiKeyEmailFieldsSchema = {
|
||||
sendEmail: z.boolean().optional().default(false),
|
||||
sendToAttributedUser: z.boolean().optional().default(false),
|
||||
emails: z.array(z.email().toLowerCase()).max(20).optional().default([])
|
||||
};
|
||||
|
||||
function refineVirtualApiKeyEmailFields(
|
||||
data: {
|
||||
sendEmail: boolean;
|
||||
sendToAttributedUser: boolean;
|
||||
emails: string[];
|
||||
userId?: string | null;
|
||||
},
|
||||
ctx: z.RefinementCtx
|
||||
) {
|
||||
if (!data.sendEmail) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.sendToAttributedUser && data.emails.length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"Select the associated user or add at least one email address",
|
||||
path: ["sendEmail"]
|
||||
});
|
||||
}
|
||||
|
||||
if (data.sendToAttributedUser && !data.userId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Associate a user to email the key to that user",
|
||||
path: ["sendToAttributedUser"]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const createVirtualApiKeyBodySchema = z
|
||||
.strictObject({
|
||||
name: z.string().nonempty(),
|
||||
@@ -11,7 +48,8 @@ export const createVirtualApiKeyBodySchema = z
|
||||
userId: z.string().optional().nullable(),
|
||||
allResources: z.boolean().optional().default(false),
|
||||
resourceIds: virtualApiKeyResourceIdsSchema,
|
||||
validForSeconds: z.int().positive().optional()
|
||||
validForSeconds: z.int().positive().optional(),
|
||||
...virtualApiKeyEmailFieldsSchema
|
||||
})
|
||||
.refine(
|
||||
(data) => data.allResources || (data.resourceIds?.length ?? 0) > 0,
|
||||
@@ -20,13 +58,30 @@ export const createVirtualApiKeyBodySchema = z
|
||||
"Select at least one public inference resource, or enable all public inference resources",
|
||||
path: ["resourceIds"]
|
||||
}
|
||||
);
|
||||
)
|
||||
.superRefine(refineVirtualApiKeyEmailFields);
|
||||
|
||||
export const updateVirtualApiKeyBodySchema = z.strictObject({
|
||||
name: z.string().nonempty().optional(),
|
||||
description: z.string().optional().nullable(),
|
||||
userId: z.string().optional().nullable(),
|
||||
allResources: z.boolean().optional(),
|
||||
resourceIds: virtualApiKeyResourceIdsSchema,
|
||||
validForSeconds: z.int().positive().optional().nullable()
|
||||
});
|
||||
export const updateVirtualApiKeyBodySchema = z
|
||||
.strictObject({
|
||||
name: z.string().nonempty().optional(),
|
||||
description: z.string().optional().nullable(),
|
||||
userId: z.string().optional().nullable(),
|
||||
allResources: z.boolean().optional(),
|
||||
resourceIds: virtualApiKeyResourceIdsSchema,
|
||||
validForSeconds: z.int().positive().optional().nullable(),
|
||||
...virtualApiKeyEmailFieldsSchema
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (!data.sendEmail) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.sendToAttributedUser && data.emails.length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"Select the associated user or add at least one email address",
|
||||
path: ["sendEmail"]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user