Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] ded7946193 Bump node in the docker-dependencies group across 1 directory
Bumps the docker-dependencies group with 1 update in the / directory: node.


Updates `node` from 24-alpine to 26-alpine

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26-alpine
  dependency-type: direct:production
  dependency-group: docker-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-28 01:32:49 +00:00
39 changed files with 3452 additions and 3286 deletions
+9 -9
View File
@@ -62,7 +62,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Monitor storage space
run: |
@@ -77,7 +77,7 @@ jobs:
fi
- name: Log in to Docker Hub
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
with:
registry: docker.io
username: ${{ secrets.DOCKER_HUB_USERNAME }}
@@ -134,7 +134,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Monitor storage space
run: |
@@ -149,7 +149,7 @@ jobs:
fi
- name: Log in to Docker Hub
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
with:
registry: docker.io
username: ${{ secrets.DOCKER_HUB_USERNAME }}
@@ -201,10 +201,10 @@ jobs:
timeout-minutes: 30
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Log in to Docker Hub
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
with:
registry: docker.io
username: ${{ secrets.DOCKER_HUB_USERNAME }}
@@ -256,7 +256,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Extract tag name
id: get-tag
@@ -264,7 +264,7 @@ jobs:
shell: bash
- name: Install Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
with:
go-version: 1.25
@@ -407,7 +407,7 @@ jobs:
shell: bash
- name: Login to GitHub Container Registry (for cosign)
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
with:
registry: ghcr.io
username: ${{ github.actor }}
+2 -2
View File
@@ -21,10 +21,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: '24'
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@1e223db275d687790206a7acac4d1a11bd6fe629 # v10.4.0
- uses: actions/stale@eb5cf3af3ac0a1aa4c9c45633dd1ae542a27a899 # v10.3.0
with:
days-before-stale: 14
days-before-close: 14
+4 -4
View File
@@ -14,10 +14,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Install Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: '24'
@@ -62,7 +62,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Build Docker image sqlite
run: make dev-build-sqlite
@@ -71,7 +71,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Build Docker image pg
run: make dev-build-pg
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:24-alpine
FROM node:26-alpine
WORKDIR /app
+3145 -2042
View File
File diff suppressed because it is too large Load Diff
+65 -65
View File
@@ -32,49 +32,49 @@
"format": "prettier --write ."
},
"dependencies": {
"@asteasolutions/zod-to-openapi": "9.1.0",
"@asteasolutions/zod-to-openapi": "8.5.0",
"@devolutions/iron-remote-desktop": "https://static.pangolin.net/packages/devolutions-iron-remote-desktop-0.0.0.tgz",
"@devolutions/iron-remote-desktop-rdp": "https://static.pangolin.net/packages/devolutions-iron-remote-desktop-rdp-0.0.1.tgz",
"@aws-sdk/client-s3": "3.1098.0",
"@aws-sdk/client-s3": "3.1056.0",
"@headlessui/react": "2.2.10",
"@hookform/resolvers": "5.5.7",
"@hookform/resolvers": "5.4.0",
"@monaco-editor/react": "4.7.0",
"@node-rs/argon2": "2.0.2",
"@novnc/novnc": "^1.7.0",
"@oslojs/crypto": "1.0.1",
"@oslojs/encoding": "1.1.0",
"@radix-ui/react-avatar": "1.2.6",
"@radix-ui/react-checkbox": "1.3.11",
"@radix-ui/react-collapsible": "1.1.20",
"@radix-ui/react-dialog": "1.1.23",
"@radix-ui/react-dropdown-menu": "2.1.24",
"@radix-ui/react-avatar": "1.1.11",
"@radix-ui/react-checkbox": "1.3.3",
"@radix-ui/react-collapsible": "1.1.12",
"@radix-ui/react-dialog": "1.1.15",
"@radix-ui/react-dropdown-menu": "2.1.16",
"@radix-ui/react-icons": "1.3.2",
"@radix-ui/react-label": "2.1.15",
"@radix-ui/react-popover": "1.1.23",
"@radix-ui/react-progress": "1.1.16",
"@radix-ui/react-radio-group": "1.4.7",
"@radix-ui/react-scroll-area": "1.2.18",
"@radix-ui/react-select": "2.3.7",
"@radix-ui/react-separator": "1.1.15",
"@radix-ui/react-slot": "1.3.3",
"@radix-ui/react-switch": "1.3.7",
"@radix-ui/react-tabs": "1.1.21",
"@radix-ui/react-toast": "1.2.23",
"@radix-ui/react-tooltip": "1.2.16",
"@radix-ui/react-label": "2.1.8",
"@radix-ui/react-popover": "1.1.15",
"@radix-ui/react-progress": "1.1.8",
"@radix-ui/react-radio-group": "1.3.8",
"@radix-ui/react-scroll-area": "1.2.10",
"@radix-ui/react-select": "2.2.6",
"@radix-ui/react-separator": "1.1.8",
"@radix-ui/react-slot": "1.2.4",
"@radix-ui/react-switch": "1.2.6",
"@radix-ui/react-tabs": "1.1.13",
"@radix-ui/react-toast": "1.2.15",
"@radix-ui/react-tooltip": "1.2.8",
"@react-email/body": "0.3.0",
"@react-email/components": "1.0.12",
"@react-email/render": "2.1.0",
"@react-email/render": "2.0.8",
"@react-email/tailwind": "2.0.7",
"@simplewebauthn/browser": "13.3.0",
"@simplewebauthn/server": "13.3.2",
"@simplewebauthn/server": "13.3.1",
"@tailwindcss/forms": "0.5.11",
"@tanstack/react-query": "5.101.4",
"@tanstack/react-query": "5.100.14",
"@tanstack/react-table": "8.21.3",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-web-links": "^0.12.0",
"@xterm/xterm": "^6.0.0",
"arctic": "3.7.0",
"axios": "1.19.0",
"axios": "1.16.1",
"better-sqlite3": "11.9.1",
"canvas-confetti": "1.9.4",
"class-variance-authority": "0.7.1",
@@ -86,61 +86,61 @@
"d3": "7.9.0",
"drizzle-orm": "0.45.2",
"express": "5.2.1",
"express-rate-limit": "8.6.1",
"express-rate-limit": "8.5.2",
"glob": "13.0.6",
"helmet": "8.3.0",
"helmet": "8.2.0",
"http-errors": "2.0.1",
"input-otp": "1.4.2",
"ioredis": "5.11.1",
"ioredis": "5.11.0",
"jmespath": "0.16.0",
"js-yaml": "5.2.2",
"js-yaml": "4.2.0",
"jsonwebtoken": "9.0.3",
"lucide-react": "1.27.0",
"lucide-react": "1.17.0",
"maxmind": "5.0.6",
"moment": "2.30.1",
"next": "16.2.12",
"next-intl": "4.13.4",
"next": "16.2.6",
"next-intl": "4.13.0",
"next-themes": "0.4.6",
"nextjs-toploader": "3.9.17",
"node-cache": "5.1.2",
"nodemailer": "9.0.3",
"nodemailer": "9.0.1",
"oslo": "1.2.1",
"pg": "8.22.0",
"posthog-node": "5.46.1",
"pg": "8.21.0",
"posthog-node": "5.35.6",
"qrcode.react": "4.2.0",
"react": "19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "19.2.8",
"react": "19.2.6",
"react-day-picker": "9.14.0",
"react-dom": "19.2.6",
"react-easy-sort": "1.8.0",
"react-hook-form": "7.83.0",
"react-icons": "5.7.0",
"recharts": "3.10.1",
"react-hook-form": "7.76.1",
"react-icons": "5.6.0",
"recharts": "3.8.1",
"reodotdev": "1.1.0",
"semver": "7.8.5",
"semver": "7.8.1",
"sshpk": "1.18.0",
"stripe": "22.3.2",
"stripe": "22.2.0",
"swagger-ui-express": "5.0.1",
"tailwind-merge": "3.6.0",
"topojson-client": "3.1.0",
"tw-animate-css": "1.4.0",
"use-debounce": "10.1.1",
"uuid": "14.0.1",
"uuid": "14.0.0",
"vaul": "1.1.2",
"visionscarto-world-atlas": "1.0.0",
"winston": "3.19.0",
"winston-daily-rotate-file": "5.0.0",
"ws": "8.21.1",
"ws": "8.21.0",
"yaml": "2.9.0",
"yargs": "18.1.0",
"yargs": "18.0.0",
"zod": "4.4.3",
"zod-validation-error": "5.0.0"
},
"devDependencies": {
"@dotenvx/dotenvx": "2.19.0",
"@dotenvx/dotenvx": "1.69.1",
"@esbuild-plugins/tsconfig-paths": "0.1.2",
"@react-email/ui": "^6.9.1",
"@tailwindcss/postcss": "4.3.3",
"@tanstack/react-query-devtools": "5.101.4",
"@react-email/ui": "^6.5.0",
"@tailwindcss/postcss": "4.3.0",
"@tanstack/react-query-devtools": "5.100.14",
"@types/better-sqlite3": "7.6.13",
"@types/cookie-parser": "1.4.10",
"@types/cors": "2.8.19",
@@ -151,14 +151,14 @@
"@types/jmespath": "0.15.2",
"@types/js-yaml": "4.0.9",
"@types/jsonwebtoken": "9.0.10",
"@types/node": "26.1.2",
"@types/nodemailer": "8.0.1",
"@types/node": "25.9.1",
"@types/nodemailer": "8.0.0",
"@types/nprogress": "0.2.3",
"@types/pg": "8.20.0",
"@types/react": "19.2.17",
"@types/react": "19.2.15",
"@types/react-dom": "19.2.3",
"@types/semver": "7.7.1",
"@types/sshpk": "1.17.5",
"@types/sshpk": "1.17.4",
"@types/swagger-ui-express": "4.1.8",
"@types/topojson-client": "3.1.5",
"@types/ws": "8.18.1",
@@ -166,21 +166,21 @@
"babel-plugin-react-compiler": "1.0.0",
"drizzle-kit": "0.31.10",
"esbuild": "0.28.1",
"esbuild-node-externals": "1.23.1",
"eslint": "10.8.0",
"eslint-config-next": "16.2.12",
"postcss": "8.5.25",
"prettier": "3.9.6",
"react-email": "6.9.1",
"tailwindcss": "4.3.3",
"tsc-alias": "1.9.1",
"tsx": "4.23.1",
"typescript": "7.0.2",
"typescript-eslint": "8.65.0"
"esbuild-node-externals": "1.22.0",
"eslint": "10.4.0",
"eslint-config-next": "16.2.6",
"postcss": "8.5.15",
"prettier": "3.8.3",
"react-email": "6.5.0",
"tailwindcss": "4.3.0",
"tsc-alias": "1.8.17",
"tsx": "4.22.3",
"typescript": "6.0.3",
"typescript-eslint": "8.60.0"
},
"overrides": {
"esbuild": "0.28.1",
"dompurify": "3.4.0",
"postcss": "8.5.25"
"postcss": "8.5.15"
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ export const domains = pgTable("domains", {
domainId: varchar("domainId").primaryKey(),
baseDomain: varchar("baseDomain").notNull(),
configManaged: boolean("configManaged").notNull().default(false),
type: varchar("type").$type<"ns" | "cname" | "wildcard">(),
type: varchar("type"), // "ns", "cname", "wildcard"
verified: boolean("verified").notNull().default(false),
failed: boolean("failed").notNull().default(false),
tries: integer("tries").notNull().default(0),
+1 -1
View File
@@ -15,7 +15,7 @@ export const domains = sqliteTable("domains", {
configManaged: integer("configManaged", { mode: "boolean" })
.notNull()
.default(false),
type: text("type").$type<"ns" | "cname" | "wildcard">(),
type: text("type"), // "ns", "cname", "wildcard"
verified: integer("verified", { mode: "boolean" }).notNull().default(false),
failed: integer("failed", { mode: "boolean" }).notNull().default(false),
tries: integer("tries").notNull().default(0),
+5 -134
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import { db, logsDb, statusHistory } from "@server/db";
import { and, eq, gte, lt, asc, desc, inArray, max, sql } from "drizzle-orm";
import { and, eq, gte, lt, asc, desc } from "drizzle-orm";
import { regionalCache as cache } from "#dynamic/lib/cache";
const STATUS_HISTORY_CACHE_TTL = 60; // seconds
@@ -41,7 +41,6 @@ export async function getCachedStatusHistory(
return cached;
}
console.time(`[getCachedStatusHistory/${entityType}=${entityId}]`);
// Anchor to local midnight (UTC when tzOffsetMinutes is 0) so the query
// window aligns with stable calendar days for the requesting client
const todayMidnightSec = localMidnightSec(tzOffsetMinutes);
@@ -77,14 +76,12 @@ export async function getCachedStatusHistory(
const priorStatus = lastKnownEvent?.status ?? null;
console.time(`[computeBuckets/${entityType}=${entityId}]`);
const { buckets, totalDowntime } = computeBuckets(
events,
days,
priorStatus,
tzOffsetMinutes
);
console.timeEnd(`[computeBuckets/${entityType}=${entityId}]`);
const totalWindow = days * 86400;
const overallUptime =
totalWindow > 0
@@ -99,7 +96,6 @@ export async function getCachedStatusHistory(
totalDowntimeSeconds: totalDowntime
};
console.timeEnd(`[getCachedStatusHistory/${entityType}=${entityId}]`);
await cache.set(cacheKey, result, STATUS_HISTORY_CACHE_TTL);
return result;
}
@@ -268,7 +264,9 @@ export function computeBuckets(
// Shift by the client's offset before formatting so the label reflects
// their local calendar date rather than the UTC date of dayStartSec
const dateStr = new Date((dayStartSec + tzOffsetMinutes * 60) * 1000)
const dateStr = new Date(
(dayStartSec + tzOffsetMinutes * 60) * 1000
)
.toISOString()
.slice(0, 10);
@@ -303,133 +301,6 @@ export function computeBuckets(
status
});
}
return { buckets, totalDowntime };
}
export type BatchedStatusHistoryResponse = Record<
string,
StatusHistoryResponse
>;
export async function getBatchedStatusHistory(
entityType: string,
entityIds: number[],
days: number,
tzOffsetMinutes: number = 0
): Promise<BatchedStatusHistoryResponse> {
console.time(
`[getBatchedStatusHistory/${entityType}=(${entityIds.join(" ,")})]`
);
// Anchor to local midnight (UTC when tzOffsetMinutes is 0) so the query
// window aligns with stable calendar days for the requesting client
const todayMidnightSec = localMidnightSec(tzOffsetMinutes);
const startSec = todayMidnightSec - days * 86400;
const events = await logsDb
.select()
.from(statusHistory)
.where(
and(
eq(statusHistory.entityType, entityType),
inArray(statusHistory.entityId, entityIds),
gte(statusHistory.timestamp, startSec)
)
)
.orderBy(asc(statusHistory.timestamp));
// Fetch the last known state before the window so that entities that
// haven't changed status recently still show the correct status rather
// than appearing as "no_data".
/**
* If we used only postgres, we would have used `SELECT DISTINCT ON` to get the
* latest event for each `entityId`,
* but it doesn't work on SQLite, so instead we use a subquery,
* the `ROW_NUMBER() OVER PARTITION` allows to assign a number
* to each row ordered by the timestamp, the number 1 is the first one appearing in
* the specified order, then the next and more, we only want the highest timestamp,
* so we get for `row_number=1`
*/
const lastKnowEventsSub = logsDb
.select({
entityId: statusHistory.entityId,
status: statusHistory.status,
timestamp: statusHistory.timestamp,
row_number:
sql<number>`ROW_NUMBER() OVER (PARTITION BY ${statusHistory.entityId} ORDER BY ${statusHistory.timestamp} DESC)`.as(
"row_number"
)
})
.from(statusHistory)
.where(
and(
eq(statusHistory.entityType, entityType),
inArray(statusHistory.entityId, entityIds),
lt(statusHistory.timestamp, startSec)
)
)
.as("sub");
const lastKnownEvents = await logsDb
.select({
entityId: lastKnowEventsSub.entityId,
status: lastKnowEventsSub.status,
timestamp: lastKnowEventsSub.timestamp
})
.from(lastKnowEventsSub)
.where(eq(lastKnowEventsSub.row_number, 1));
const eventStatusMap: Record<
number,
{
events: typeof events;
lastKnownEvent: (typeof lastKnownEvents)[number] | null;
}
> = {};
for (const entityId of entityIds) {
eventStatusMap[entityId] = {
events: events.filter((ev) => ev.entityId === entityId),
lastKnownEvent:
lastKnownEvents.find((ev) => ev.entityId === entityId) ?? null
};
}
const result: BatchedStatusHistoryResponse = {};
console.time(`[computeBuckets/${entityType}=(${entityIds.join(" ,")})]`);
for (const entityId in eventStatusMap) {
const event = eventStatusMap[Number(entityId)];
const priorStatus = event.lastKnownEvent?.status ?? null;
const { buckets, totalDowntime } = computeBuckets(
event.events,
days,
priorStatus,
tzOffsetMinutes
);
const totalWindow = days * 86400;
const overallUptime =
totalWindow > 0
? Math.max(
0,
((totalWindow - totalDowntime) / totalWindow) * 100
)
: 100;
result[entityId] = {
entityType,
entityId: Number(entityId),
days: buckets,
overallUptimePercent: Math.round(overallUptime * 100) / 100,
totalDowntimeSeconds: totalDowntime
};
}
console.timeEnd(`[computeBuckets/${entityType}=(${entityIds.join(" ,")})]`);
console.timeEnd(
`[getBatchedStatusHistory/${entityType}=(${entityIds.join(" ,")})]`
);
return result;
}
-19
View File
@@ -1,29 +1,10 @@
import {
getResourceRuleValueValidationError,
isValidDomain,
isValidUrlGlobPattern
} from "./validators";
import { assertEquals } from "@test/assert";
function runTests() {
console.log("Running domain validation tests...");
assertEquals(
isValidDomain("example.com"),
true,
"Standard ASCII domain should be valid"
);
assertEquals(
isValidDomain("xn--e1afmkfd.xn--p1ai"),
true,
"Punycode IDN domain should be valid"
);
assertEquals(
isValidDomain("example.invalid-tld"),
false,
"Domain with unknown TLD should be invalid"
);
console.log("Running URL pattern validation tests...");
// Test valid patterns
+2 -3
View File
@@ -171,10 +171,9 @@ export function isValidDomain(domain: string): boolean {
if (!/^[a-zA-Z0-9-]+$/.test(label)) return false;
}
// TLD should be at least 2 characters. Punycode TLDs can contain digits
// and hyphens, so validity is ultimately enforced by the TLD allowlist.
// TLD should be at least 2 characters and contain only letters
const tld = labels[labels.length - 1];
if (tld.length < 2) return false;
if (tld.length < 2 || !/^[a-zA-Z]+$/.test(tld)) return false;
// Check if TLD is in the list of valid TLDs
if (!validTlds.includes(tld.toUpperCase())) return false;
@@ -1,190 +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 { 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, or } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
const getCertificateParamSchema = z.strictObject({
orgId: z.string()
});
const getCertificateQuerySchema = z.object({
domains: z.preprocess(
(val) => {
if (val === undefined || val === null || val === "") {
return undefined;
}
if (Array.isArray(val)) {
return val;
}
// the array is returned as this
if (typeof val === "string") {
return val.split(",");
}
return undefined;
},
z.array(z.string().min(1).max(255))
)
});
async function query(orgId: string, domainList: string[]) {
// Try to get CNAME certificates first
let existingCertificates = await db
.select({
certId: certificates.certId,
domain: certificates.domain,
wildcard: certificates.wildcard,
status: certificates.status,
expiresAt: certificates.expiresAt,
lastRenewalAttempt: certificates.lastRenewalAttempt,
createdAt: certificates.createdAt,
updatedAt: certificates.updatedAt,
errorMessage: certificates.errorMessage,
renewalCount: certificates.renewalCount,
domainId: domains.domainId,
domainType: domains.type
})
.from(certificates)
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
.innerJoin(
orgDomains,
and(
eq(domains.domainId, orgDomains.domainId),
eq(orgDomains.orgId, orgId)
)
)
.where(and(inArray(certificates.domain, domainList)));
// All non resolved domain certificates might be `ns` or `wildcard`,
// which means exact domain certificates do not
const nonAvailableCertificates = existingCertificates
.filter((cert) => !domainList.includes(cert.domain))
.map((cert) => cert.domain);
if (nonAvailableCertificates.length > 0) {
const domainLevelDownSet = new Set<string>();
const wildcardDomainSet = new Set<string>();
for (const domain of nonAvailableCertificates) {
const domainLevelDown = domain.split(".").slice(1).join(".");
const wildcardPrefixed = `*.${domainLevelDown}`;
domainLevelDownSet.add(domainLevelDown);
wildcardDomainSet.add(wildcardPrefixed);
}
// Need to map the certificates to each domain
const wildcardCertificates = await db
.select({
certId: certificates.certId,
domain: certificates.domain,
wildcard: certificates.wildcard,
status: certificates.status,
expiresAt: certificates.expiresAt,
lastRenewalAttempt: certificates.lastRenewalAttempt,
createdAt: certificates.createdAt,
updatedAt: certificates.updatedAt,
errorMessage: certificates.errorMessage,
renewalCount: certificates.renewalCount,
domainId: domains.domainId,
domainType: domains.type
})
.from(certificates)
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
.innerJoin(
orgDomains,
and(
eq(domains.domainId, orgDomains.domainId),
eq(orgDomains.orgId, orgId)
)
)
.where(
and(
eq(certificates.wildcard, true),
or(
inArray(certificates.domain, [...domainLevelDownSet]),
inArray(certificates.domain, [...wildcardDomainSet])
)
)
);
existingCertificates.push(...wildcardCertificates);
}
const certificateMap: Record<string, any> = {};
for (const domain of domainList) {
const domainLevelDown = domain.split(".").slice(1).join(".");
const wildcardPrefixed = `*.${domainLevelDown}`;
certificateMap[domain] =
existingCertificates.find(
(cert) =>
cert.domain === domain ||
cert.domain === domainLevelDown ||
cert.domain === wildcardPrefixed
) ?? null;
}
return certificateMap;
}
export async function getBatchedCertificates(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = getCertificateParamSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const parsedQuery = getCertificateQuerySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error).toString()
)
);
}
const { domains } = parsedQuery.data;
const cert = await query(orgId, domains);
return response<GetBatchedCertificateResponse>(res, {
data: cert,
success: true,
error: false,
message: "Certificates retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
@@ -14,4 +14,3 @@
export * from "./getCertificate";
export * from "./restartCertificate";
export * from "./syncCertToNewts";
export * from "./getBatchedCertificates";
@@ -11,16 +11,18 @@
* This file is not licensed under the AGPLv3.
*/
import { certificates, db } from "@server/db";
import response from "@server/lib/response";
import logger from "@server/logger";
import { registry } from "@server/openApi";
import HttpCode from "@server/types/HttpCode";
import { eq } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { certificates, db } from "@server/db";
import { sites } from "@server/db";
import { eq, and } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import stoi from "@server/lib/stoi";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
const restartCertificateParamsSchema = z.strictObject({
certId: z.coerce.number().int().positive(),
-15
View File
@@ -175,13 +175,6 @@ authenticated.get(
certificates.getCertificate
);
authenticated.get(
"/org/:orgId/batched-certificates",
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.getCertificate),
certificates.getBatchedCertificates
);
authenticated.post(
"/org/:orgId/certificate/:certId/restart",
verifyValidLicense,
@@ -860,14 +853,6 @@ authenticated.get(
healthChecks.getHealthCheckStatusHistory
);
authenticated.get(
"/org/:orgId/health-check-status-histories",
verifyValidLicense,
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.getTarget),
healthChecks.getBatchedHealthCheckStatusHistory
);
authenticated.get(
"/client/:clientId/verify-associations-cache",
verifyClientAccess,
@@ -1,96 +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 response from "@server/lib/response";
import {
getBatchedStatusHistory,
type BatchedStatusHistoryResponse
} from "@server/lib/statusHistory";
import logger from "@server/logger";
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";
const healthCheckIdParamsSchema = z.object({
days: z
.string()
.optional()
.transform((v) => (v ? parseInt(v, 10) : 90)),
// Minutes to add to UTC to get the requesting client's local time
// (e.g. Australia/Sydney standard time is 600). Optional and
// defaults to 0 (UTC) so older clients keep the prior behavior.
tzOffsetMinutes: z
.string()
.optional()
.transform((v) => (v ? parseInt(v, 10) : 0)),
healthCheckIds: z
.preprocess((val) => {
if (val === undefined || val === null || val === "") {
return undefined;
}
const raw = Array.isArray(val) ? val : [val];
const nums = raw
.map((v) =>
typeof v === "string" ? parseInt(v, 10) : Number(v)
)
.filter((n) => Number.isInteger(n) && n > 0);
const unique = [...new Set(nums)];
return unique.length ? unique : undefined;
}, z.array(z.number().int().positive()))
.openapi({
description: "Filter by healthCheckIds (repeat query param)"
})
});
export async function getBatchedHealthCheckStatusHistory(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = healthCheckIdParamsSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error).toString()
)
);
}
const entityType = "health_check";
const { days, healthCheckIds, tzOffsetMinutes } = parsedQuery.data;
const data = await getBatchedStatusHistory(
entityType,
healthCheckIds,
days,
tzOffsetMinutes
);
return response<BatchedStatusHistoryResponse>(res, {
data,
success: true,
error: false,
message: "Status history retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
@@ -16,4 +16,3 @@ export * from "./createHealthCheck";
export * from "./updateHealthCheck";
export * from "./deleteHealthCheck";
export * from "./getStatusHistory";
export * from "./getBatchedStatusHistory";
+2 -9
View File
@@ -1,11 +1,9 @@
import type { Domain } from "@server/db";
export type GetCertificateResponse = {
certId: number;
domain: string;
domainId: string;
wildcard: boolean;
domainType: Domain["type"];
domainType: string;
status: string; // pending, requested, valid, expired, failed
expiresAt: string | null;
lastRenewalAttempt: Date | null;
@@ -13,9 +11,4 @@ export type GetCertificateResponse = {
updatedAt: number;
errorMessage?: string | null;
renewalCount: number;
};
export type GetBatchedCertificateResponse = Record<
string,
GetCertificateResponse | null
>;
};
+1 -20
View File
@@ -319,13 +319,6 @@ authenticated.get(
site.getSiteStatusHistory
);
authenticated.get(
"/org/:orgId/site-status-histories",
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.listSites),
site.getBatchedSiteStatusHistory
);
// Site Resource endpoints
authenticated.put(
"/org/:orgId/site-resource",
@@ -476,13 +469,6 @@ authenticated.get(
resource.getResourceStatusHistory
);
authenticated.get(
"/org/:orgId/resource-status-histories",
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.listResources),
resource.getBatchedResourceStatusHistory
);
authenticated.get(
"/org/:orgId/resources",
verifyOrgAccess,
@@ -1411,12 +1397,6 @@ authenticated.put(
// Auth routes
export const authRouter = Router();
unauthenticated.use("/auth", authRouter);
// Register setup-check BEFORE the global auth rate limiter.
// This endpoint is called on every dashboard root page load (pure boolean
// read, no secrets) and must not consume the auth rate-limit budget.
authRouter.get("/initial-setup-complete", auth.initialSetupComplete);
authRouter.use(
rateLimit({
windowMs:
@@ -1721,6 +1701,7 @@ authRouter.post("/idp/:idpId/oidc/generate-url", idp.generateOidcUrl);
authRouter.post("/idp/:idpId/oidc/validate-callback", idp.validateOidcCallback);
authRouter.put("/set-server-admin", auth.setServerAdmin);
authRouter.get("/initial-setup-complete", auth.initialSetupComplete);
authRouter.post("/validate-setup-token", auth.validateSetupToken);
// Security Key routes
@@ -1,83 +0,0 @@
import response from "@server/lib/response";
import {
getBatchedStatusHistory,
type BatchedStatusHistoryResponse
} from "@server/lib/statusHistory";
import logger from "@server/logger";
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";
const resourceIdParamsSchema = z.object({
days: z
.string()
.optional()
.transform((v) => (v ? parseInt(v, 10) : 90)),
// Minutes to add to UTC to get the requesting client's local time
// (e.g. Australia/Sydney standard time is 600). Optional and
// defaults to 0 (UTC) so older clients keep the prior behavior.
tzOffsetMinutes: z
.string()
.optional()
.transform((v) => (v ? parseInt(v, 10) : 0)),
resourceIds: z
.preprocess((val) => {
if (val === undefined || val === null || val === "") {
return undefined;
}
const raw = Array.isArray(val) ? val : [val];
const nums = raw
.map((v) =>
typeof v === "string" ? parseInt(v, 10) : Number(v)
)
.filter((n) => Number.isInteger(n) && n > 0);
const unique = [...new Set(nums)];
return unique.length ? unique : undefined;
}, z.array(z.number().int().positive()))
.openapi({
description: "Filter by resourceIds (repeat query param)"
})
});
export async function getBatchedResourceStatusHistory(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = resourceIdParamsSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error).toString()
)
);
}
const entityType = "resource";
const { days, resourceIds, tzOffsetMinutes } = parsedQuery.data;
const data = await getBatchedStatusHistory(
entityType,
resourceIds,
days,
tzOffsetMinutes
);
return response<BatchedStatusHistoryResponse>(res, {
data,
success: true,
error: false,
message: "Status history retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
-1
View File
@@ -33,5 +33,4 @@ export * from "./removeUserFromResource";
export * from "./listAllResourceNames";
export * from "./removeEmailFromResourceWhitelist";
export * from "./getStatusHistory";
export * from "./getBatchedStatusHistory";
export * from "./getResourcePolicies";
@@ -1,83 +0,0 @@
import response from "@server/lib/response";
import {
getBatchedStatusHistory,
type BatchedStatusHistoryResponse
} from "@server/lib/statusHistory";
import logger from "@server/logger";
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";
const siteIdParamsSchema = z.object({
days: z
.string()
.optional()
.transform((v) => (v ? parseInt(v, 10) : 90)),
// Minutes to add to UTC to get the requesting client's local time
// (e.g. Australia/Sydney standard time is 600). Optional and
// defaults to 0 (UTC) so older clients keep the prior behavior.
tzOffsetMinutes: z
.string()
.optional()
.transform((v) => (v ? parseInt(v, 10) : 0)),
siteIds: z
.preprocess((val) => {
if (val === undefined || val === null || val === "") {
return undefined;
}
const raw = Array.isArray(val) ? val : [val];
const nums = raw
.map((v) =>
typeof v === "string" ? parseInt(v, 10) : Number(v)
)
.filter((n) => Number.isInteger(n) && n > 0);
const unique = [...new Set(nums)];
return unique.length ? unique : undefined;
}, z.array(z.number().int().positive()))
.openapi({
description: "Filter by siteIds (repeat query param)"
})
});
export async function getBatchedSiteStatusHistory(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = siteIdParamsSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error).toString()
)
);
}
const entityType = "site";
const { days, siteIds, tzOffsetMinutes } = parsedQuery.data;
const data = await getBatchedStatusHistory(
entityType,
siteIds,
days,
tzOffsetMinutes
);
return response<BatchedStatusHistoryResponse>(res, {
data,
success: true,
error: false,
message: "Status history retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
-1
View File
@@ -1,6 +1,5 @@
export * from "./getSite";
export * from "./getStatusHistory";
export * from "./getBatchedStatusHistory";
export * from "./createSite";
export * from "./deleteSite";
export * from "./updateSite";
@@ -6,8 +6,6 @@ import { internal } from "@app/lib/api";
import { authCookieHeader } from "@app/lib/api/cookies";
import { getCachedOrg } from "@app/lib/api/getCachedOrg";
import OrgProvider from "@app/providers/OrgProvider";
import { build } from "@server/build";
import type { GetBatchedCertificateResponse } from "@server/routers/certificates/types";
import type { ListAllSiteResourcesByOrgResponse } from "@server/routers/siteResource";
import type { AxiosResponse } from "axios";
import type { Metadata } from "next";
@@ -101,42 +99,6 @@ export default async function ClientResourcesPage(
};
}
);
// Prefetched in one batched call so the table doesn't fire a separate
// certificate request per visible row once it mounts on the client.
const certDomains = Array.from(
new Set(
internalResourceRows
.filter(
(r) =>
r.mode === "http" &&
!r.alias &&
r.ssl &&
r.domainId &&
r.fullDomain
)
.map((r) => r.fullDomain as string)
)
);
let initialCertificates: GetBatchedCertificateResponse | undefined;
if (build !== "oss" && certDomains.length > 0) {
try {
const certSearchParams = new URLSearchParams(
certDomains.map((domain) => ["domains", domain])
);
const certRes = await internal.get<
AxiosResponse<GetBatchedCertificateResponse>
>(
`/org/${params.orgId}/batched-certificates?${certSearchParams.toString()}`,
await authCookieHeader()
);
initialCertificates = certRes.data.data;
} catch {
// leave undefined so each row falls back to fetching its own
}
}
return (
<>
<SettingsSectionTitle
@@ -155,7 +117,6 @@ export default async function ClientResourcesPage(
pageIndex: pagination.page - 1,
pageSize: pagination.pageSize
}}
initialCertificates={initialCertificates}
/>
</OrgProvider>
</>
@@ -5,8 +5,6 @@ import PublicResourcesBanner from "@app/components/PublicResourcesBanner";
import { internal } from "@app/lib/api";
import { authCookieHeader } from "@app/lib/api/cookies";
import OrgProvider from "@app/providers/OrgProvider";
import { build } from "@server/build";
import type { GetBatchedCertificateResponse } from "@server/routers/certificates/types";
import type { GetOrgResponse } from "@server/routers/org";
import type { ListResourcesResponse } from "@server/routers/resource";
import { GetSiteResponse } from "@server/routers/site/getSite";
@@ -62,7 +60,29 @@ export default async function ProxyResourcesPage(
searchParams.get("siteId") ?? undefined
);
let initialFilterSite: {
siteId: number;
name: string;
type: string;
} | null = null;
if (siteIdParam) {
try {
const siteRes = await internal.get(
`/site/${siteIdParam}`,
await authCookieHeader()
);
const s = (siteRes.data as ResponseT<GetSiteResponse>).data;
if (s && s.orgId === params.orgId) {
initialFilterSite = {
siteId: s.siteId,
name: s.name,
type: s.type
};
}
} catch {
// leave null
}
}
let org = null;
try {
@@ -120,34 +140,6 @@ export default async function ProxyResourcesPage(
health: (resource.health as ResourceRow["health"]) ?? undefined
};
});
// Prefetched in one batched call so the table doesn't fire a separate
// certificate request per visible row once it mounts on the client.
const certDomains = Array.from(
new Set(
resourceRows
.filter((r) => r.ssl && r.fullDomain)
.map((r) => r.fullDomain as string)
)
);
let initialCertificates: GetBatchedCertificateResponse | undefined;
if (build !== "oss" && certDomains.length > 0) {
try {
const certSearchParams = new URLSearchParams(
certDomains.map((domain) => ["domains", domain])
);
const certRes = await internal.get<
AxiosResponse<GetBatchedCertificateResponse>
>(
`/org/${params.orgId}/batched-certificates?${certSearchParams.toString()}`,
await authCookieHeader()
);
initialCertificates = certRes.data.data;
} catch {
// leave undefined so each row falls back to fetching its own
}
}
return (
<>
<SettingsSectionTitle
@@ -166,7 +158,7 @@ export default async function ProxyResourcesPage(
pageIndex: pagination.page - 1,
pageSize: pagination.pageSize
}}
initialCertificates={initialCertificates}
initialFilterSite={initialFilterSite}
/>
</OrgProvider>
</>
+3 -8
View File
@@ -29,19 +29,14 @@ export default async function Page(props: {
const user = await verifySession({ skipCheckVerifyEmail: true });
let complete: boolean | null = null; // null means "unknown" (request errored)
let complete = false;
try {
const setupRes = await internal.get<
AxiosResponse<InitialSetupCompleteResponse>
>(`/auth/initial-setup-complete`, await authCookieHeader());
complete = setupRes.data.data.complete;
} catch (e) {
// Swallow errors (e.g. 429 rate limit, 500, network failure).
// Only redirect to initial-setup when the server *confirms* setup
// is incomplete (complete === false). If the request itself failed we
// cannot tell, so fall through to the login redirect instead.
}
if (complete === false) {
} catch (e) {}
if (!complete) {
redirect("/auth/initial-setup");
}
+1
View File
@@ -412,6 +412,7 @@ function AuthPageSettings({
fullDomain={
loginPage.fullDomain
}
autoFetch={true}
showLabel={true}
polling={true}
/>
+6 -3
View File
@@ -5,7 +5,6 @@ import { FileBadge, RotateCw } from "lucide-react";
import { useCertificate } from "@app/hooks/useCertificate";
import type { GetCertificateResponse } from "@server/routers/certificates/types";
import { useTranslations } from "next-intl";
import { durationToMs } from "@app/lib/durationToMs";
export type CertificateStatusContentProps = {
cert: GetCertificateResponse | null;
@@ -33,7 +32,8 @@ export function CertificateStatusContent({
const labelClass =
"inline-flex shrink-0 items-center self-center text-sm font-medium leading-normal";
const valueClass = "inline-flex items-center gap-2 text-sm leading-normal";
const valueClass =
"inline-flex items-center gap-2 text-sm leading-normal";
const handleRefresh = async () => {
await refreshCert();
@@ -187,6 +187,7 @@ type CertificateStatusProps = {
orgId: string;
domainId: string;
fullDomain: string;
autoFetch?: boolean;
showLabel?: boolean;
className?: string;
onRefresh?: () => void;
@@ -198,16 +199,18 @@ export default function CertificateStatus({
orgId,
domainId,
fullDomain,
autoFetch = true,
showLabel = true,
className = "",
onRefresh,
polling = false,
pollingInterval = durationToMs(5, "seconds")
pollingInterval = 5000
}: CertificateStatusProps) {
const hook = useCertificate({
orgId,
domainId,
fullDomain,
autoFetch,
polling,
pollingInterval
});
+4 -26
View File
@@ -1,6 +1,6 @@
"use client";
import { UptimeMiniBar } from "@app/components/UptimeMiniBar";
import UptimeMiniBar from "@app/components/UptimeMiniBar";
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import HealthCheckCredenza, {
@@ -51,8 +51,6 @@ import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import { cn } from "@app/lib/cn";
import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover";
import { orgQueries } from "@app/lib/queries";
import { useQuery } from "@tanstack/react-query";
type StandaloneHealthChecksTableProps = {
orgId: string;
@@ -83,8 +81,6 @@ function formatTarget(row: HealthCheckRow): string {
return `${scheme}://${host}${port}${path}`;
}
const HEALTH_CHECK_STATUS_HISTORY_DAYS = 30;
export default function HealthChecksTable({
orgId,
healthChecks,
@@ -161,20 +157,6 @@ export default function HealthChecksTable({
const rows = healthChecks;
const healthCheckIds = useMemo(
() => rows.map((r) => r.targetHealthCheckId),
[rows]
);
const statusHistoryQuery = useQuery({
...orgQueries.batchedHealthCheckStatusHistory({
orgId,
healthCheckIds,
days: HEALTH_CHECK_STATUS_HISTORY_DAYS
}),
enabled: healthCheckIds.length > 0
});
function refreshList() {
startRefresh(() => {
router.refresh();
@@ -565,13 +547,9 @@ export default function HealthChecksTable({
cell: ({ row }) => {
return (
<UptimeMiniBar
isLoading={statusHistoryQuery.isLoading}
data={
statusHistoryQuery.data?.[
row.original.targetHealthCheckId
]
}
days={HEALTH_CHECK_STATUS_HISTORY_DAYS}
orgId={orgId}
healthCheckId={row.original.targetHealthCheckId}
days={30}
/>
);
}
+2 -9
View File
@@ -37,7 +37,6 @@ import { getPrivateResourceSettingsHref } from "@app/lib/launcherResourceAdminHr
import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn";
import { build } from "@server/build";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import type { GetBatchedCertificateResponse } from "@server/routers/certificates/types";
import { UpdateSiteResourceResponse } from "@server/routers/siteResource";
import type { PaginationState } from "@tanstack/react-table";
import { AxiosResponse } from "axios";
@@ -137,16 +136,13 @@ type ClientResourcesTableProps = {
orgId: string;
pagination: PaginationState;
rowCount: number;
/** Certificates prefetched on the server, keyed by full domain. */
initialCertificates?: GetBatchedCertificateResponse;
};
export default function PrivateResourcesTable({
internalResources,
orgId,
pagination,
rowCount,
initialCertificates
rowCount
}: ClientResourcesTableProps) {
const router = useRouter();
const {
@@ -436,9 +432,6 @@ export default function PrivateResourcesTable({
orgId={resourceRow.orgId}
domainId={domainId}
fullDomain={fullDomain}
initialCertValue={
initialCertificates?.[fullDomain]
}
/>
) : null}
<div className="">
@@ -592,7 +585,7 @@ export default function PrivateResourcesTable({
];
return cols;
}, [orgId, t, searchParams, initialCertificates]);
}, [orgId, t, searchParams]);
function handleFilterChange(
column: string,
+26 -45
View File
@@ -7,7 +7,8 @@ import {
ResourceSitesStatusCell,
type ResourceSiteRow
} from "@app/components/ResourceSitesStatusCell";
import { Selectedsite } from "@app/components/site-selector";
import { Selectedsite, SitesSelector } from "@app/components/site-selector";
import { Badge } from "@app/components/ui/badge";
import { Button } from "@app/components/ui/button";
import { ExtendedColumnDef } from "@app/components/ui/data-table";
import {
@@ -17,19 +18,23 @@ import {
DropdownMenuTrigger
} from "@app/components/ui/dropdown-menu";
import { InfoPopup } from "@app/components/ui/info-popup";
import {
Popover,
PopoverContent,
PopoverTrigger
} from "@app/components/ui/popover";
import { Switch } from "@app/components/ui/switch";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useNavigationContext } from "@app/hooks/useNavigationContext";
import { useOptimisticLabels } from "@app/hooks/useOptimisticLabels";
import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { toast } from "@app/hooks/useToast";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { orgQueries } from "@app/lib/queries";
import { cn } from "@app/lib/cn";
import { dataTableFilterPopoverContentClassName } from "@app/lib/dataTableFilterPopover";
import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn";
import { build } from "@server/build";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import { UpdateResourceResponse } from "@server/routers/resource";
import type { GetBatchedCertificateResponse } from "@server/routers/certificates/types";
import { useQuery } from "@tanstack/react-query";
import type { PaginationState } from "@tanstack/react-table";
import { AxiosResponse } from "axios";
import {
@@ -40,7 +45,9 @@ import {
ChevronDown,
ChevronsUpDownIcon,
Clock,
Funnel,
MoreHorizontal,
PlusIcon,
ShieldCheck,
ShieldOff,
XCircle
@@ -50,6 +57,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import {
startTransition,
useEffect,
useMemo,
useOptimistic,
useRef,
@@ -60,11 +68,15 @@ import {
import { useDebouncedCallback } from "use-debounce";
import z from "zod";
import { ColumnFilterButton } from "./ColumnFilterButton";
import { LabelColumnFilterButton } from "./LabelColumnFilterButton";
import { LabelsTableCell } from "./LabelsTableCell";
import { SitesColumnFilterButton } from "./SitesColumnFilterButton";
import { ControlledDataTable } from "./ui/controlled-data-table";
import { UptimeMiniBar } from "./UptimeMiniBar";
import UptimeMiniBar from "./UptimeMiniBar";
import { type SelectedLabel } from "./labels-selector";
import { LabelColumnFilterButton } from "./LabelColumnFilterButton";
import { useLocalLabels } from "@app/hooks/useLocalLabels";
import { LabelsTableCell } from "./LabelsTableCell";
import { useOptimisticLabels } from "@app/hooks/useOptimisticLabels";
import { refresh } from "next/cache";
import { SitesColumnFilterButton } from "./SitesColumnFilterButton";
export type TargetHealth = {
targetId: number;
@@ -108,8 +120,6 @@ type ProxyResourcesTableProps = {
pagination: PaginationState;
rowCount: number;
initialFilterSite?: Selectedsite | null;
/** Certificates prefetched on the server, keyed by full domain. */
initialCertificates?: GetBatchedCertificateResponse;
};
const booleanSearchFilterSchema = z
@@ -117,14 +127,12 @@ const booleanSearchFilterSchema = z
.optional()
.catch(undefined);
const RESOURCE_STATUS_HISTORY_DAYS = 30;
export default function PublicResourcesTable({
resources,
orgId,
pagination,
rowCount,
initialCertificates
initialFilterSite = null
}: ProxyResourcesTableProps) {
const router = useRouter();
const {
@@ -142,24 +150,11 @@ export default function PublicResourcesTable({
const [selectedResource, setSelectedResource] =
useState<ResourceRow | null>();
const { isPaidUser } = usePaidStatus();
const [isRefreshing, startTransition] = useTransition();
const [isNavigatingToAddPage, startNavigation] = useTransition();
// Only http resources show an uptime bar, so don't ask for the others
const statusHistoryResourceIds = useMemo(
() => resources.filter((r) => r.mode === "http").map((r) => r.id),
[resources]
);
const statusHistoryQuery = useQuery({
...orgQueries.batchedResourceStatusHistory({
orgId,
resourceIds: statusHistoryResourceIds,
days: RESOURCE_STATUS_HISTORY_DAYS
}),
enabled: statusHistoryResourceIds.length > 0
});
const refreshData = () => {
startTransition(() => {
try {
@@ -412,11 +407,7 @@ export default function PublicResourcesTable({
return <span>-</span>;
}
return (
<UptimeMiniBar
isLoading={statusHistoryQuery.isLoading}
data={statusHistoryQuery.data?.[resourceRow.id]}
days={RESOURCE_STATUS_HISTORY_DAYS}
/>
<UptimeMiniBar resourceId={resourceRow.id} days={30} />
);
}
},
@@ -470,9 +461,6 @@ export default function PublicResourcesTable({
orgId={resourceRow.orgId}
domainId={domainId}
fullDomain={certHostname}
initialCertValue={
initialCertificates?.[certHostname]
}
/>
) : null}
<div className="">
@@ -637,14 +625,7 @@ export default function PublicResourcesTable({
];
return cols;
}, [
orgId,
t,
searchParams,
statusHistoryQuery.data,
statusHistoryQuery.isLoading,
initialCertificates
]);
}, [orgId, t, searchParams]);
function handleFilterChange(
column: string,
+4 -11
View File
@@ -7,7 +7,6 @@ import {
PopoverContent
} from "@app/components/ui/popover";
import { useCertificate } from "@app/hooks/useCertificate";
import type { GetCertificateResponse } from "@server/routers/certificates/types";
import { cn } from "@app/lib/cn";
import { FileBadge } from "lucide-react";
import { useTranslations } from "next-intl";
@@ -18,13 +17,11 @@ import {
useState,
type ReactNode
} from "react";
import { durationToMs } from "@app/lib/durationToMs";
type ResourceAccessCertIndicatorProps = {
orgId: string;
domainId: string;
fullDomain: string;
initialCertValue?: GetCertificateResponse | null;
};
function getStatusColor(status: string) {
@@ -46,8 +43,7 @@ function getStatusColor(status: string) {
export function ResourceAccessCertIndicator({
orgId,
domainId,
fullDomain,
initialCertValue
fullDomain
}: ResourceAccessCertIndicatorProps) {
const t = useTranslations();
const [open, setOpen] = useState(false);
@@ -57,19 +53,16 @@ export function ResourceAccessCertIndicator({
orgId,
domainId,
fullDomain,
initialCertValue,
autoFetch: true,
polling: open,
pollingInterval: durationToMs(5, "seconds")
pollingInterval: 5000
});
const { cert, certLoading, certError, refreshing, fetchCert } = certificate;
// `polling` only schedules on predefined intervals (1 second),
// so the first request would be a full interval away if open = true (which set polling = true).
// So we fetch immediately so the popover opens with fresh data.
useEffect(() => {
if (!open) return;
void fetchCert();
void fetchCert(false);
}, [open, fetchCert]);
const clearCloseTimer = useCallback(() => {
+1
View File
@@ -180,6 +180,7 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
orgId={resource.orgId}
domainId={resource.domainId!}
fullDomain={resource.fullDomain!}
autoFetch={true}
showLabel={false}
polling={true}
/>
+1
View File
@@ -182,6 +182,7 @@ export function SiteResourceInfoSections({
orgId={siteResource.orgId}
domainId={siteResource.domainId!}
fullDomain={siteResource.fullDomain!}
autoFetch={true}
showLabel={false}
polling={true}
/>
+14 -29
View File
@@ -1,7 +1,7 @@
"use client";
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import { UptimeMiniBar } from "@app/components/UptimeMiniBar";
import UptimeMiniBar from "@app/components/UptimeMiniBar";
import {
Credenza,
@@ -52,12 +52,12 @@ import {
} from "./ui/controlled-data-table";
import { useOptimisticLabels } from "@app/hooks/useOptimisticLabels";
import { durationToMs } from "@app/lib/durationToMs";
import { orgQueries, productUpdatesQueries } from "@app/lib/queries";
import { useQuery } from "@tanstack/react-query";
import semver from "semver";
import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { LabelColumnFilterButton } from "./LabelColumnFilterButton";
import { LabelsTableCell } from "./LabelsTableCell";
import { useQuery } from "@tanstack/react-query";
import { productUpdatesQueries } from "@app/lib/queries";
import semver from "semver";
export type SiteRow = {
id: number;
@@ -89,8 +89,6 @@ type SitesTableProps = {
rowCount: number;
};
const SITE_STATUS_HISTORY_DAYS = 30;
export default function SitesTable({
sites,
orgId,
@@ -114,16 +112,7 @@ export default function SitesTable({
const [isRefreshing, startTransition] = useTransition();
const [isNavigatingToAddPage, startNavigation] = useTransition();
const siteIds = sites.map((s) => s.id);
const statusHistoryQuery = useQuery({
...orgQueries.batchedSiteStatusHistory({
orgId,
siteIds,
days: SITE_STATUS_HISTORY_DAYS
}),
enabled: siteIds.length > 0
});
const { isPaidUser } = usePaidStatus();
const api = createApiClient(useEnvContext());
const t = useTranslations();
@@ -307,14 +296,7 @@ export default function SitesTable({
if (originalRow.type == "local") {
return <span>-</span>;
}
const data = statusHistoryQuery.data?.[row.original.id];
return (
<UptimeMiniBar
isLoading={statusHistoryQuery.isLoading}
data={data}
days={SITE_STATUS_HISTORY_DAYS}
/>
);
return <UptimeMiniBar siteId={originalRow.id} days={30} />;
}
},
{
@@ -377,11 +359,14 @@ export default function SitesTable({
cell: ({ row }) => {
const originalRow = row.original;
const updateAvailable = Boolean(
let updateAvailable = Boolean(
latestNewtVersion &&
originalRow.newtVersion &&
semver.valid(originalRow.newtVersion) &&
semver.lt(originalRow.newtVersion, latestNewtVersion)
originalRow.newtVersion &&
semver.valid(originalRow.newtVersion) &&
semver.lt(
originalRow.newtVersion,
latestNewtVersion
)
);
if (originalRow.type === "newt") {
+19 -26
View File
@@ -1,14 +1,15 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { orgQueries } from "@app/lib/queries";
import {
Tooltip,
TooltipContent,
TooltipTrigger
} from "@app/components/ui/tooltip";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { createApiClient } from "@app/lib/api";
import { cn } from "@app/lib/cn";
import { orgQueries } from "@app/lib/queries";
import type { StatusHistoryResponse } from "@server/lib/statusHistory";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
function formatDuration(seconds: number): string {
@@ -45,16 +46,21 @@ type UptimeMiniBarProps = {
days?: number;
};
export default function UptimeMiniBarWrapper({
export default function UptimeMiniBar({
orgId,
siteId,
resourceId,
healthCheckId,
days = 30
}: UptimeMiniBarProps) {
const t = useTranslations();
const api = createApiClient(useEnvContext());
const siteQuery = useQuery({
...orgQueries.siteStatusHistory({ siteId: siteId ?? 0, days }),
enabled: siteId != null
enabled: siteId != null,
meta: { api },
staleTime: 5 * 60 * 1000
});
const hcQuery = useQuery({
@@ -63,12 +69,16 @@ export default function UptimeMiniBarWrapper({
healthCheckId: healthCheckId ?? 0,
days
}),
enabled: healthCheckId != null && siteId == null && resourceId == null
enabled: healthCheckId != null && siteId == null && resourceId == null,
meta: { api },
staleTime: 5 * 60 * 1000
});
const resourceQuery = useQuery({
...orgQueries.resourceStatusHistory({ resourceId, days }),
enabled: resourceId != null && siteId == null && healthCheckId == null
enabled: resourceId != null && siteId == null && healthCheckId == null,
meta: { api },
staleTime: 5 * 60 * 1000
});
const { data, isLoading } =
@@ -78,22 +88,6 @@ export default function UptimeMiniBarWrapper({
? resourceQuery
: hcQuery;
return <UptimeMiniBar data={data} isLoading={isLoading} days={days} />;
}
type UptimeMiniBarUIProps = {
data?: StatusHistoryResponse;
isLoading?: boolean;
days?: number;
};
export function UptimeMiniBar({
data,
isLoading,
days = 30
}: UptimeMiniBarUIProps) {
const t = useTranslations();
if (isLoading) {
return (
<div className="flex items-center gap-2">
@@ -144,8 +138,7 @@ export function UptimeMiniBar({
{formatDate(day.date)}
</div>
<div className="text-xs text-primary-foreground/80">
{day.status === "no_data" ||
day.status === "unknown"
{day.status === "no_data" || day.status === "unknown"
? t("uptimeNoData")
: `${day.uptimePercent.toFixed(1)}% ${t("uptimeSuffix")}`}
</div>
@@ -166,4 +159,4 @@ export function UptimeMiniBar({
</span>
</div>
);
}
}
+96 -80
View File
@@ -1,20 +1,18 @@
"use client";
import { useCallback } from "react";
import { useState, useCallback, useEffect } from "react";
import { AxiosResponse } from "axios";
import { GetCertificateResponse } from "@server/routers/certificates/types";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { domainQueries } from "@app/lib/queries";
import { durationToMs } from "@app/lib/durationToMs";
type UseCertificateProps = {
orgId: string;
domainId: string;
fullDomain: string;
autoFetch?: boolean;
polling?: boolean;
pollingInterval?: number;
initialCertValue?: GetCertificateResponse | null;
};
type UseCertificateReturn = {
@@ -22,106 +20,124 @@ type UseCertificateReturn = {
certLoading: boolean;
certError: string | null;
refreshing: boolean;
fetchCert: () => Promise<void>;
fetchCert: (showLoading?: boolean) => Promise<void>;
refreshCert: () => Promise<void>;
// clearCert: () => void;
clearCert: () => void;
};
const POLL_JITTER_MS = durationToMs(1, "seconds");
/** A valid cert isn't going anywhere soon, so check on it far less often. */
const VALID_POLL_INTERVAL_MS = durationToMs(30, "seconds");
export function useCertificate({
orgId,
domainId,
fullDomain,
initialCertValue,
autoFetch = true,
polling = false,
pollingInterval = durationToMs(5, "seconds")
pollingInterval = 5000
}: UseCertificateProps): UseCertificateReturn {
const api = createApiClient(useEnvContext());
const queryClient = useQueryClient();
const certQuery = domainQueries.getCertificate({
orgId,
domainId,
domain: fullDomain
});
const [cert, setCert] = useState<GetCertificateResponse | null>(null);
const [certLoading, setCertLoading] = useState(false);
const [certError, setCertError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const { data, isLoading, isError, refetch } = useQuery({
...certQuery,
enabled: Boolean(orgId && domainId && fullDomain),
refetchInterval: (query) => {
if (!polling) return false;
const interval =
query.state.data?.status === "valid"
? VALID_POLL_INTERVAL_MS
: pollingInterval;
// Add a small random offset to each tick. Without it, every row in
// a table would poll at the exact same instant, hitting the server
// in bursts instead of spreading the requests out.
// the requests will be jittered by less or more than 1s
const jitter = (Math.random() * 2 - 1) * POLL_JITTER_MS;
return Math.max(1000, interval + jitter);
const fetchCert = useCallback(
async (showLoading = true) => {
if (!orgId || !domainId || !fullDomain) return;
if (showLoading) {
setCertLoading(true);
}
try {
const res = await api.get<
AxiosResponse<GetCertificateResponse>
>(`/org/${orgId}/certificate/${domainId}/${fullDomain}`);
const certData = res.data.data;
if (certData) {
setCertError(null);
setCert(certData);
}
} catch (error: any) {
console.error("Failed to fetch certificate:", error);
setCertError("Failed");
} finally {
if (showLoading) {
setCertLoading(false);
}
}
},
// An explicit `null` is a real answer ("this domain has no certificate")
// and is seeded like any other, so a server-prefetched row doesn't
// refetch on mount. Only an omitted prop leaves the cache empty.
...(initialCertValue !== undefined && { initialData: initialCertValue })
});
[api, orgId, domainId, fullDomain]
);
const cert = data ?? null;
const restartCert = useMutation({
mutationFn: async (certId: number) => {
await api.post(`/org/${orgId}/certificate/${certId}/restart`, {});
},
onSuccess: () => {
// the backend flips the status asynchronously; reflect it optimistically
setTimeout(() => {
queryClient.setQueryData(certQuery.queryKey, (prev) =>
prev ? { ...prev, status: "pending" } : prev
);
}, 500);
},
onError: (error) => {
console.error("Failed to restart certificate:", error);
}
});
const fetchCert = useCallback(async () => {
await refetch();
}, [refetch]);
const { mutateAsync: restartCertAsync } = restartCert;
const refreshCert = useCallback(async () => {
if (!cert) return;
setRefreshing(true);
setCertError(null);
try {
await restartCertAsync(cert.certId);
} catch {
// surfaced through certError
await api.post(
`/org/${orgId}/certificate/${cert.certId}/restart`,
{}
);
// Update status to pending
setTimeout(() => {
setCert({ ...cert, status: "pending" });
}, 500);
} catch (error: any) {
console.error("Failed to restart certificate:", error);
setCertError("Failed to restart");
} finally {
setRefreshing(false);
}
}, [cert, restartCertAsync]);
}, [api, orgId, cert]);
// const clearCert = useCallback(() => {
// queryClient.removeQueries({ queryKey: certQuery.queryKey });
// }, [queryClient, certQuery.queryKey]);
const clearCert = useCallback(() => {
setCert(null);
setCertError(null);
}, []);
let certError: string | null = null;
if (restartCert.isError) {
certError = "Failed to restart";
} else if (isError) {
certError = "Failed";
}
// Auto-fetch on mount if enabled
useEffect(() => {
if (autoFetch && orgId && domainId && fullDomain) {
fetchCert();
}
}, [autoFetch, orgId, domainId, fullDomain, fetchCert]);
useEffect(() => {
if (!polling || !orgId || !domainId || !fullDomain) return;
const POLL_JITTER_MS = 1000;
let cancelled = false;
let timeoutId: ReturnType<typeof setTimeout>;
const scheduleNext = () => {
const jitter = (Math.random() * 2 - 1) * POLL_JITTER_MS;
const delayMs = Math.max(
1000,
Math.round(pollingInterval + jitter)
);
timeoutId = setTimeout(() => {
if (cancelled) return;
void fetchCert(false);
scheduleNext();
}, delayMs);
};
scheduleNext();
return () => {
cancelled = true;
clearTimeout(timeoutId);
};
}, [polling, orgId, domainId, fullDomain, pollingInterval, fetchCert]);
return {
cert,
certLoading: isLoading,
certLoading,
certError,
refreshing: restartCert.isPending,
refreshing,
fetchCert,
refreshCert
// clearCert
refreshCert,
clearCert
};
}
+2 -188
View File
@@ -41,16 +41,13 @@ import {
keepPreviousData,
queryOptions
} from "@tanstack/react-query";
import { isAxiosError, type AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import z, { meta } from "zod";
import { remote } from "./api";
import { durationToMs } from "./durationToMs";
import type { ListOrgLabelsResponse } from "@server/routers/labels/types";
import { ListHealthChecksResponse } from "@server/routers/healthChecks/types";
import {
StatusHistoryResponse,
type BatchedStatusHistoryResponse
} from "@server/lib/statusHistory";
import { StatusHistoryResponse } from "@server/lib/statusHistory";
import type { ListResourcePoliciesResponse } from "@server/routers/resource/types";
import type { GetResourcePolicyResponse } from "@server/routers/policy";
import type {
@@ -69,7 +66,6 @@ import type { GetResourceAuthInfoResponse } from "@server/routers/resource/getRe
import type { GetSiteResourceResponse } from "@server/routers/siteResource/getSiteResource";
import type { LauncherQueryFilters } from "@app/lib/launcherSearchParams";
import { buildLauncherSearchParams } from "@app/lib/launcherSearchParams";
import type { GetCertificateResponse } from "@server/routers/certificates/types";
export type { LauncherQueryFilters } from "@app/lib/launcherSearchParams";
export { buildLauncherSearchParams } from "@app/lib/launcherSearchParams";
@@ -644,143 +640,6 @@ export const orgQueries = {
};
}
}),
batchedSiteStatusHistory: ({
siteIds,
orgId,
days = 90
}: {
orgId: string;
siteIds: number[];
days?: number;
}) =>
queryOptions({
queryKey: [
"ORG",
orgId,
"BATCHED_SITE_STATUS_HISTORY",
siteIds,
days
] as const,
queryFn: async ({ signal, meta }) => {
// Negated because getTimezoneOffset() returns UTC - local,
// while the API expects minutes to add to UTC to get local
const tzOffsetMinutes = -new Date().getTimezoneOffset();
const sp = new URLSearchParams([
["days", days.toString()],
["tzOffsetMinutes", tzOffsetMinutes.toString()],
...siteIds.map((id) => ["siteIds", id.toString()])
]);
const res = await meta!.api.get<
AxiosResponse<BatchedStatusHistoryResponse>
>(`/org/${orgId}/site-status-histories?${sp.toString()}`, {
signal
});
return res.data.data;
},
staleTime: durationToMs(5, "seconds")
}),
batchedHealthCheckStatusHistory: ({
healthCheckIds,
orgId,
days = 90
}: {
orgId: string;
healthCheckIds: number[];
days?: number;
}) =>
queryOptions({
queryKey: [
"ORG",
orgId,
"BATCHED_HEALTH_CHECK_STATUS_HISTORY",
healthCheckIds,
days
] as const,
queryFn: async ({ signal, meta }) => {
// Negated because getTimezoneOffset() returns UTC - local,
// while the API expects minutes to add to UTC to get local
const tzOffsetMinutes = -new Date().getTimezoneOffset();
const sp = new URLSearchParams([
["days", days.toString()],
["tzOffsetMinutes", tzOffsetMinutes.toString()],
...healthCheckIds.map((id) => [
"healthCheckIds",
id.toString()
])
]);
const res = await meta!.api.get<
AxiosResponse<BatchedStatusHistoryResponse>
>(
`/org/${orgId}/health-check-status-histories?${sp.toString()}`,
{ signal }
);
return res.data.data;
},
staleTime: durationToMs(5, "seconds")
}),
batchedDomainCertificates: ({
domains,
orgId
}: {
orgId: string;
domains: string[];
}) =>
queryOptions({
queryKey: ["ORG", orgId, "BATCHED_CERTIFICATES", domains] as const,
queryFn: async ({ signal, meta }) => {
// Negated because getTimezoneOffset() returns UTC - local,
// while the API expects minutes to add to UTC to get local
const sp = new URLSearchParams([
...domains.map((domain) => ["domains", domain.toString()])
]);
const res = await meta!.api.get<
AxiosResponse<BatchedStatusHistoryResponse>
>(`/org/${orgId}/batched-certificates?${sp.toString()}`, {
signal
});
return res.data.data;
},
staleTime: durationToMs(5, "seconds")
}),
batchedResourceStatusHistory: ({
resourceIds,
orgId,
days = 90
}: {
orgId: string;
resourceIds: number[];
days?: number;
}) =>
queryOptions({
queryKey: [
"ORG",
orgId,
"BATCHED_RESOURCE_STATUS_HISTORY",
resourceIds,
days
] as const,
queryFn: async ({ signal, meta }) => {
// Negated because getTimezoneOffset() returns UTC - local,
// while the API expects minutes to add to UTC to get local
const tzOffsetMinutes = -new Date().getTimezoneOffset();
const sp = new URLSearchParams([
["days", days.toString()],
["tzOffsetMinutes", tzOffsetMinutes.toString()],
...resourceIds.map((id) => ["resourceIds", id.toString()])
]);
const res = await meta!.api.get<
AxiosResponse<BatchedStatusHistoryResponse>
>(`/org/${orgId}/resource-status-histories?${sp.toString()}`, {
signal
});
return res.data.data;
},
staleTime: durationToMs(5, "seconds")
}),
siteStatusHistory: ({
siteId,
days = 90
@@ -790,7 +649,6 @@ export const orgQueries = {
}) =>
queryOptions({
queryKey: ["SITE_STATUS_HISTORY", siteId, days] as const,
staleTime: durationToMs(5, "seconds"),
queryFn: async ({ signal, meta }) => {
const tzOffsetMinutes = -new Date().getTimezoneOffset();
const res = await meta!.api.get<
@@ -812,7 +670,6 @@ export const orgQueries = {
}) =>
queryOptions({
queryKey: ["RESOURCE_STATUS_HISTORY", resourceId, days] as const,
staleTime: durationToMs(5, "seconds"),
queryFn: async ({ signal, meta }) => {
const tzOffsetMinutes = -new Date().getTimezoneOffset();
const res = await meta!.api.get<
@@ -835,7 +692,6 @@ export const orgQueries = {
days?: number;
}) =>
queryOptions({
staleTime: durationToMs(5, "seconds"),
queryKey: [
"HC_STATUS_HISTORY",
orgId,
@@ -1381,48 +1237,6 @@ export const approvalQueries = {
};
export const domainQueries = {
getCertificate: ({
orgId,
domainId,
domain
}: {
orgId: string;
domainId: string;
domain: string;
}) =>
queryOptions({
queryKey: [
"ORG",
orgId,
"DOMAIN",
domainId,
"CERTIFICATE",
domain
] as const,
queryFn: async ({ signal, meta }) => {
try {
const res = await meta!.api.get<
AxiosResponse<GetCertificateResponse | null>
>(`/org/${orgId}/certificate/${domainId}/${domain}`, {
signal
});
return res.data.data;
} catch (error) {
// the endpoint 404s when the domain has no certificate yet
if (isAxiosError(error) && error.response?.status === 404) {
return null;
}
throw error;
}
},
retry: (failureCount, error) =>
isAxiosError(error) &&
error.response != null &&
error.response.status < 500
? false
: failureCount < 2,
staleTime: durationToMs(1, "minutes")
}),
getDomain: ({ orgId, domainId }: { orgId: string; domainId: string }) =>
queryOptions({
queryKey: ["ORG", orgId, "DOMAIN", domainId] as const,