Compare commits

...

20 Commits

Author SHA1 Message Date
Fred KISSIE ea740e12d1 💄 nice little animation on alert rule field 2026-08-14 19:07:13 +02:00
Fred KISSIE 46f341f7fd 🏷️ fix types 2026-08-13 19:26:15 +02:00
Fred KISSIE 9bb413bb1e ♻️ refactor 2026-08-13 19:23:39 +02:00
Fred KISSIE 2878d5690c 💬 update texts for heading & trigger 2026-08-13 19:19:55 +02:00
Fred KISSIE 1143404a65 💄alert rule popover 2026-08-13 19:15:23 +02:00
Fred KISSIE 49b4fcf063 ♻️ refactor 2026-08-12 21:36:40 +02:00
Fred KISSIE 4b61e12ca6 ♻️ trigger alert correctly 2026-08-12 18:56:56 +02:00
Fred KISSIE c6bd657ee6 send webhook action 2026-08-12 18:48:14 +02:00
Fred KISSIE 21032bc22b test alert email works 2026-08-11 22:25:26 +02:00
Fred KISSIE 899c47e9a3 🚧 write process test alert function 2026-08-11 20:52:13 +02:00
Fred KISSIE 403b8a12e4 🚧 wip 2026-08-07 20:57:54 +02:00
Fred KISSIE 3f305e4d5c 🚧 process test alert 2026-08-07 20:52:25 +02:00
Fred KISSIE 6689a8d93e 🚧 wip: test alert rule 2026-08-07 19:05:28 +02:00
Owen e91c344e64 Update link to be correct 2026-08-07 10:21:15 -04:00
miloschwartz 4048fa274a fix non admins cant see private resources details in launcher 2026-08-06 12:32:19 -04:00
miloschwartz 82b86263dc allow chars in 2fa input form closes #3532 2026-08-06 11:39:06 -04:00
Owen 835a30cffe Show the cert status of the namespace domains properly 2026-08-04 17:44:34 -04:00
Owen 18b90da6ab Merge branch 'main' into dev 2026-08-04 17:22:32 -04:00
Owen f079714caf Dont redirect when the browser agent is not real 2026-08-04 10:07:52 -04:00
Owen efd2792197 bump default rate limit 2026-08-03 17:57:36 -04:00
28 changed files with 854 additions and 108 deletions
+8
View File
@@ -1695,6 +1695,8 @@
"alertingRuleSaved": "Alert rule saved", "alertingRuleSaved": "Alert rule saved",
"alertingRuleSavedCreatedDescription": "Your new alert rule was created. You can keep editing it on this page.", "alertingRuleSavedCreatedDescription": "Your new alert rule was created. You can keep editing it on this page.",
"alertingRuleSavedUpdatedDescription": "Your changes to this alert rule were saved.", "alertingRuleSavedUpdatedDescription": "Your changes to this alert rule were saved.",
"alertingTestAlertSent": "Test alert sent",
"alertingTestAlertSentDescription": "A test alert was sent to the actions configured on this rule.",
"alertingEditRule": "Edit Alert Rule", "alertingEditRule": "Edit Alert Rule",
"alertingCreateRule": "Create Alert Rule", "alertingCreateRule": "Create Alert Rule",
"alertingRuleCredenzaDescription": "Choose what to watch, when to fire, and how to notify", "alertingRuleCredenzaDescription": "Choose what to watch, when to fire, and how to notify",
@@ -1804,6 +1806,12 @@
"alertingRulesBannerDescription": "Each rule ties together what to watch (a site, health check, or resource), when to fire (for example offline or unhealthy), and how to notify your team via email, webhooks, or integrations. Use this list to create, enable, and manage those rules.", "alertingRulesBannerDescription": "Each rule ties together what to watch (a site, health check, or resource), when to fire (for example offline or unhealthy), and how to notify your team via email, webhooks, or integrations. Use this list to create, enable, and manage those rules.",
"alertingHealthChecksBannerTitle": "Monitor Health & Resources", "alertingHealthChecksBannerTitle": "Monitor Health & Resources",
"alertingHealthChecksBannerDescription": "Health checks are HTTP or TCP monitors you define once. You can then use them as sources in alert rules so you get notified when a target becomes healthy or unhealthy. Health checks on resources also appear here.", "alertingHealthChecksBannerDescription": "Health checks are HTTP or TCP monitors you define once. You can then use them as sources in alert rules so you get notified when a target becomes healthy or unhealthy. Health checks on resources also appear here.",
"alertingTestRule": "Test Alert Rule",
"alertingAddActionHeading": "Add New Action",
"alertingSelectActionType": "Choose an action type",
"alertingNoActionsTitle": "No actions configured",
"alertingNoActionsSaveDescription": "Add at least one action so this rule can notify someone when it fires.",
"alertingNoActionsTestDescription": "Add at least one action before you can test this rule.",
"standaloneHcTableTitle": "Health Checks", "standaloneHcTableTitle": "Health Checks",
"standaloneHcSearchPlaceholder": "Search health checks…", "standaloneHcSearchPlaceholder": "Search health checks…",
"standaloneHcAddButton": "Create Health Check", "standaloneHcAddButton": "Create Health Check",
+1
View File
@@ -151,6 +151,7 @@ export enum ActionsEnum {
createAlertRule = "createAlertRule", createAlertRule = "createAlertRule",
updateAlertRule = "updateAlertRule", updateAlertRule = "updateAlertRule",
deleteAlertRule = "deleteAlertRule", deleteAlertRule = "deleteAlertRule",
testAlertRule = "testAlertRule",
listAlertRules = "listAlertRules", listAlertRules = "listAlertRules",
listOrgLabels = "listOrgLabels", listOrgLabels = "listOrgLabels",
createOrgLabel = "createOrgLabel", createOrgLabel = "createOrgLabel",
+30 -3
View File
@@ -31,9 +31,24 @@ export type AlertNotificationProps = {
orgId: string; orgId: string;
data: Record<string, unknown>; data: Record<string, unknown>;
dashboardLink: string; dashboardLink: string;
isTestAlert?: boolean;
}; };
function getEventMeta(eventType: AlertEventType): { function getEventMeta(
eventType: AlertEventType,
isTestAlert: boolean = false
): {
heading: string;
previewText: string;
summary: string;
statusLabel: string | null;
statusColor: string | null;
} {
const meta = getBaseEventMeta(eventType);
return isTestAlert ? { ...meta, heading: `[TEST] ${meta.heading}` } : meta;
}
function getBaseEventMeta(eventType: AlertEventType): {
heading: string; heading: string;
previewText: string; previewText: string;
summary: string; summary: string;
@@ -180,8 +195,14 @@ function formatDataItems(
} }
export const AlertNotification = (props: AlertNotificationProps) => { export const AlertNotification = (props: AlertNotificationProps) => {
const { eventType, orgId, data, dashboardLink } = props; const {
const meta = getEventMeta(eventType); eventType,
orgId,
data,
dashboardLink,
isTestAlert = false
} = props;
const meta = getEventMeta(eventType, isTestAlert);
const dataItems = formatDataItems(data); const dataItems = formatDataItems(data);
const isToggle = const isToggle =
@@ -242,6 +263,12 @@ export const AlertNotification = (props: AlertNotificationProps) => {
Open your dashboard to view more details and manage Open your dashboard to view more details and manage
your alert rules. your alert rules.
</EmailText> </EmailText>
{isTestAlert && (
<EmailText>
This is a test alert. No action is required,
and no real event has occurred.
</EmailText>
)}
<EmailSection> <EmailSection>
<ButtonLink href={dashboardLink}> <ButtonLink href={dashboardLink}>
+2 -2
View File
@@ -266,13 +266,13 @@ export const configSchema = z
.positive() .positive()
.gt(0) .gt(0)
.optional() .optional()
.default(10), .default(30),
burst: z burst: z
.number() .number()
.positive() .positive()
.gt(0) .gt(0)
.optional() .optional()
.default(16) .default(50)
}) })
.optional() .optional()
.prefault({}) .prefault({})
@@ -0,0 +1,105 @@
import { db, userOrgRoles, users } from "@server/db";
import logger from "@server/logger";
import type {
EmailAlertAction,
TestAlertContext,
WebhookAlertConfig
} from "@server/routers/alertRule/types";
import { eq, inArray } from "drizzle-orm";
import { sendAlertEmail } from "./sendAlertEmail";
import { sendAlertWebhook } from "./sendAlertWebhook";
export async function processTestAlerts(context: TestAlertContext) {
// Process email actions
const emailActions = context.actions.filter(
(action) => action.type === "email"
);
for (const action of emailActions) {
try {
const recipients = await resolveEmailRecipients(action);
if (recipients.length > 0) {
await sendAlertEmail(recipients, {
...context,
isTest: true
});
}
} catch (err) {
logger.error(`processTestAlerts: failed to send alert email`, err);
}
}
// Process webhook actions
const webhookActions = context.actions.filter(
(action) => action.type === "webhook"
);
for (const action of webhookActions) {
try {
let webhookConfig: WebhookAlertConfig = { authType: "none" };
if (action.config) {
try {
webhookConfig = JSON.parse(
action.config
) as WebhookAlertConfig;
} catch (err) {
logger.error(
`processTestAlerts: failed to decrypt webhook`,
err
);
continue;
}
}
await sendAlertWebhook(action.webhookUrl, webhookConfig, {
...context,
isTest: true
});
} catch (err) {
logger.error(
`processTestAlerts: failed to send alert webhook `,
err
);
}
}
}
/**
* Resolves all email addresses for a given `emailActionId`.
*
* Recipients may be:
* - Direct users (by `userId`)
* - All users in a role (by `roleId`, resolved via `userOrgRoles`)
* - Direct external email addresses
*/
async function resolveEmailRecipients(
action: EmailAlertAction
): Promise<string[]> {
const emailList: string[] = [];
emailList.push(...(action.emails ?? []));
if (action.userIds && action.userIds?.length > 0) {
const userList = await db
.select({ email: users.email })
.from(users)
.where(inArray(users.userId, action.userIds));
emailList.push(
...userList.filter((u) => u.email !== null).map((u) => u.email!)
);
}
if (action.roleIds && action.roleIds?.length > 0) {
const userList = await db
.select({ email: users.email })
.from(userOrgRoles)
.innerJoin(users, eq(userOrgRoles.userId, users.userId))
.where(inArray(userOrgRoles.roleId, action.roleIds.map(Number)));
emailList.push(
...userList.filter((u) => u.email !== null).map((u) => u.email!)
);
}
return [...new Set(emailList)];
}
+31 -15
View File
@@ -15,7 +15,21 @@ import { sendEmail } from "@server/emails";
import AlertNotification from "@server/emails/templates/AlertNotification"; import AlertNotification from "@server/emails/templates/AlertNotification";
import config from "@server/lib/config"; import config from "@server/lib/config";
import logger from "@server/logger"; import logger from "@server/logger";
import { AlertContext } from "@server/routers/alertRule/types"; import { type AlertEventType } from "@server/routers/alertRule/types";
type EmailAlertContext = {
eventType: AlertEventType;
orgId: string;
/** Set for site_online / site_offline events */
siteId?: number;
/** Set for health_check_* events */
healthCheckId?: number;
/** Set for resource_* events */
resourceId?: number;
/** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>;
isTest?: boolean;
};
/** /**
* Sends an alert notification email to every address in `recipients`. * Sends an alert notification email to every address in `recipients`.
@@ -27,7 +41,7 @@ import { AlertContext } from "@server/routers/alertRule/types";
*/ */
export async function sendAlertEmail( export async function sendAlertEmail(
recipients: string[], recipients: string[],
context: AlertContext context: EmailAlertContext
): Promise<void> { ): Promise<void> {
if (recipients.length === 0) { if (recipients.length === 0) {
return; return;
@@ -46,7 +60,8 @@ export async function sendAlertEmail(
eventType: context.eventType, eventType: context.eventType,
orgId: context.orgId, orgId: context.orgId,
data: context.data, data: context.data,
dashboardLink dashboardLink,
isTestAlert: context.isTest
}), }),
{ {
from, from,
@@ -70,34 +85,35 @@ export async function sendAlertEmail(
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function buildSubject(context: AlertContext): string { function buildSubject(context: EmailAlertContext): string {
const prefix = context.isTest ? "[Test Alert]" : "[Alert]";
switch (context.eventType) { switch (context.eventType) {
case "site_online": case "site_online":
return "[Alert] Site Back Online"; return `${prefix} Site Back Online`;
case "site_offline": case "site_offline":
return "[Alert] Site Offline"; return `${prefix} Site Offline`;
case "site_toggle": case "site_toggle":
return "[Alert] Site Status Changed"; return `${prefix} Site Status Changed`;
case "health_check_healthy": case "health_check_healthy":
return "[Alert] Health Check Recovered"; return `${prefix} Health Check Recovered`;
case "health_check_unhealthy": case "health_check_unhealthy":
return "[Alert] Health Check Failing"; return `${prefix} Health Check Failing`;
case "health_check_toggle": case "health_check_toggle":
return "[Alert] Health Check Status Changed"; return `${prefix} Health Check Status Changed`;
case "resource_healthy": case "resource_healthy":
return "[Alert] Resource Healthy"; return `${prefix} Resource Healthy`;
case "resource_unhealthy": case "resource_unhealthy":
return "[Alert] Resource Unhealthy"; return `${prefix} Resource Unhealthy`;
case "resource_degraded": case "resource_degraded":
return "[Alert] Resource Degraded"; return `${prefix} Resource Degraded`;
case "resource_toggle": case "resource_toggle":
return "[Alert] Resource Status Changed"; return `${prefix} Resource Status Changed`;
default: { default: {
// Exhaustiveness fallback should never be reached with a // Exhaustiveness fallback should never be reached with a
// well-typed caller, but keeps runtime behaviour predictable. // well-typed caller, but keeps runtime behaviour predictable.
const _exhaustive: never = context.eventType; const _exhaustive: never = context.eventType;
void _exhaustive; void _exhaustive;
return "[Alert] Event Notification"; return `${prefix} Event Notification`;
} }
} }
} }
+31 -10
View File
@@ -14,13 +14,28 @@
import logger from "@server/logger"; import logger from "@server/logger";
import { import {
AlertContext, AlertContext,
WebhookAlertConfig WebhookAlertConfig,
type AlertEventType
} from "@server/routers/alertRule/types"; } from "@server/routers/alertRule/types";
const REQUEST_TIMEOUT_MS = 15_000; const REQUEST_TIMEOUT_MS = 15_000;
const MAX_RETRIES = 3; const MAX_RETRIES = 3;
const RETRY_BASE_DELAY_MS = 500; const RETRY_BASE_DELAY_MS = 500;
type WebhookAlertContext = {
eventType: AlertEventType;
orgId: string;
/** Set for site_online / site_offline events */
siteId?: number;
/** Set for health_check_* events */
healthCheckId?: number;
/** Set for resource_* events */
resourceId?: number;
/** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>;
isTest?: boolean;
};
/** /**
* Sends a single webhook POST for an alert event. * Sends a single webhook POST for an alert event.
* *
@@ -40,14 +55,14 @@ const RETRY_BASE_DELAY_MS = 500;
export async function sendAlertWebhook( export async function sendAlertWebhook(
url: string, url: string,
webhookConfig: WebhookAlertConfig, webhookConfig: WebhookAlertConfig,
context: AlertContext context: WebhookAlertContext
): Promise<void> { ): Promise<void> {
const eventType = context.eventType; const eventType = context.eventType;
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
const status = deriveStatus(eventType, context.data); const status = deriveStatus(eventType, context.data);
const data = { orgId: context.orgId, ...context.data }; const data = { orgId: context.orgId, ...context.data };
let body: string; let body: Record<string, any>;
if (webhookConfig.useBodyTemplate && webhookConfig.bodyTemplate?.trim()) { if (webhookConfig.useBodyTemplate && webhookConfig.bodyTemplate?.trim()) {
body = renderTemplate(webhookConfig.bodyTemplate, { body = renderTemplate(webhookConfig.bodyTemplate, {
event: eventType, event: eventType,
@@ -56,7 +71,11 @@ export async function sendAlertWebhook(
data data
}); });
} else { } else {
body = JSON.stringify({ event: eventType, timestamp, status, data }); body = { event: eventType, timestamp, status, data };
}
if (body.data && context.isTest) {
body.data.test = true;
} }
const headers = buildHeaders(webhookConfig); const headers = buildHeaders(webhookConfig);
@@ -75,7 +94,7 @@ export async function sendAlertWebhook(
response = await fetch(url, { response = await fetch(url, {
method: webhookConfig.method ?? "POST", method: webhookConfig.method ?? "POST",
headers, headers,
body, body: JSON.stringify(body),
signal: controller.signal signal: controller.signal
}); });
} catch (err: unknown) { } catch (err: unknown) {
@@ -247,7 +266,10 @@ interface TemplateContext {
* left untouched. * left untouched.
* 3. The fixed top-level keys: event, timestamp, status. * 3. The fixed top-level keys: event, timestamp, status.
*/ */
function renderTemplate(template: string, ctx: TemplateContext): string { function renderTemplate(
template: string,
ctx: TemplateContext
): Record<string, any> {
// Step 1 expand {{data}} first so its contents are already serialised // Step 1 expand {{data}} first so its contents are already serialised
// and won't be touched by later passes. // and won't be touched by later passes.
let rendered = template.replace(/\{\{data\}\}/g, JSON.stringify(ctx.data)); let rendered = template.replace(/\{\{data\}\}/g, JSON.stringify(ctx.data));
@@ -280,20 +302,19 @@ function renderTemplate(template: string, ctx: TemplateContext): string {
// Validate the rendered result is valid JSON; if not, log a warning and // Validate the rendered result is valid JSON; if not, log a warning and
// fall back to the default payload so the webhook still fires. // fall back to the default payload so the webhook still fires.
try { try {
JSON.parse(rendered); return JSON.parse(rendered);
return rendered;
} catch { } catch {
logger.warn( logger.warn(
`sendAlertWebhook: body template produced invalid JSON for event ` + `sendAlertWebhook: body template produced invalid JSON for event ` +
`"${ctx.event}" destined for a webhook. Falling back to default ` + `"${ctx.event}" destined for a webhook. Falling back to default ` +
`payload. Check that {{data}} is NOT wrapped in quotes in your template.` `payload. Check that {{data}} is NOT wrapped in quotes in your template.`
); );
return JSON.stringify({ return {
event: ctx.event, event: ctx.event,
timestamp: ctx.timestamp, timestamp: ctx.timestamp,
status: ctx.status, status: ctx.status,
data: ctx.data data: ctx.data
}); };
} }
} }
+2 -1
View File
@@ -15,4 +15,5 @@ export * from "./createAlertRule";
export * from "./updateAlertRule"; export * from "./updateAlertRule";
export * from "./deleteAlertRule"; export * from "./deleteAlertRule";
export * from "./listAlertRules"; export * from "./listAlertRules";
export * from "./getAlertRule"; export * from "./getAlertRule";
export * from "./testAlertRule";
@@ -0,0 +1,196 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025-2026 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { getRandomItemInArray } from "@app/lib/getRandomItemInArray";
import response from "@server/lib/response";
import logger from "@server/logger";
import { processTestAlerts } from "@server/private/lib/alerts/processTestAlerts";
import { type AlertAction } from "@server/routers/alertRule/types";
import HttpCode from "@server/types/HttpCode";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import type { TriggerSiteAlertResponse } from "../alertEvents";
import {
HC_EVENT_TYPES,
SITE_EVENT_TYPES,
RESOURCE_EVENT_TYPES
} from "./createAlertRule";
const paramsSchema = z.strictObject({
orgId: z.string().nonempty()
});
const webhookActionSchema = z.strictObject({
webhookUrl: z.url(),
config: z.string().optional(),
enabled: z.boolean().optional().default(true)
});
const bodySchema = z.object({
eventType: z.enum([
...HC_EVENT_TYPES,
...SITE_EVENT_TYPES,
...RESOURCE_EVENT_TYPES
]),
// Email recipients (flat)
userIds: z.array(z.string().nonempty()).optional().default([]),
roleIds: z.array(z.number()).optional().default([]),
emails: z.array(z.email()).optional().default([]),
// Webhook actions
webhookActions: z.array(webhookActionSchema).optional().default([])
});
export async function testAlertRule(
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 { orgId } = parsedParams.data;
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const body = parsedBody.data;
const collectedActions: AlertAction[] = [];
if (
body.emails.length > 0 ||
body.roleIds.length > 0 ||
body.userIds.length > 0
) {
collectedActions.push({
type: "email",
emails: body.emails,
roleIds: body.roleIds,
userIds: body.userIds
});
}
for (const action of body.webhookActions) {
collectedActions.push({
type: "webhook",
...action
});
}
let data: Record<string, any> = {};
switch (body.eventType) {
case "site_toggle":
data = {
status: getRandomItemInArray(["online", "offline"]),
siteName: "Test Site Alert"
};
break;
case "site_offline":
data = {
status: "offline",
siteName: "Test Site Alert"
};
break;
case "site_online":
data = {
status: "online",
siteName: "Test Site Alert"
};
break;
case "resource_toggle":
data = {
status: getRandomItemInArray([
"healthy",
"unhealthy",
"degraded"
]),
siteName: "Test Resource Alert"
};
break;
case "resource_healthy":
data = {
status: "healthy",
siteName: "Test Resource Alert"
};
break;
case "resource_unhealthy":
data = {
status: "unhealthy",
siteName: "Test Resource Alert"
};
break;
case "resource_degraded":
data = {
status: "degraded",
siteName: "Test Resource Alert"
};
break;
case "health_check_toggle":
data = {
status: getRandomItemInArray(["healthy", "unhealthy"]),
healthCheckName: "Test Health Check Alert"
};
break;
case "health_check_healthy":
data = {
status: "healthy",
healthCheckName: "Test Health Check Alert"
};
break;
case "health_check_unhealthy":
data = {
status: "unhealthy",
healthCheckName: "Test Health Check Alert"
};
break;
default:
break;
}
// TODO: process alert rule
await processTestAlerts({
eventType: body.eventType,
orgId,
actions: collectedActions,
data
});
return response<TriggerSiteAlertResponse>(res, {
data: { success: true },
success: true,
error: false,
message: "Alert triggered successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
@@ -10,12 +10,12 @@
* *
* This file is not licensed under the AGPLv3. * This file is not licensed under the AGPLv3.
*/ */
import { certificates, db, domains, orgDomains } from "@server/db"; import { certificates, db, domainNamespaces, domains, orgDomains } from "@server/db";
import response from "@server/lib/response"; import response from "@server/lib/response";
import logger from "@server/logger"; import logger from "@server/logger";
import { type GetBatchedCertificateResponse } from "@server/routers/certificates/types"; import { type GetBatchedCertificateResponse } from "@server/routers/certificates/types";
import HttpCode from "@server/types/HttpCode"; import HttpCode from "@server/types/HttpCode";
import { and, eq, inArray, or } from "drizzle-orm"; import { and, eq, inArray, isNotNull, or } from "drizzle-orm";
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors"; import createHttpError from "http-errors";
import { z } from "zod"; import { z } from "zod";
@@ -63,14 +63,28 @@ async function query(orgId: string, domainList: string[]) {
}) })
.from(certificates) .from(certificates)
.innerJoin(domains, eq(certificates.domainId, domains.domainId)) .innerJoin(domains, eq(certificates.domainId, domains.domainId))
.innerJoin( .leftJoin(
orgDomains, orgDomains,
and( and(
eq(domains.domainId, orgDomains.domainId), eq(domains.domainId, orgDomains.domainId),
eq(orgDomains.orgId, orgId) eq(orgDomains.orgId, orgId)
) )
) )
.where(and(inArray(certificates.domain, domainList))); .leftJoin(
domainNamespaces,
eq(domains.domainId, domainNamespaces.domainId)
)
.where(
and(
inArray(certificates.domain, domainList),
// Namespace domains are shared across all orgs, so they skip
// the org-ownership check (mirrors verifyCertificateAccess).
or(
isNotNull(orgDomains.orgId),
isNotNull(domainNamespaces.domainNamespaceId)
)
)
);
// All non resolved domain certificates might be `ns` or `wildcard`, // All non resolved domain certificates might be `ns` or `wildcard`,
// which means exact domain certificates do not exist // which means exact domain certificates do not exist
@@ -110,19 +124,27 @@ async function query(orgId: string, domainList: string[]) {
}) })
.from(certificates) .from(certificates)
.innerJoin(domains, eq(certificates.domainId, domains.domainId)) .innerJoin(domains, eq(certificates.domainId, domains.domainId))
.innerJoin( .leftJoin(
orgDomains, orgDomains,
and( and(
eq(domains.domainId, orgDomains.domainId), eq(domains.domainId, orgDomains.domainId),
eq(orgDomains.orgId, orgId) eq(orgDomains.orgId, orgId)
) )
) )
.leftJoin(
domainNamespaces,
eq(domains.domainId, domainNamespaces.domainId)
)
.where( .where(
and( and(
eq(certificates.wildcard, true), eq(certificates.wildcard, true),
or( or(
inArray(certificates.domain, [...domainLevelDownSet]), inArray(certificates.domain, [...domainLevelDownSet]),
inArray(certificates.domain, [...wildcardDomainSet]) inArray(certificates.domain, [...wildcardDomainSet])
),
or(
isNotNull(orgDomains.orgId),
isNotNull(domainNamespaces.domainNamespaceId)
) )
) )
); );
+8
View File
@@ -808,6 +808,14 @@ authenticated.get(
alertRule.listAlertRules alertRule.listAlertRules
); );
authenticated.post(
"/org/:orgId/test-alert-rule",
verifyValidLicense,
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.testAlertRule),
alertRule.testAlertRule
);
authenticated.get( authenticated.get(
"/org/:orgId/alert-rule/:alertRuleId", "/org/:orgId/alert-rule/:alertRuleId",
verifyValidLicense, verifyValidLicense,
+23
View File
@@ -124,3 +124,26 @@ export interface AlertContext {
/** Human-readable context data included in emails and webhook payloads */ /** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>; data: Record<string, unknown>;
} }
export type EmailAlertAction = {
type: "email";
userIds?: string[];
roleIds?: number[];
emails?: string[];
};
export type WebhookAlertAction = {
type: "webhook";
webhookUrl: string;
enabled: boolean;
config?: string | undefined;
};
export type AlertAction = EmailAlertAction | WebhookAlertAction;
export interface TestAlertContext {
eventType: AlertEventType;
actions: AlertAction[];
orgId: string;
/** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>;
}
+51 -3
View File
@@ -127,6 +127,9 @@ export async function verifyResourceSession(
// Extract HTTP Basic Auth credentials if present // Extract HTTP Basic Auth credentials if present
const clientHeaderAuth = extractBasicAuth(headers); const clientHeaderAuth = extractBasicAuth(headers);
const clientUserAgent = headers?.["user-agent"] || headers?.["User-Agent"];
const clientIsBrowser = isBrowserUserAgent(clientUserAgent);
const clientIp = requestIp const clientIp = requestIp
? stripPortFromHost(requestIp, badgerVersion) ? stripPortFromHost(requestIp, badgerVersion)
: undefined; : undefined;
@@ -313,9 +316,14 @@ export async function verifyResourceSession(
return allowed(res, undefined, dontStripSession); return allowed(res, undefined, dontStripSession);
} }
const redirectPath = `/auth/resource/${encodeURIComponent( // Only offer a browser redirect to clients that can actually follow one and log in
resource.resourceGuid // (an interactive browser). Non-browser clients (curl, scripts, bots, etc.) just get
)}?redirect=${encodeURIComponent(originalRequestURL)}`; // an unauthorized response from Badger instead of a login redirect URL.
const redirectPath = clientIsBrowser
? `/auth/resource/${encodeURIComponent(
resource.resourceGuid
)}?redirect=${encodeURIComponent(originalRequestURL)}`
: undefined;
// check for access token in headers // check for access token in headers
if ( if (
@@ -1476,6 +1484,46 @@ async function getCountryCodeFromIp(ip: string): Promise<string | undefined> {
return cachedCountryCode; return cachedCountryCode;
} }
// Permissive by default: only reject known non-browser clients or a missing
// User-Agent (real browsers always send one). This avoids blocking real
// browsers whose UA string doesn't match a hardcoded allow-list.
const NON_BROWSER_USER_AGENT_PATTERNS = [
/curl/,
/wget/,
/python-requests/,
/python-urllib/,
/go-http-client/,
/okhttp/,
/axios/,
/node-fetch/,
/postmanruntime/,
/insomnia/,
/libwww-perl/,
/java\//,
/ruby/,
/php/,
/bot/,
/spider/,
/crawler/,
/headlesschrome/,
/phantomjs/,
/httpclient/,
/prometheus/,
/go-resty/,
/apache-httpclient/,
/scrapy/
];
function isBrowserUserAgent(userAgent: string | undefined): boolean {
if (!userAgent) {
return false;
}
const ua = userAgent.toLowerCase();
return !NON_BROWSER_USER_AGENT_PATTERNS.some((pattern) => pattern.test(ua));
}
function extractBasicAuth( function extractBasicAuth(
headers: Record<string, string> | undefined headers: Record<string, string> | undefined
): string | undefined { ): string | undefined {
+3 -1
View File
@@ -34,7 +34,9 @@ const createRoleSchema = z.strictObject({
export const defaultRoleAllowedActions: ActionsEnum[] = [ export const defaultRoleAllowedActions: ActionsEnum[] = [
ActionsEnum.getOrg, ActionsEnum.getOrg,
ActionsEnum.getResource, ActionsEnum.getResource,
ActionsEnum.listResources ActionsEnum.listResources,
ActionsEnum.getSiteResource,
ActionsEnum.listSiteResources
]; ];
export type CreateRoleBody = z.infer<typeof createRoleSchema>; export type CreateRoleBody = z.infer<typeof createRoleSchema>;
@@ -3,11 +3,13 @@ import {
DB_TYPE, DB_TYPE,
Label, Label,
SiteResource, SiteResource,
roleSiteResources,
siteNetworks, siteNetworks,
siteResourceLabels, siteResourceLabels,
siteResources, siteResources,
sites, sites,
labels labels,
userSiteResources
} from "@server/db"; } from "@server/db";
import response from "@server/lib/response"; import response from "@server/lib/response";
import logger from "@server/logger"; import logger from "@server/logger";
@@ -323,7 +325,48 @@ export async function listAllSiteResourcesByOrg(
labels: labelFilter labels: labelFilter
} = parsedQuery.data; } = parsedQuery.data;
const conditions = [and(eq(siteResources.orgId, orgId))]; let accessibleSiteResourceIds: number[];
if (req.user) {
const accessibleSiteResources = await db
.select({
siteResourceId: sql<number>`COALESCE(${userSiteResources.siteResourceId}, ${roleSiteResources.siteResourceId})`
})
.from(userSiteResources)
.fullJoin(
roleSiteResources,
eq(
userSiteResources.siteResourceId,
roleSiteResources.siteResourceId
)
)
.where(
or(
eq(userSiteResources.userId, req.user.userId),
inArray(
roleSiteResources.roleId,
req.userOrgRoleIds ?? []
)
)
);
accessibleSiteResourceIds = accessibleSiteResources.map(
(row) => row.siteResourceId
);
} else {
const allOrgSiteResources = await db
.select({ siteResourceId: siteResources.siteResourceId })
.from(siteResources)
.where(eq(siteResources.orgId, orgId));
accessibleSiteResourceIds = allOrgSiteResources.map(
(row) => row.siteResourceId
);
}
const conditions = [
and(
eq(siteResources.orgId, orgId),
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
)
];
if (siteId != null) { if (siteId != null) {
// Keep inner joins here: filtering by a specific site implies the // Keep inner joins here: filtering by a specific site implies the
@@ -1,11 +1,17 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { z } from "zod"; import { z } from "zod";
import { db, networks, siteNetworks } from "@server/db"; import {
db,
networks,
roleSiteResources,
siteNetworks,
userSiteResources
} from "@server/db";
import { siteResources, sites, SiteResource } from "@server/db"; import { siteResources, sites, SiteResource } from "@server/db";
import response from "@server/lib/response"; import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode"; import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors"; import createHttpError from "http-errors";
import { and, asc, desc, eq } from "drizzle-orm"; import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
import { fromError } from "zod-validation-error"; import { fromError } from "zod-validation-error";
import logger from "@server/logger"; import logger from "@server/logger";
import { OpenAPITags, registry } from "@server/openApi"; import { OpenAPITags, registry } from "@server/openApi";
@@ -159,10 +165,47 @@ export async function listSiteResources(
return next(createHttpError(HttpCode.NOT_FOUND, "Site not found")); return next(createHttpError(HttpCode.NOT_FOUND, "Site not found"));
} }
let accessibleSiteResourceIds: number[];
if (req.user) {
const accessibleSiteResources = await db
.select({
siteResourceId: sql<number>`COALESCE(${userSiteResources.siteResourceId}, ${roleSiteResources.siteResourceId})`
})
.from(userSiteResources)
.fullJoin(
roleSiteResources,
eq(
userSiteResources.siteResourceId,
roleSiteResources.siteResourceId
)
)
.where(
or(
eq(userSiteResources.userId, req.user.userId),
inArray(
roleSiteResources.roleId,
req.userOrgRoleIds ?? []
)
)
);
accessibleSiteResourceIds = accessibleSiteResources.map(
(row) => row.siteResourceId
);
} else {
const allOrgSiteResources = await db
.select({ siteResourceId: siteResources.siteResourceId })
.from(siteResources)
.where(eq(siteResources.orgId, orgId));
accessibleSiteResourceIds = allOrgSiteResources.map(
(row) => row.siteResourceId
);
}
// Get site resources by joining networks to siteResources via siteNetworks // Get site resources by joining networks to siteResources via siteNetworks
const conditions = [ const conditions = [
eq(siteNetworks.siteId, siteId), eq(siteNetworks.siteId, siteId),
eq(siteResources.orgId, orgId) eq(siteResources.orgId, orgId),
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
]; ];
if (typeof status !== "undefined") { if (typeof status !== "undefined") {
+3 -1
View File
@@ -28,6 +28,7 @@ import m19 from "./scriptsPg/1.18.4";
import m20 from "./scriptsPg/1.19.0"; import m20 from "./scriptsPg/1.19.0";
import m21 from "./scriptsPg/1.20.0"; import m21 from "./scriptsPg/1.20.0";
import m22 from "./scriptsPg/1.21.0"; import m22 from "./scriptsPg/1.21.0";
import m23 from "./scriptsPg/1.21.1";
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER // THIS CANNOT IMPORT ANYTHING FROM THE SERVER
// EXCEPT FOR THE DATABASE AND THE SCHEMA // EXCEPT FOR THE DATABASE AND THE SCHEMA
@@ -55,7 +56,8 @@ const migrations = [
{ version: "1.18.4", run: m19 }, { version: "1.18.4", run: m19 },
{ version: "1.19.0", run: m20 }, { version: "1.19.0", run: m20 },
{ version: "1.20.0", run: m21 }, { version: "1.20.0", run: m21 },
{ version: "1.21.0", run: m22 } { version: "1.21.0", run: m22 },
{ version: "1.21.1", run: m23 }
// Add new migrations here as they are created // Add new migrations here as they are created
] as { ] as {
version: string; version: string;
+3 -1
View File
@@ -47,6 +47,7 @@ import m41 from "./scriptsSqlite/1.19.0";
import m42 from "./scriptsSqlite/1.19.1"; import m42 from "./scriptsSqlite/1.19.1";
import m43 from "./scriptsSqlite/1.20.0"; import m43 from "./scriptsSqlite/1.20.0";
import m44 from "./scriptsSqlite/1.21.0"; import m44 from "./scriptsSqlite/1.21.0";
import m45 from "./scriptsSqlite/1.21.1";
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER // THIS CANNOT IMPORT ANYTHING FROM THE SERVER
// EXCEPT FOR THE DATABASE AND THE SCHEMA // EXCEPT FOR THE DATABASE AND THE SCHEMA
@@ -91,7 +92,8 @@ const migrations = [
{ version: "1.19.0", run: m41 }, { version: "1.19.0", run: m41 },
{ version: "1.19.1", run: m42 }, { version: "1.19.1", run: m42 },
{ version: "1.20.0", run: m43 }, { version: "1.20.0", run: m43 },
{ version: "1.21.0", run: m44 } { version: "1.21.0", run: m44 },
{ version: "1.21.1", run: m45 }
// Add new migrations here as they are created // Add new migrations here as they are created
] as const; ] as const;
+37
View File
@@ -0,0 +1,37 @@
import { db } from "@server/db/pg/driver";
import { sql } from "drizzle-orm";
const version = "1.21.1";
const actionsToGrant = ["getSiteResource", "listSiteResources"] as const;
export default async function migration() {
console.log(`Running setup script ${version}...`);
try {
await db.execute(sql`BEGIN`);
for (const actionId of actionsToGrant) {
await db.execute(sql`
INSERT INTO "roleActions" ("roleId", "actionId", "orgId")
SELECT r."roleId", ${actionId}, r."orgId"
FROM "roles" r
WHERE COALESCE(r."isAdmin", false) = false
AND NOT EXISTS (
SELECT 1 FROM "roleActions" ra
WHERE ra."roleId" = r."roleId"
AND ra."actionId" = ${actionId}
AND ra."orgId" = r."orgId"
);
`);
}
await db.execute(sql`COMMIT`);
console.log(`Finished setup script ${version}`);
} catch (e) {
await db.execute(sql`ROLLBACK`);
console.log("Unable to migrate database");
console.log(e);
throw e;
}
}
+43
View File
@@ -0,0 +1,43 @@
import { APP_PATH } from "@server/lib/consts";
import Database from "better-sqlite3";
import path from "path";
const version = "1.21.1";
const actionsToGrant = ["getSiteResource", "listSiteResources"] as const;
export default async function migration() {
console.log(`Running setup script ${version}...`);
const location = path.join(APP_PATH, "db", "db.sqlite");
const db = new Database(location);
try {
db.transaction(() => {
const insertRoleAction = db.prepare(`
INSERT INTO 'roleActions' ("roleId", "actionId", "orgId")
SELECT r."roleId", ?, r."orgId"
FROM 'roles' r
WHERE COALESCE(r."isAdmin", 0) = 0
AND NOT EXISTS (
SELECT 1 FROM 'roleActions' ra
WHERE ra."roleId" = r."roleId"
AND ra."actionId" = ?
AND ra."orgId" = r."orgId"
);
`);
for (const actionId of actionsToGrant) {
insertRoleAction.run(actionId, actionId);
}
})();
console.log(`Finished setup script ${version}`);
} catch (e) {
console.log("Unable to migrate database");
console.log(e);
throw e;
} finally {
db.close();
}
}
@@ -181,7 +181,7 @@ export default function NetworkingPage() {
<SettingsSectionDescription> <SettingsSectionDescription>
{t("remoteExitNodeNetworkingDescription")} {t("remoteExitNodeNetworkingDescription")}
<a <a
href="https://docs.pangolin.net/placeholder" href="https://docs.pangolin.net/manage/remote-node/backhaul"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="text-primary hover:underline inline-flex items-center gap-1" className="text-primary hover:underline inline-flex items-center gap-1"
+13 -11
View File
@@ -24,19 +24,21 @@ export function ContactSalesBanner() {
<ExternalLink className="size-3.5 shrink-0" /> <ExternalLink className="size-3.5 shrink-0" />
</Link> </Link>
{" " + t("contactSalesOr") + " "} {" " + t("contactSalesOr") + " "}
<Link <span className="whitespace-nowrap">
href="https://pangolin.net/contact" <Link
target="_blank" href="https://pangolin.net/contact"
rel="noopener noreferrer" target="_blank"
className="inline-flex items-center gap-1 font-medium text-black-600 underline" rel="noopener noreferrer"
> className="inline-flex items-center gap-1 font-medium text-black-600 underline"
{t("contactSalesContactUs")} >
<ExternalLink className="size-3.5 shrink-0" /> {t("contactSalesContactUs")}
</Link> <ExternalLink className="size-3.5 shrink-0" />
. </Link>
.
</span>
</span> </span>
</div> </div>
</div> </div>
</div> </div>
); );
} }
+5 -3
View File
@@ -13,7 +13,7 @@ import {
import { InputOTP, InputOTPGroup, InputOTPSlot } from "./ui/input-otp"; import { InputOTP, InputOTPGroup, InputOTPSlot } from "./ui/input-otp";
import { Alert, AlertDescription } from "@app/components/ui/alert"; import { Alert, AlertDescription } from "@app/components/ui/alert";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { REGEXP_ONLY_DIGITS } from "input-otp"; import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
const MFA_OTP_INPUT_ID = "mfa-otp-code"; const MFA_OTP_INPUT_ID = "mfa-otp-code";
@@ -82,9 +82,11 @@ export default function MfaInputForm({
maxLength={6} maxLength={6}
{...field} {...field}
autoComplete="one-time-code" autoComplete="one-time-code"
inputMode="numeric" inputMode="text"
autoFocus autoFocus
pattern={REGEXP_ONLY_DIGITS} pattern={
REGEXP_ONLY_DIGITS_AND_CHARS
}
onChange={(value: string) => { onChange={(value: string) => {
field.onChange(value); field.onChange(value);
if (value.length === 6) { if (value.length === 6) {
@@ -45,7 +45,14 @@ import {
import { getUserDisplayName } from "@app/lib/getUserDisplayName"; import { getUserDisplayName } from "@app/lib/getUserDisplayName";
import { orgQueries } from "@app/lib/queries"; import { orgQueries } from "@app/lib/queries";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { Bell, ChevronsUpDown, Globe, Plus, Trash2 } from "lucide-react"; import {
Bell,
ChevronRightIcon,
ChevronsUpDown,
Globe,
Plus,
Trash2
} from "lucide-react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import type { Control, UseFormReturn } from "react-hook-form"; import type { Control, UseFormReturn } from "react-hook-form";
@@ -53,6 +60,7 @@ import { useFormContext, useWatch } from "react-hook-form";
import { useDebounce } from "use-debounce"; import { useDebounce } from "use-debounce";
import { RolesSelector } from "../roles-selector"; import { RolesSelector } from "../roles-selector";
import { UsersSelector } from "../users-selector"; import { UsersSelector } from "../users-selector";
import { cn } from "@app/lib/cn";
export function AddActionPanel({ export function AddActionPanel({
onAdd onAdd
@@ -95,6 +103,7 @@ export function AddActionPanel({
const EXTERNAL_IDS = EXTERNAL_INTEGRATIONS.map((i) => i.id); const EXTERNAL_IDS = EXTERNAL_INTEGRATIONS.map((i) => i.id);
const [selected, setSelected] = useState<string | null>("notify"); const [selected, setSelected] = useState<string | null>("notify");
const [isPopoverOpen, setPopoverOpen] = useState(false);
const isPremiumSelected = const isPremiumSelected =
selected !== null && EXTERNAL_IDS.includes(selected as any); selected !== null && EXTERNAL_IDS.includes(selected as any);
@@ -131,27 +140,46 @@ export function AddActionPanel({
if (!isBuiltInSelected) return; if (!isBuiltInSelected) return;
onAdd(selected as AlertRuleFormAction["type"]); onAdd(selected as AlertRuleFormAction["type"]);
setSelected(null); setSelected(null);
setPopoverOpen(false);
}; };
return ( return (
<div className="space-y-3"> <div className="flex flex-col gap-3 items-start">
<StrategySelect <h3 className="font-medium">{t("alertingAddActionHeading")}</h3>
options={actionTypeOptions} <Popover open={isPopoverOpen} onOpenChange={setPopoverOpen}>
value={selected} <PopoverTrigger asChild>
cols={2} <Button type="button" variant="outline">
onChange={(v) => setSelected(v)} {t("alertingSelectActionType")}
/> <ChevronRightIcon
{isPremiumSelected && <ContactSalesBanner />} className={cn(
{!isPremiumSelected && ( "size-4 transition-transform duration-150",
<Button isPopoverOpen && "rotate-90"
type="button" )}
disabled={!isBuiltInSelected} />
onClick={handleAdd} </Button>
> </PopoverTrigger>
<Plus className="h-4 w-4 mr-1" /> <PopoverContent className="shadow-md flex flex-col gap-3 w-150">
{t("alertingAddAction")} <StrategySelect
</Button> options={actionTypeOptions}
)} value={selected}
cols={2}
onChange={(v) => setSelected(v)}
/>
{isPremiumSelected ? (
<ContactSalesBanner />
) : (
<Button
type="button"
disabled={!isBuiltInSelected}
onClick={handleAdd}
>
<Plus className="h-4 w-4 mr-1" />
{t("alertingAddAction")}
</Button>
)}
</PopoverContent>
</Popover>
</div> </div>
); );
} }
@@ -6,7 +6,9 @@ import {
AlertRuleSourceFields, AlertRuleSourceFields,
AlertRuleTriggerFields AlertRuleTriggerFields
} from "@app/components/alert-rule-editor/AlertRuleFields"; } from "@app/components/alert-rule-editor/AlertRuleFields";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { SettingsContainer } from "@app/components/Settings"; import { SettingsContainer } from "@app/components/Settings";
import { SwitchInput } from "@app/components/SwitchInput";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { Card, CardContent } from "@app/components/ui/card"; import { Card, CardContent } from "@app/components/ui/card";
import { import {
@@ -19,6 +21,7 @@ import {
FormMessage FormMessage
} from "@app/components/ui/form"; } from "@app/components/ui/form";
import { Input } from "@app/components/ui/input"; import { Input } from "@app/components/ui/input";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { import {
buildFormSchema, buildFormSchema,
@@ -27,19 +30,15 @@ import {
type AlertRuleFormValues type AlertRuleFormValues
} from "@app/lib/alertRuleForm"; } from "@app/lib/alertRuleForm";
import { createApiClient, formatAxiosError } from "@app/lib/api"; import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { zodResolver } from "@hookform/resolvers/zod";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import type { CreateAlertRuleResponse } from "@server/routers/alertRule/types"; import type { CreateAlertRuleResponse } from "@server/routers/alertRule/types";
import type { AxiosResponse } from "axios"; import type { AxiosResponse } from "axios";
import { zodResolver } from "@hookform/resolvers/zod"; import { Cog, Flag, Zap, ZapIcon } from "lucide-react";
import { ChevronLeft, Cog, Flag, Zap } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState, type ReactNode } from "react";
import { useFieldArray, useForm, type Resolver } from "react-hook-form";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { useRouter } from "next/navigation";
import { SwitchInput } from "@app/components/SwitchInput"; import { useActionState, useMemo, useTransition, type ReactNode } from "react";
import { tierMatrix } from "@server/lib/billing/tierMatrix"; import { useFieldArray, useForm, type Resolver } from "react-hook-form";
import { Badge } from "../ui/badge"; import { Badge } from "../ui/badge";
const FORM_ID = "alert-rule-form"; const FORM_ID = "alert-rule-form";
@@ -115,7 +114,6 @@ export default function AlertRuleGraphEditor({
const t = useTranslations(); const t = useTranslations();
const router = useRouter(); const router = useRouter();
const api = createApiClient(useEnvContext()); const api = createApiClient(useEnvContext());
const [isSaving, setIsSaving] = useState(false);
const schema = useMemo(() => buildFormSchema(t), [t]); const schema = useMemo(() => buildFormSchema(t), [t]);
const form = useForm<AlertRuleFormValues>({ const form = useForm<AlertRuleFormValues>({
resolver: zodResolver(schema) as Resolver<AlertRuleFormValues>, resolver: zodResolver(schema) as Resolver<AlertRuleFormValues>,
@@ -127,8 +125,22 @@ export default function AlertRuleGraphEditor({
name: "actions" name: "actions"
}); });
const onSubmit = form.handleSubmit(async (values) => { const saveAlert = async () => {
setIsSaving(true); const isValid = await form.trigger();
if (!isValid) {
const values = form.getValues();
if (values.actions.length === 0) {
toast({
variant: "warning",
title: t("alertingNoActionsTitle"),
description: t("alertingNoActionsSaveDescription")
});
}
return;
}
const values = form.getValues();
try { try {
const payload = formValuesToApiPayload(values); const payload = formValuesToApiPayload(values);
if (isNew) { if (isNew) {
@@ -158,14 +170,48 @@ export default function AlertRuleGraphEditor({
description: formatAxiosError(e), description: formatAxiosError(e),
variant: "destructive" variant: "destructive"
}); });
} finally {
setIsSaving(false);
} }
}); };
const testAlert = async () => {
const isValid = await form.trigger("actions");
const values = form.getValues();
if (!isValid) {
if (values.actions.length === 0) {
toast({
variant: "warning",
title: t("alertingNoActionsTitle"),
description: t("alertingNoActionsTestDescription")
});
}
return;
}
try {
const payload = formValuesToApiPayload(values);
await api.post(`/org/${orgId}/test-alert-rule`, payload);
toast({
title: t("alertingTestAlertSent"),
description: t("alertingTestAlertSentDescription")
});
} catch (e) {
toast({
title: t("error"),
description: formatAxiosError(e),
variant: "destructive"
});
}
};
const [, formAction, isSaving] = useActionState(saveAlert, null);
const [isTestingAlert, startTransition] = useTransition();
return ( return (
<Form {...form}> <Form {...form}>
<form id={FORM_ID} onSubmit={onSubmit}> <form id={FORM_ID} action={formAction}>
<SettingsContainer> <SettingsContainer>
<PaidFeaturesAlert tiers={tierMatrix.alertingRules} /> <PaidFeaturesAlert tiers={tierMatrix.alertingRules} />
<div className="flex flex-col lg:flex-row gap-6 lg:gap-8 items-start"> <div className="flex flex-col lg:flex-row gap-6 lg:gap-8 items-start">
@@ -263,14 +309,29 @@ export default function AlertRuleGraphEditor({
</FormItem> </FormItem>
)} )}
/> />
<Button <div className="flex flex-col items-center w-full gap-3">
type="submit" <Button
className="w-full" type="submit"
disabled={isSaving} className="w-full"
loading={isSaving} disabled={isSaving}
> loading={isSaving}
{t("save")} >
</Button> {t("save")}
</Button>
<Button
type="button"
variant="outline"
className="w-full gap-1.5"
onClick={() =>
startTransition(testAlert)
}
loading={isTestingAlert}
>
{t("alertingTestRule")}
<ZapIcon className="size-3.5 flex-none" />
</Button>
</div>
</fieldset> </fieldset>
</CardContent> </CardContent>
</Card> </Card>
+1 -1
View File
@@ -111,7 +111,7 @@ export function useCertificate({
let certError: string | null = null; let certError: string | null = null;
if (restartCert.isError) { if (restartCert.isError) {
certError = "Failed to restart"; certError = "Failed to restart";
} else if (isError || initialCertValue === null) { } else if (isError || (!isLoading && data === null)) {
// Null value means failed to get the certificate // Null value means failed to get the certificate
certError = "Failed"; certError = "Failed";
} }
+5
View File
@@ -0,0 +1,5 @@
export function getRandomItemInArray<T>(array: T[]) {
// Source - https://stackoverflow.com/a/4550514
const randomElement = array[Math.floor(Math.random() * array.length)];
return randomElement;
}
+1 -1
View File
@@ -1371,7 +1371,7 @@ export const approvalQueries = {
}, },
refetchInterval: (query) => { refetchInterval: (query) => {
if (query.state.data) { if (query.state.data) {
return durationToMs(30, "seconds"); return durationToMs(1.5, "minutes");
} }
return false; return false;
} }