Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] d374b4f66e Bump ip-address from 10.2.0 to 10.4.0
Bumps [ip-address](https://github.com/beaugunderson/ip-address) from 10.2.0 to 10.4.0.
- [Release notes](https://github.com/beaugunderson/ip-address/releases)
- [Commits](https://github.com/beaugunderson/ip-address/compare/v10.2.0...v10.4.0)

---
updated-dependencies:
- dependency-name: ip-address
  dependency-version: 10.4.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-04 01:45:48 +00:00
23 changed files with 62 additions and 575 deletions
-4
View File
@@ -1804,10 +1804,6 @@
"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",
"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",
"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",
"standaloneHcSearchPlaceholder": "Search health checks…",
"standaloneHcAddButton": "Create Health Check",
+3 -3
View File
@@ -13111,9 +13111,9 @@
}
},
"node_modules/ip-address": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz",
"integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==",
"license": "MIT",
"engines": {
"node": ">= 12"
-1
View File
@@ -151,7 +151,6 @@ export enum ActionsEnum {
createAlertRule = "createAlertRule",
updateAlertRule = "updateAlertRule",
deleteAlertRule = "deleteAlertRule",
testAlertRule = "testAlertRule",
listAlertRules = "listAlertRules",
listOrgLabels = "listOrgLabels",
createOrgLabel = "createOrgLabel",
+2 -2
View File
@@ -266,13 +266,13 @@ export const configSchema = z
.positive()
.gt(0)
.optional()
.default(30),
.default(10),
burst: z
.number()
.positive()
.gt(0)
.optional()
.default(50)
.default(16)
})
.optional()
.prefault({})
@@ -1,73 +0,0 @@
import logger from "@server/logger";
import type {
EmailAlertAction,
TestAlertContext
} from "@server/routers/alertRule/types";
import { sendAlertEmail } from "./sendAlertEmail";
import type { db, alertEmailRecipients, users, userOrgRoles } from "@server/db";
import type { eq } from "drizzle-orm";
export async function processTestAlerts(context: TestAlertContext) {
const emailActions = context.actions.filter(
(action) => action.type === "email"
);
// Process email actions
for (const action of emailActions) {
try {
const recipients = await resolveEmailRecipients(action);
if (recipients.length > 0) {
await sendAlertEmail(recipients, context);
}
} catch (err) {
logger.error(`processAlerts: failed to send alert email`, 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 emailSet = new Set<string>();
// for (const row of rows) {
// if (row.email) {
// emailSet.add(row.email);
// }
// if (row.userId) {
// const [user] = await db
// .select({ email: users.email })
// .from(users)
// .where(eq(users.userId, row.userId))
// .limit(1);
// if (user?.email) {
// emailSet.add(user.email);
// }
// }
// if (row.roleId) {
// // Find all users with this role via userOrgRoles
// const roleUsers = await db
// .select({ email: users.email })
// .from(userOrgRoles)
// .innerJoin(users, eq(userOrgRoles.userId, users.userId))
// .where(eq(userOrgRoles.roleId, Number(row.roleId)));
// for (const u of roleUsers) {
// if (u.email) {
// emailSet.add(u.email);
// }
// }
// }
// }
return Array.from(emailSet);
}
+1 -2
View File
@@ -15,5 +15,4 @@ export * from "./createAlertRule";
export * from "./updateAlertRule";
export * from "./deleteAlertRule";
export * from "./listAlertRules";
export * from "./getAlertRule";
export * from "./testAlertRule";
export * from "./getAlertRule";
@@ -1,107 +0,0 @@
/*
* 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 { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import {
alertRules,
alertSites,
alertHealthChecks,
alertResources
} 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, asc, desc, eq, inArray, like, or, sql } from "drizzle-orm";
import { ListAlertRulesResponse } from "@server/routers/alertRule/types";
const paramsSchema = z.strictObject({
orgId: z.string().nonempty()
});
export const SITE_EVENT_TYPES = [
"site_online",
"site_offline",
"site_toggle"
] as const;
export const HC_EVENT_TYPES = [
"health_check_healthy",
"health_check_unhealthy",
"health_check_toggle"
] as const;
export const RESOURCE_EVENT_TYPES = [
"resource_healthy",
"resource_unhealthy",
"resource_degraded",
"resource_toggle"
] as const;
const webhookActionSchema = z.strictObject({
webhookUrl: z.string().url(),
config: z.string().optional(),
enabled: z.boolean().optional().default(true)
});
const bodySchema = z.strictObject({
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()
)
);
}
// TODO: process alert rule
} 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.
*/
import { certificates, db, domainNamespaces, domains, orgDomains } from "@server/db";
import { certificates, db, domains, orgDomains } from "@server/db";
import response from "@server/lib/response";
import logger from "@server/logger";
import { type GetBatchedCertificateResponse } from "@server/routers/certificates/types";
import HttpCode from "@server/types/HttpCode";
import { and, eq, inArray, isNotNull, or } from "drizzle-orm";
import { and, eq, inArray, or } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
@@ -63,28 +63,14 @@ async function query(orgId: string, domainList: string[]) {
})
.from(certificates)
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
.leftJoin(
.innerJoin(
orgDomains,
and(
eq(domains.domainId, orgDomains.domainId),
eq(orgDomains.orgId, orgId)
)
)
.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)
)
)
);
.where(and(inArray(certificates.domain, domainList)));
// All non resolved domain certificates might be `ns` or `wildcard`,
// which means exact domain certificates do not exist
@@ -124,27 +110,19 @@ async function query(orgId: string, domainList: string[]) {
})
.from(certificates)
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
.leftJoin(
.innerJoin(
orgDomains,
and(
eq(domains.domainId, orgDomains.domainId),
eq(orgDomains.orgId, orgId)
)
)
.leftJoin(
domainNamespaces,
eq(domains.domainId, domainNamespaces.domainId)
)
.where(
and(
eq(certificates.wildcard, true),
or(
inArray(certificates.domain, [...domainLevelDownSet]),
inArray(certificates.domain, [...wildcardDomainSet])
),
or(
isNotNull(orgDomains.orgId),
isNotNull(domainNamespaces.domainNamespaceId)
)
)
);
-8
View File
@@ -808,14 +808,6 @@ authenticated.get(
alertRule.listAlertRules
);
authenticated.post(
"/org/:orgId/alert-rule/test",
verifyValidLicense,
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.testAlertRule),
alertRule.testAlertRule
);
authenticated.get(
"/org/:orgId/alert-rule/:alertRuleId",
verifyValidLicense,
-23
View File
@@ -124,26 +124,3 @@ export interface AlertContext {
/** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>;
}
export type EmailAlertAction = {
type: "email";
userIds?: string[];
roleIds?: string[];
emails?: string[];
};
export type WebhookAlertAction = {
type: "webhook";
webhookUrl: string;
enabled: boolean;
config?: string | undefined;
};
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>;
}
+3 -51
View File
@@ -127,9 +127,6 @@ export async function verifyResourceSession(
// Extract HTTP Basic Auth credentials if present
const clientHeaderAuth = extractBasicAuth(headers);
const clientUserAgent = headers?.["user-agent"] || headers?.["User-Agent"];
const clientIsBrowser = isBrowserUserAgent(clientUserAgent);
const clientIp = requestIp
? stripPortFromHost(requestIp, badgerVersion)
: undefined;
@@ -316,14 +313,9 @@ export async function verifyResourceSession(
return allowed(res, undefined, dontStripSession);
}
// Only offer a browser redirect to clients that can actually follow one and log in
// (an interactive browser). Non-browser clients (curl, scripts, bots, etc.) just get
// an unauthorized response from Badger instead of a login redirect URL.
const redirectPath = clientIsBrowser
? `/auth/resource/${encodeURIComponent(
resource.resourceGuid
)}?redirect=${encodeURIComponent(originalRequestURL)}`
: undefined;
const redirectPath = `/auth/resource/${encodeURIComponent(
resource.resourceGuid
)}?redirect=${encodeURIComponent(originalRequestURL)}`;
// check for access token in headers
if (
@@ -1484,46 +1476,6 @@ async function getCountryCodeFromIp(ip: string): Promise<string | undefined> {
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(
headers: Record<string, string> | undefined
): string | undefined {
+1 -3
View File
@@ -34,9 +34,7 @@ const createRoleSchema = z.strictObject({
export const defaultRoleAllowedActions: ActionsEnum[] = [
ActionsEnum.getOrg,
ActionsEnum.getResource,
ActionsEnum.listResources,
ActionsEnum.getSiteResource,
ActionsEnum.listSiteResources
ActionsEnum.listResources
];
export type CreateRoleBody = z.infer<typeof createRoleSchema>;
@@ -3,13 +3,11 @@ import {
DB_TYPE,
Label,
SiteResource,
roleSiteResources,
siteNetworks,
siteResourceLabels,
siteResources,
sites,
labels,
userSiteResources
labels
} from "@server/db";
import response from "@server/lib/response";
import logger from "@server/logger";
@@ -325,48 +323,7 @@ export async function listAllSiteResourcesByOrg(
labels: labelFilter
} = parsedQuery.data;
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)
)
];
const conditions = [and(eq(siteResources.orgId, orgId))];
if (siteId != null) {
// Keep inner joins here: filtering by a specific site implies the
@@ -1,17 +1,11 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import {
db,
networks,
roleSiteResources,
siteNetworks,
userSiteResources
} from "@server/db";
import { db, networks, siteNetworks } from "@server/db";
import { siteResources, sites, SiteResource } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
import { and, asc, desc, eq } from "drizzle-orm";
import { fromError } from "zod-validation-error";
import logger from "@server/logger";
import { OpenAPITags, registry } from "@server/openApi";
@@ -165,47 +159,10 @@ export async function listSiteResources(
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
const conditions = [
eq(siteNetworks.siteId, siteId),
eq(siteResources.orgId, orgId),
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
eq(siteResources.orgId, orgId)
];
if (typeof status !== "undefined") {
+1 -3
View File
@@ -28,7 +28,6 @@ import m19 from "./scriptsPg/1.18.4";
import m20 from "./scriptsPg/1.19.0";
import m21 from "./scriptsPg/1.20.0";
import m22 from "./scriptsPg/1.21.0";
import m23 from "./scriptsPg/1.21.1";
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER
// EXCEPT FOR THE DATABASE AND THE SCHEMA
@@ -56,8 +55,7 @@ const migrations = [
{ version: "1.18.4", run: m19 },
{ version: "1.19.0", run: m20 },
{ version: "1.20.0", run: m21 },
{ version: "1.21.0", run: m22 },
{ version: "1.21.1", run: m23 }
{ version: "1.21.0", run: m22 }
// Add new migrations here as they are created
] as {
version: string;
+1 -3
View File
@@ -47,7 +47,6 @@ import m41 from "./scriptsSqlite/1.19.0";
import m42 from "./scriptsSqlite/1.19.1";
import m43 from "./scriptsSqlite/1.20.0";
import m44 from "./scriptsSqlite/1.21.0";
import m45 from "./scriptsSqlite/1.21.1";
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER
// EXCEPT FOR THE DATABASE AND THE SCHEMA
@@ -92,8 +91,7 @@ const migrations = [
{ version: "1.19.0", run: m41 },
{ version: "1.19.1", run: m42 },
{ version: "1.20.0", run: m43 },
{ version: "1.21.0", run: m44 },
{ version: "1.21.1", run: m45 }
{ version: "1.21.0", run: m44 }
// Add new migrations here as they are created
] as const;
-37
View File
@@ -1,37 +0,0 @@
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
@@ -1,43 +0,0 @@
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>
{t("remoteExitNodeNetworkingDescription")}
<a
href="https://docs.pangolin.net/manage/remote-node/backhaul"
href="https://docs.pangolin.net/placeholder"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline inline-flex items-center gap-1"
+11 -13
View File
@@ -24,21 +24,19 @@ export function ContactSalesBanner() {
<ExternalLink className="size-3.5 shrink-0" />
</Link>
{" " + t("contactSalesOr") + " "}
<span className="whitespace-nowrap">
<Link
href="https://pangolin.net/contact"
target="_blank"
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" />
</Link>
.
</span>
<Link
href="https://pangolin.net/contact"
target="_blank"
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" />
</Link>
.
</span>
</div>
</div>
</div>
);
}
}
+3 -5
View File
@@ -13,7 +13,7 @@ import {
import { InputOTP, InputOTPGroup, InputOTPSlot } from "./ui/input-otp";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import { useTranslations } from "next-intl";
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
import { REGEXP_ONLY_DIGITS } from "input-otp";
const MFA_OTP_INPUT_ID = "mfa-otp-code";
@@ -82,11 +82,9 @@ export default function MfaInputForm({
maxLength={6}
{...field}
autoComplete="one-time-code"
inputMode="text"
inputMode="numeric"
autoFocus
pattern={
REGEXP_ONLY_DIGITS_AND_CHARS
}
pattern={REGEXP_ONLY_DIGITS}
onChange={(value: string) => {
field.onChange(value);
if (value.length === 6) {
@@ -6,9 +6,7 @@ import {
AlertRuleSourceFields,
AlertRuleTriggerFields
} from "@app/components/alert-rule-editor/AlertRuleFields";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { SettingsContainer } from "@app/components/Settings";
import { SwitchInput } from "@app/components/SwitchInput";
import { Button } from "@app/components/ui/button";
import { Card, CardContent } from "@app/components/ui/card";
import {
@@ -21,7 +19,6 @@ import {
FormMessage
} from "@app/components/ui/form";
import { Input } from "@app/components/ui/input";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import {
buildFormSchema,
@@ -30,15 +27,19 @@ import {
type AlertRuleFormValues
} from "@app/lib/alertRuleForm";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import { useEnvContext } from "@app/hooks/useEnvContext";
import type { CreateAlertRuleResponse } from "@server/routers/alertRule/types";
import type { AxiosResponse } from "axios";
import { Cog, Flag, Zap, ZapIcon } from "lucide-react";
import { useTranslations } from "next-intl";
import { zodResolver } from "@hookform/resolvers/zod";
import { ChevronLeft, Cog, Flag, Zap } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useActionState, useMemo, useTransition, type ReactNode } from "react";
import { useMemo, useState, type ReactNode } from "react";
import { useFieldArray, useForm, type Resolver } from "react-hook-form";
import { useTranslations } from "next-intl";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { SwitchInput } from "@app/components/SwitchInput";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import { Badge } from "../ui/badge";
const FORM_ID = "alert-rule-form";
@@ -114,6 +115,7 @@ export default function AlertRuleGraphEditor({
const t = useTranslations();
const router = useRouter();
const api = createApiClient(useEnvContext());
const [isSaving, setIsSaving] = useState(false);
const schema = useMemo(() => buildFormSchema(t), [t]);
const form = useForm<AlertRuleFormValues>({
resolver: zodResolver(schema) as Resolver<AlertRuleFormValues>,
@@ -125,22 +127,8 @@ export default function AlertRuleGraphEditor({
name: "actions"
});
const saveAlert = async () => {
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();
const onSubmit = form.handleSubmit(async (values) => {
setIsSaving(true);
try {
const payload = formValuesToApiPayload(values);
if (isNew) {
@@ -170,37 +158,14 @@ export default function AlertRuleGraphEditor({
description: formatAxiosError(e),
variant: "destructive"
});
} finally {
setIsSaving(false);
}
// const submit = form.handleSubmit(async (values) => {
// });
// await submit();
};
const testAlert = async () => {
const isValid = await form.trigger();
if (!isValid) {
const values = form.getValues();
if (values.actions.length === 0) {
toast({
variant: "warning",
title: t("alertingNoActionsTitle"),
description: t("alertingNoActionsTestDescription")
});
}
return;
}
const values = form.getValues();
};
const [, formAction, isSaving] = useActionState(saveAlert, null);
const [isTestingAlert, startTransition] = useTransition();
});
return (
<Form {...form}>
<form id={FORM_ID} action={formAction}>
<form id={FORM_ID} onSubmit={onSubmit}>
<SettingsContainer>
<PaidFeaturesAlert tiers={tierMatrix.alertingRules} />
<div className="flex flex-col lg:flex-row gap-6 lg:gap-8 items-start">
@@ -298,29 +263,14 @@ export default function AlertRuleGraphEditor({
</FormItem>
)}
/>
<div className="flex flex-col items-center w-full gap-3">
<Button
type="submit"
className="w-full"
disabled={isSaving}
loading={isSaving}
>
{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>
<Button
type="submit"
className="w-full"
disabled={isSaving}
loading={isSaving}
>
{t("save")}
</Button>
</fieldset>
</CardContent>
</Card>
+1 -1
View File
@@ -111,7 +111,7 @@ export function useCertificate({
let certError: string | null = null;
if (restartCert.isError) {
certError = "Failed to restart";
} else if (isError || (!isLoading && data === null)) {
} else if (isError || initialCertValue === null) {
// Null value means failed to get the certificate
certError = "Failed";
}