mirror of
https://github.com/fosrl/pangolin.git
synced 2026-05-07 00:39:53 +00:00
Compare commits
56 Commits
1.18.0
...
1.18.1-s.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53e096f7cb | ||
|
|
3dfd7e8a43 | ||
|
|
db6e60d0a3 | ||
|
|
54d2d689c1 | ||
|
|
68f5512732 | ||
|
|
416e124c02 | ||
|
|
d3e4d8cda8 | ||
|
|
81972dbb73 | ||
|
|
ae24eb2d2c | ||
|
|
20fc59dcda | ||
|
|
93b09de425 | ||
|
|
bacc130453 | ||
|
|
81197f8a86 | ||
|
|
dcfc7822f4 | ||
|
|
0a0817b860 | ||
|
|
ab60438aa7 | ||
|
|
b9f3f90de6 | ||
|
|
b53cc397be | ||
|
|
994fb456c2 | ||
|
|
b36927c7a0 | ||
|
|
1c57473b6d | ||
|
|
c02c3eaa4a | ||
|
|
3c265ee577 | ||
|
|
98dfd05f06 | ||
|
|
faa2e97530 | ||
|
|
175f10a51d | ||
|
|
6284930fce | ||
|
|
6c93aca444 | ||
|
|
d83318cbfc | ||
|
|
143f362a48 | ||
|
|
698cd868a8 | ||
|
|
a55842ffff | ||
|
|
2ffe254879 | ||
|
|
e173f59d89 | ||
|
|
d3870f4920 | ||
|
|
227501d8f8 | ||
|
|
a16f805709 | ||
|
|
a029b107ae | ||
|
|
f03389a9a0 | ||
|
|
78fff6bfde | ||
|
|
bc585c24fc | ||
|
|
0f6c66dc67 | ||
|
|
6be150bafe | ||
|
|
1eac7741a5 | ||
|
|
b8ca0499af | ||
|
|
b39a2bcfb1 | ||
|
|
d45b727dca | ||
|
|
5c31d35e28 | ||
|
|
8c645315f3 | ||
|
|
3bcbeb24f3 | ||
|
|
1d0a92c83e | ||
|
|
a44100c2bd | ||
|
|
2203ebf723 | ||
|
|
7e374baee9 | ||
|
|
4cf6ca1d55 | ||
|
|
8ed9adbfae |
112
.github/workflows/cicd.yml
vendored
112
.github/workflows/cicd.yml
vendored
@@ -414,28 +414,18 @@ jobs:
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install cosign
|
||||
# cosign is used to sign and verify container images (key and keyless)
|
||||
# cosign is used to sign container images using keyless (OIDC) signing
|
||||
uses: sigstore/cosign-installer@cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003 # v4.1.1
|
||||
|
||||
- name: Dual-sign and verify (GHCR & Docker Hub)
|
||||
# Sign each image by digest using keyless (OIDC) and key-based signing,
|
||||
# then verify both the public key signature and the keyless OIDC signature.
|
||||
- name: Sign (GHCR, keyless)
|
||||
# Sign each GHCR image by digest using keyless (OIDC) signing via Sigstore/Rekor.
|
||||
# Signatures are stored in the registry alongside the image.
|
||||
env:
|
||||
TAG: ${{ env.TAG }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
COSIGN_PUBLIC_KEY: ${{ secrets.COSIGN_PUBLIC_KEY }}
|
||||
COSIGN_YES: "true"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
issuer="https://token.actions.githubusercontent.com"
|
||||
id_regex="^https://github.com/${{ github.repository }}/.+" # accept this repo (all workflows/refs)
|
||||
|
||||
# Track failures
|
||||
FAILED_TAGS=()
|
||||
SUCCESSFUL_TAGS=()
|
||||
|
||||
# Determine if this is an RC release
|
||||
IS_RC="false"
|
||||
if [[ "$TAG" == *"-rc."* ]]; then
|
||||
@@ -463,95 +453,47 @@ jobs:
|
||||
)
|
||||
fi
|
||||
|
||||
# Sign each image variant for both registries
|
||||
for BASE_IMAGE in "${GHCR_IMAGE}" "${DOCKERHUB_IMAGE}"; do
|
||||
for IMAGE_TAG in "${IMAGE_TAGS[@]}"; do
|
||||
echo "Processing ${BASE_IMAGE}:${IMAGE_TAG}"
|
||||
TAG_FAILED=false
|
||||
FAILED_TAGS=()
|
||||
SUCCESSFUL_TAGS=()
|
||||
|
||||
# Wrap the entire tag processing in error handling
|
||||
(
|
||||
set -e
|
||||
DIGEST="$(skopeo inspect --retry-times 3 docker://${BASE_IMAGE}:${IMAGE_TAG} | jq -r '.Digest')"
|
||||
REF="${BASE_IMAGE}@${DIGEST}"
|
||||
echo "Resolved digest: ${REF}"
|
||||
for IMAGE_TAG in "${IMAGE_TAGS[@]}"; do
|
||||
echo "Processing ${GHCR_IMAGE}:${IMAGE_TAG}"
|
||||
TAG_FAILED=false
|
||||
|
||||
echo "==> cosign sign (keyless) --recursive ${REF}"
|
||||
cosign sign --recursive "${REF}"
|
||||
(
|
||||
set -e
|
||||
DIGEST="$(skopeo inspect --retry-times 3 docker://${GHCR_IMAGE}:${IMAGE_TAG} | jq -r '.Digest')"
|
||||
REF="${GHCR_IMAGE}@${DIGEST}"
|
||||
echo "Resolved digest: ${REF}"
|
||||
|
||||
echo "==> cosign sign (key) --recursive ${REF}"
|
||||
cosign sign --key env://COSIGN_PRIVATE_KEY --recursive "${REF}"
|
||||
echo "==> cosign sign (keyless) --recursive ${REF}"
|
||||
cosign sign --recursive "${REF}"
|
||||
) || TAG_FAILED=true
|
||||
|
||||
# Retry wrapper for verification to handle registry propagation delays
|
||||
retry_verify() {
|
||||
local cmd="$1"
|
||||
local attempts=6
|
||||
local delay=5
|
||||
local i=1
|
||||
until eval "$cmd"; do
|
||||
if [ $i -ge $attempts ]; then
|
||||
echo "Verification failed after $attempts attempts"
|
||||
return 1
|
||||
fi
|
||||
echo "Verification not yet available. Retry $i/$attempts after ${delay}s..."
|
||||
sleep $delay
|
||||
i=$((i+1))
|
||||
delay=$((delay*2))
|
||||
# Cap the delay to avoid very long waits
|
||||
if [ $delay -gt 60 ]; then delay=60; fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
echo "==> cosign verify (public key) ${REF}"
|
||||
if retry_verify "cosign verify --key env://COSIGN_PUBLIC_KEY '${REF}' -o text"; then
|
||||
VERIFIED_INDEX=true
|
||||
else
|
||||
VERIFIED_INDEX=false
|
||||
fi
|
||||
|
||||
echo "==> cosign verify (keyless policy) ${REF}"
|
||||
if retry_verify "cosign verify --certificate-oidc-issuer '${issuer}' --certificate-identity-regexp '${id_regex}' '${REF}' -o text"; then
|
||||
VERIFIED_INDEX_KEYLESS=true
|
||||
else
|
||||
VERIFIED_INDEX_KEYLESS=false
|
||||
fi
|
||||
|
||||
# Check if verification succeeded
|
||||
if [ "${VERIFIED_INDEX}" != "true" ] && [ "${VERIFIED_INDEX_KEYLESS}" != "true" ]; then
|
||||
echo "⚠️ WARNING: Verification not available for ${BASE_IMAGE}:${IMAGE_TAG}"
|
||||
echo "This may be due to registry propagation delays. Continuing anyway."
|
||||
fi
|
||||
) || TAG_FAILED=true
|
||||
|
||||
if [ "$TAG_FAILED" = "true" ]; then
|
||||
echo "⚠️ WARNING: Failed to sign/verify ${BASE_IMAGE}:${IMAGE_TAG}"
|
||||
FAILED_TAGS+=("${BASE_IMAGE}:${IMAGE_TAG}")
|
||||
else
|
||||
echo "✓ Successfully signed and verified ${BASE_IMAGE}:${IMAGE_TAG}"
|
||||
SUCCESSFUL_TAGS+=("${BASE_IMAGE}:${IMAGE_TAG}")
|
||||
fi
|
||||
done
|
||||
if [ "$TAG_FAILED" = "true" ]; then
|
||||
echo "⚠️ WARNING: Failed to sign ${GHCR_IMAGE}:${IMAGE_TAG}"
|
||||
FAILED_TAGS+=("${GHCR_IMAGE}:${IMAGE_TAG}")
|
||||
else
|
||||
echo "✓ Successfully signed ${GHCR_IMAGE}:${IMAGE_TAG}"
|
||||
SUCCESSFUL_TAGS+=("${GHCR_IMAGE}:${IMAGE_TAG}")
|
||||
fi
|
||||
done
|
||||
|
||||
# Report summary
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "Sign and Verify Summary"
|
||||
echo "Sign Summary"
|
||||
echo "=========================================="
|
||||
echo "Successful: ${#SUCCESSFUL_TAGS[@]}"
|
||||
echo "Failed: ${#FAILED_TAGS[@]}"
|
||||
echo ""
|
||||
|
||||
if [ ${#FAILED_TAGS[@]} -gt 0 ]; then
|
||||
echo "Failed tags:"
|
||||
for tag in "${FAILED_TAGS[@]}"; do
|
||||
echo " - $tag"
|
||||
done
|
||||
echo ""
|
||||
echo "⚠️ WARNING: Some tags failed to sign/verify, but continuing anyway"
|
||||
echo "⚠️ WARNING: Some tags failed to sign, but continuing anyway"
|
||||
else
|
||||
echo "✓ All images signed and verified successfully!"
|
||||
echo "✓ All images signed successfully!"
|
||||
fi
|
||||
shell: bash
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CommandModule } from "yargs";
|
||||
import { db, idpOidcConfig, licenseKey } from "@server/db";
|
||||
import { db, idpOidcConfig, licenseKey, certificates, eventStreamingDestinations, alertWebhookActions } from "@server/db";
|
||||
import { encrypt, decrypt } from "@server/lib/crypto";
|
||||
import { configFilePath1, configFilePath2 } from "@server/lib/consts";
|
||||
import { eq } from "drizzle-orm";
|
||||
@@ -129,9 +129,15 @@ export const rotateServerSecret: CommandModule<
|
||||
console.log("\nReading encrypted data from database...");
|
||||
const idpConfigs = await db.select().from(idpOidcConfig);
|
||||
const licenseKeys = await db.select().from(licenseKey);
|
||||
const certs = await db.select().from(certificates);
|
||||
const streamingDestinations = await db.select().from(eventStreamingDestinations);
|
||||
const webhookActions = await db.select().from(alertWebhookActions);
|
||||
|
||||
console.log(`Found ${idpConfigs.length} OIDC IdP configuration(s)`);
|
||||
console.log(`Found ${licenseKeys.length} license key(s)`);
|
||||
console.log(`Found ${certs.length} certificate(s)`);
|
||||
console.log(`Found ${streamingDestinations.length} event streaming destination(s)`);
|
||||
console.log(`Found ${webhookActions.length} alert webhook action(s)`);
|
||||
|
||||
// Prepare all decrypted and re-encrypted values
|
||||
console.log("\nDecrypting and re-encrypting values...");
|
||||
@@ -149,8 +155,27 @@ export const rotateServerSecret: CommandModule<
|
||||
encryptedInstanceId: string;
|
||||
};
|
||||
|
||||
type CertUpdate = {
|
||||
certId: number;
|
||||
encryptedCertFile: string | null;
|
||||
encryptedKeyFile: string | null;
|
||||
};
|
||||
|
||||
type StreamingDestinationUpdate = {
|
||||
destinationId: number;
|
||||
encryptedConfig: string;
|
||||
};
|
||||
|
||||
type WebhookActionUpdate = {
|
||||
webhookActionId: number;
|
||||
encryptedConfig: string;
|
||||
};
|
||||
|
||||
const idpUpdates: IdpUpdate[] = [];
|
||||
const licenseKeyUpdates: LicenseKeyUpdate[] = [];
|
||||
const certUpdates: CertUpdate[] = [];
|
||||
const streamingDestinationUpdates: StreamingDestinationUpdate[] = [];
|
||||
const webhookActionUpdates: WebhookActionUpdate[] = [];
|
||||
|
||||
// Process idpOidcConfig entries
|
||||
for (const idpConfig of idpConfigs) {
|
||||
@@ -217,6 +242,70 @@ export const rotateServerSecret: CommandModule<
|
||||
}
|
||||
}
|
||||
|
||||
// Process certificate entries
|
||||
for (const cert of certs) {
|
||||
try {
|
||||
const encryptedCertFile = cert.certFile
|
||||
? encrypt(decrypt(cert.certFile, oldSecret), newSecret)
|
||||
: null;
|
||||
const encryptedKeyFile = cert.keyFile
|
||||
? encrypt(decrypt(cert.keyFile, oldSecret), newSecret)
|
||||
: null;
|
||||
|
||||
certUpdates.push({
|
||||
certId: cert.certId,
|
||||
encryptedCertFile,
|
||||
encryptedKeyFile
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error processing certificate ${cert.certId} (${cert.domain}):`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Process eventStreamingDestinations entries
|
||||
for (const dest of streamingDestinations) {
|
||||
try {
|
||||
const decryptedConfig = decrypt(dest.config, oldSecret);
|
||||
const encryptedConfig = encrypt(decryptedConfig, newSecret);
|
||||
|
||||
streamingDestinationUpdates.push({
|
||||
destinationId: dest.destinationId,
|
||||
encryptedConfig
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error processing event streaming destination ${dest.destinationId}:`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Process alertWebhookActions entries
|
||||
for (const webhook of webhookActions) {
|
||||
try {
|
||||
if (webhook.config == null) continue;
|
||||
|
||||
const decryptedConfig = decrypt(webhook.config, oldSecret);
|
||||
const encryptedConfig = encrypt(decryptedConfig, newSecret);
|
||||
|
||||
webhookActionUpdates.push({
|
||||
webhookActionId: webhook.webhookActionId,
|
||||
encryptedConfig
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error processing alert webhook action ${webhook.webhookActionId}:`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Perform all database updates in a single transaction
|
||||
console.log("\nUpdating database in transaction...");
|
||||
await db.transaction(async (trx) => {
|
||||
@@ -250,10 +339,50 @@ export const rotateServerSecret: CommandModule<
|
||||
instanceId: update.encryptedInstanceId
|
||||
});
|
||||
}
|
||||
|
||||
// Update certificate entries
|
||||
for (const update of certUpdates) {
|
||||
await trx
|
||||
.update(certificates)
|
||||
.set({
|
||||
certFile: update.encryptedCertFile,
|
||||
keyFile: update.encryptedKeyFile
|
||||
})
|
||||
.where(eq(certificates.certId, update.certId));
|
||||
}
|
||||
|
||||
// Update event streaming destination entries
|
||||
for (const update of streamingDestinationUpdates) {
|
||||
await trx
|
||||
.update(eventStreamingDestinations)
|
||||
.set({ config: update.encryptedConfig })
|
||||
.where(
|
||||
eq(
|
||||
eventStreamingDestinations.destinationId,
|
||||
update.destinationId
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Update alert webhook action entries
|
||||
for (const update of webhookActionUpdates) {
|
||||
await trx
|
||||
.update(alertWebhookActions)
|
||||
.set({ config: update.encryptedConfig })
|
||||
.where(
|
||||
eq(
|
||||
alertWebhookActions.webhookActionId,
|
||||
update.webhookActionId
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`Rotated ${idpUpdates.length} OIDC IdP configuration(s)`);
|
||||
console.log(`Rotated ${licenseKeyUpdates.length} license key(s)`);
|
||||
console.log(`Rotated ${certUpdates.length} certificate(s)`);
|
||||
console.log(`Rotated ${streamingDestinationUpdates.length} event streaming destination(s)`);
|
||||
console.log(`Rotated ${webhookActionUpdates.length} alert webhook action(s)`);
|
||||
|
||||
// Update config file with new secret
|
||||
console.log("\nUpdating config file...");
|
||||
@@ -270,6 +399,9 @@ export const rotateServerSecret: CommandModule<
|
||||
console.log(`\nSummary:`);
|
||||
console.log(` - OIDC IdP configurations: ${idpUpdates.length}`);
|
||||
console.log(` - License keys: ${licenseKeyUpdates.length}`);
|
||||
console.log(` - Certificates: ${certUpdates.length}`);
|
||||
console.log(` - Event streaming destinations: ${streamingDestinationUpdates.length}`);
|
||||
console.log(` - Alert webhook actions: ${webhookActionUpdates.length}`);
|
||||
console.log(
|
||||
`\n IMPORTANT: Restart the server for the new secret to take effect.`
|
||||
);
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Създаване на админ акаунт",
|
||||
"setupErrorCreateAdmin": "Възникна грешка при създаване на админ акаунт.",
|
||||
"certificateStatus": "Сертификат",
|
||||
"certificateStatusAutoRefreshHint": "Състоянието се опреснява автоматично.",
|
||||
"loading": "Зареждане",
|
||||
"loadingAnalytics": "Зареждане на анализи",
|
||||
"restart": "Рестарт",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Vytvořit účet správce",
|
||||
"setupErrorCreateAdmin": "Došlo k chybě při vytváření účtu správce serveru.",
|
||||
"certificateStatus": "Certifikát",
|
||||
"certificateStatusAutoRefreshHint": "Stav se automaticky obnovuje.",
|
||||
"loading": "Načítání",
|
||||
"loadingAnalytics": "Načítání analytiky",
|
||||
"restart": "Restartovat",
|
||||
@@ -3167,7 +3168,7 @@
|
||||
"publicIpEndpoint": "Koncový bod",
|
||||
"lastTriggeredAt": "Poslední spouštěč",
|
||||
"reject": "Odmítnout",
|
||||
"uptimeDaysAgo": "{count} days ago",
|
||||
"uptimeDaysAgo": "Před {count} dny",
|
||||
"uptimeToday": "Dnes",
|
||||
"uptimeNoDataAvailable": "Dostupná žádná data",
|
||||
"uptimeSuffix": "doba dostupnosti",
|
||||
|
||||
@@ -1432,7 +1432,7 @@
|
||||
"alertingTriggerHcToggle": "Gesundheits-Check-Status ändern",
|
||||
"alertingTriggerResourceHealthy": "Ressource gesund",
|
||||
"alertingTriggerResourceUnhealthy": "Ressource ungesund",
|
||||
"alertingTriggerResourceDegraded": "Resource degraded",
|
||||
"alertingTriggerResourceDegraded": "Ressource verschlechtert",
|
||||
"alertingSearchHealthChecks": "Gesundheits-Checks suchen…",
|
||||
"alertingHealthChecksEmpty": "Keine Gesundheits-Checks verfügbar.",
|
||||
"alertingTriggerResourceToggle": "Ressourcenstatus ändern",
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Admin-Konto erstellen",
|
||||
"setupErrorCreateAdmin": "Beim Erstellen des Server-Admin-Kontos ist ein Fehler aufgetreten.",
|
||||
"certificateStatus": "Zertifikat",
|
||||
"certificateStatusAutoRefreshHint": "Der Status wird automatisch aktualisiert.",
|
||||
"loading": "Laden",
|
||||
"loadingAnalytics": "Analytik wird geladen",
|
||||
"restart": "Neustart",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Create Admin Account",
|
||||
"setupErrorCreateAdmin": "An error occurred while creating the server admin account.",
|
||||
"certificateStatus": "Certificate",
|
||||
"certificateStatusAutoRefreshHint": "Status refreshes automatically.",
|
||||
"loading": "Loading",
|
||||
"loadingAnalytics": "Loading Analytics",
|
||||
"restart": "Restart",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Crear cuenta de administrador",
|
||||
"setupErrorCreateAdmin": "Se produjo un error al crear la cuenta de administrador del servidor.",
|
||||
"certificateStatus": "Certificado",
|
||||
"certificateStatusAutoRefreshHint": "El estado se actualiza automáticamente.",
|
||||
"loading": "Cargando",
|
||||
"loadingAnalytics": "Cargando analíticas",
|
||||
"restart": "Reiniciar",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Créer un compte administrateur",
|
||||
"setupErrorCreateAdmin": "Une erreur s'est produite lors de la création du compte administrateur du serveur.",
|
||||
"certificateStatus": "Certificat",
|
||||
"certificateStatusAutoRefreshHint": "L'état se rafraîchit automatiquement.",
|
||||
"loading": "Chargement",
|
||||
"loadingAnalytics": "Chargement de l'analyse",
|
||||
"restart": "Redémarrer",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Crea Account Admin",
|
||||
"setupErrorCreateAdmin": "Si è verificato un errore durante la creazione dell'account amministratore del server.",
|
||||
"certificateStatus": "Certificato",
|
||||
"certificateStatusAutoRefreshHint": "Lo stato si aggiorna automaticamente.",
|
||||
"loading": "Caricamento",
|
||||
"loadingAnalytics": "Caricamento Delle Analisi",
|
||||
"restart": "Riavvia",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "관리자 계정 생성",
|
||||
"setupErrorCreateAdmin": "서버 관리자 계정을 생성하는 동안 오류가 발생했습니다.",
|
||||
"certificateStatus": "인증서",
|
||||
"certificateStatusAutoRefreshHint": "상태가 자동으로 새로 고쳐집니다.",
|
||||
"loading": "로딩 중",
|
||||
"loadingAnalytics": "분석 로딩 중",
|
||||
"restart": "재시작",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Opprett administratorkonto",
|
||||
"setupErrorCreateAdmin": "En feil oppstod under opprettelsen av serveradministratorkontoen.",
|
||||
"certificateStatus": "Sertifikat",
|
||||
"certificateStatusAutoRefreshHint": "Status oppdateres automatisk.",
|
||||
"loading": "Laster inn",
|
||||
"loadingAnalytics": "Laster inn analyser",
|
||||
"restart": "Start på nytt",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Maak een beheeraccount aan",
|
||||
"setupErrorCreateAdmin": "Er is een fout opgetreden bij het maken van het serverbeheerdersaccount.",
|
||||
"certificateStatus": "Certificaat",
|
||||
"certificateStatusAutoRefreshHint": "Status ververst automatisch.",
|
||||
"loading": "Bezig met laden",
|
||||
"loadingAnalytics": "Laden van Analytics",
|
||||
"restart": "Herstarten",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Utwórz konto administratora",
|
||||
"setupErrorCreateAdmin": "Wystąpił błąd podczas tworzenia konta administratora serwera.",
|
||||
"certificateStatus": "Certyfikat",
|
||||
"certificateStatusAutoRefreshHint": "Status odświeża się automatycznie.",
|
||||
"loading": "Ładowanie",
|
||||
"loadingAnalytics": "Ładowanie Analityki",
|
||||
"restart": "Uruchom ponownie",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Criar Conta de Administrador",
|
||||
"setupErrorCreateAdmin": "Ocorreu um erro ao criar a conta de administrador do servidor.",
|
||||
"certificateStatus": "Certificado",
|
||||
"certificateStatusAutoRefreshHint": "Status atualiza automaticamente.",
|
||||
"loading": "Carregando",
|
||||
"loadingAnalytics": "Carregando Analytics",
|
||||
"restart": "Reiniciar",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Создать учётную запись администратора",
|
||||
"setupErrorCreateAdmin": "Произошла ошибка при создании учётной записи администратора сервера.",
|
||||
"certificateStatus": "Сертификат",
|
||||
"certificateStatusAutoRefreshHint": "Статус обновляется автоматически.",
|
||||
"loading": "Загрузка",
|
||||
"loadingAnalytics": "Загрузка аналитики",
|
||||
"restart": "Перезагрузка",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "Yönetici Hesabı Oluştur",
|
||||
"setupErrorCreateAdmin": "Sunucu yönetici hesabı oluşturulurken bir hata oluştu.",
|
||||
"certificateStatus": "Sertifika",
|
||||
"certificateStatusAutoRefreshHint": "Durum otomatik olarak yenilenir.",
|
||||
"loading": "Yükleniyor",
|
||||
"loadingAnalytics": "Analiz Yükleniyor",
|
||||
"restart": "Yeniden Başlat",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
"createAdminAccount": "创建管理员帐户",
|
||||
"setupErrorCreateAdmin": "创建服务器管理员账户时发生错误。",
|
||||
"certificateStatus": "证书",
|
||||
"certificateStatusAutoRefreshHint": "状态自动刷新。",
|
||||
"loading": "加载中",
|
||||
"loadingAnalytics": "加载分析",
|
||||
"restart": "重启",
|
||||
|
||||
@@ -122,8 +122,6 @@ export enum ActionsEnum {
|
||||
createOrgDomain = "createOrgDomain",
|
||||
deleteOrgDomain = "deleteOrgDomain",
|
||||
restartOrgDomain = "restartOrgDomain",
|
||||
sendUsageNotification = "sendUsageNotification",
|
||||
sendTrialNotification = "sendTrialNotification",
|
||||
createRemoteExitNode = "createRemoteExitNode",
|
||||
updateRemoteExitNode = "updateRemoteExitNode",
|
||||
getRemoteExitNode = "getRemoteExitNode",
|
||||
|
||||
@@ -566,6 +566,17 @@ export const alertWebhookActions = pgTable("alertWebhookActions", {
|
||||
lastSentAt: bigint("lastSentAt", { mode: "number" }) // nullable
|
||||
});
|
||||
|
||||
export const trialNotifications = pgTable("trialNotifications", {
|
||||
notificationId: serial("notificationId").primaryKey(),
|
||||
subscriptionId: varchar("subscriptionId", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => subscriptions.subscriptionId, {
|
||||
onDelete: "cascade"
|
||||
}),
|
||||
notificationType: varchar("notificationType", { length: 50 }).notNull(), // trial_ending_5d, trial_ending_24h, trial_ended
|
||||
sentAt: bigint("sentAt", { mode: "number" }).notNull()
|
||||
});
|
||||
|
||||
export type Approval = InferSelectModel<typeof approvals>;
|
||||
export type Limit = InferSelectModel<typeof limits>;
|
||||
export type Account = InferSelectModel<typeof account>;
|
||||
@@ -604,3 +615,12 @@ export type EventStreamingCursor = InferSelectModel<
|
||||
typeof eventStreamingCursors
|
||||
>;
|
||||
export type AlertResources = InferSelectModel<typeof alertResources>;
|
||||
export type AlertHealthChecks = InferSelectModel<typeof alertHealthChecks>;
|
||||
export type AlertSites = InferSelectModel<typeof alertSites>;
|
||||
export type AlertRules = InferSelectModel<typeof alertRules>;
|
||||
export type AlertEmailActions = InferSelectModel<typeof alertEmailActions>;
|
||||
export type AlertEmailRecipients = InferSelectModel<
|
||||
typeof alertEmailRecipients
|
||||
>;
|
||||
export type AlertWebhookActions = InferSelectModel<typeof alertWebhookActions>;
|
||||
export type TrialNotification = InferSelectModel<typeof trialNotifications>;
|
||||
|
||||
@@ -21,6 +21,9 @@ import {
|
||||
targetHealthCheck,
|
||||
users
|
||||
} from "./schema";
|
||||
import { serial, varchar } from "drizzle-orm/mysql-core";
|
||||
import { pgTable } from "drizzle-orm/pg-core";
|
||||
import { bigint } from "zod";
|
||||
|
||||
export const certificates = sqliteTable("certificates", {
|
||||
certId: integer("certId").primaryKey({ autoIncrement: true }),
|
||||
@@ -569,6 +572,19 @@ export const alertWebhookActions = sqliteTable("alertWebhookActions", {
|
||||
lastSentAt: integer("lastSentAt")
|
||||
});
|
||||
|
||||
export const trialNotifications = sqliteTable("trialNotifications", {
|
||||
notificationId: integer("notificationId").primaryKey({
|
||||
autoIncrement: true
|
||||
}),
|
||||
subscriptionId: text("subscriptionId")
|
||||
.notNull()
|
||||
.references(() => subscriptions.subscriptionId, {
|
||||
onDelete: "cascade"
|
||||
}),
|
||||
notificationType: text("notificationType").notNull(), // trial_ending_5d, trial_ending_24h, trial_ended
|
||||
sentAt: integer("sentAt").notNull()
|
||||
});
|
||||
|
||||
export type Approval = InferSelectModel<typeof approvals>;
|
||||
export type Limit = InferSelectModel<typeof limits>;
|
||||
export type Account = InferSelectModel<typeof account>;
|
||||
@@ -601,3 +617,10 @@ export type EventStreamingCursor = InferSelectModel<
|
||||
typeof eventStreamingCursors
|
||||
>;
|
||||
export type AlertResources = InferSelectModel<typeof alertResources>;
|
||||
export type AlertHealthChecks = InferSelectModel<typeof alertHealthChecks>;
|
||||
export type AlertSites = InferSelectModel<typeof alertSites>;
|
||||
export type AlertRule = InferSelectModel<typeof alertRules>;
|
||||
export type AlertEmailAction = InferSelectModel<typeof alertEmailActions>;
|
||||
export type AlertEmailRecipient = InferSelectModel<typeof alertEmailRecipients>;
|
||||
export type AlertWebhookAction = InferSelectModel<typeof alertWebhookActions>;
|
||||
export type TrialNotification = InferSelectModel<typeof trialNotifications>;
|
||||
|
||||
@@ -64,7 +64,7 @@ export const NotifyTrialExpiring = ({
|
||||
|
||||
<EmailText>
|
||||
Some features and resources may now be
|
||||
restricted or disconnected. To restore full
|
||||
restricted. To restore full
|
||||
access and continue using all the features
|
||||
you had during your trial, please upgrade to
|
||||
a paid plan.
|
||||
@@ -85,7 +85,7 @@ export const NotifyTrialExpiring = ({
|
||||
<strong>{orgName}</strong> will end on{" "}
|
||||
<strong>{trialEndsAt}</strong>
|
||||
{isLastDay
|
||||
? " — that's tomorrow!"
|
||||
? " - that's tomorrow!"
|
||||
: `, in ${daysRemaining} days`}
|
||||
.
|
||||
</EmailText>
|
||||
@@ -93,8 +93,7 @@ export const NotifyTrialExpiring = ({
|
||||
<EmailText>
|
||||
After your trial ends, your account will be
|
||||
moved to the free plan and some
|
||||
functionality may be restricted or your
|
||||
sites may disconnect.
|
||||
functionality may be restricted.
|
||||
</EmailText>
|
||||
|
||||
<EmailText>
|
||||
|
||||
@@ -25,7 +25,7 @@ export const tier1LimitSet: LimitSet = {
|
||||
|
||||
export const tier2LimitSet: LimitSet = {
|
||||
[FeatureId.USERS]: {
|
||||
value: 100,
|
||||
value: 50,
|
||||
description: "Team limit"
|
||||
},
|
||||
[FeatureId.SITES]: {
|
||||
@@ -48,7 +48,7 @@ export const tier2LimitSet: LimitSet = {
|
||||
|
||||
export const tier3LimitSet: LimitSet = {
|
||||
[FeatureId.USERS]: {
|
||||
value: 500,
|
||||
value: 250,
|
||||
description: "Business limit"
|
||||
},
|
||||
[FeatureId.SITES]: {
|
||||
|
||||
@@ -64,7 +64,7 @@ export const tierMatrix: Record<TierFeature, Tier[]> = {
|
||||
[TierFeature.SIEM]: ["enterprise"],
|
||||
[TierFeature.HTTPPrivateResources]: ["tier3", "enterprise"],
|
||||
[TierFeature.DomainNamespaces]: ["tier1", "tier2", "tier3", "enterprise"],
|
||||
[TierFeature.StandaloneHealthChecks]: ["tier2", "tier3", "enterprise"],
|
||||
[TierFeature.AlertingRules]: ["tier2", "tier3", "enterprise"],
|
||||
[TierFeature.StandaloneHealthChecks]: ["tier3", "enterprise"],
|
||||
[TierFeature.AlertingRules]: ["tier3", "enterprise"],
|
||||
[TierFeature.WildcardSubdomain]: ["tier1", "tier2", "tier3", "enterprise"]
|
||||
};
|
||||
|
||||
@@ -125,47 +125,28 @@ export async function updateClientResources(
|
||||
|
||||
const existingSiteIds = existingResource?.networkId
|
||||
? await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.select({ siteId: siteNetworks.siteId })
|
||||
.from(siteNetworks)
|
||||
.where(eq(siteNetworks.networkId, existingResource.networkId))
|
||||
: [];
|
||||
|
||||
let allSites: { siteId: number }[] = [];
|
||||
const allSites: { siteId: number }[] = [];
|
||||
|
||||
if (resourceData.site) {
|
||||
let siteSingle;
|
||||
const resourceSiteId = resourceData.site;
|
||||
|
||||
if (resourceSiteId) {
|
||||
// Look up site by niceId
|
||||
[siteSingle] = await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.from(sites)
|
||||
.where(
|
||||
and(
|
||||
eq(sites.niceId, resourceSiteId),
|
||||
eq(sites.orgId, orgId)
|
||||
)
|
||||
// Look up site by niceId
|
||||
const [siteSingle] = await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.from(sites)
|
||||
.where(
|
||||
and(
|
||||
eq(sites.niceId, resourceData.site),
|
||||
eq(sites.orgId, orgId)
|
||||
)
|
||||
.limit(1);
|
||||
} else if (siteId) {
|
||||
// Use the provided siteId directly, but verify it belongs to the org
|
||||
[siteSingle] = await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.from(sites)
|
||||
.where(
|
||||
and(eq(sites.siteId, siteId), eq(sites.orgId, orgId))
|
||||
)
|
||||
.limit(1);
|
||||
} else {
|
||||
throw new Error(`Target site is required`);
|
||||
)
|
||||
.limit(1);
|
||||
if (siteSingle) {
|
||||
allSites.push(siteSingle);
|
||||
}
|
||||
|
||||
if (!siteSingle) {
|
||||
throw new Error(
|
||||
`Site not found: ${resourceSiteId} in org ${orgId}`
|
||||
);
|
||||
}
|
||||
allSites.push(siteSingle);
|
||||
}
|
||||
|
||||
if (resourceData.sites) {
|
||||
@@ -180,15 +161,31 @@ export async function updateClientResources(
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (!site) {
|
||||
throw new Error(
|
||||
`Site not found: ${siteId} in org ${orgId}`
|
||||
);
|
||||
if (site) {
|
||||
allSites.push(site);
|
||||
}
|
||||
allSites.push(site);
|
||||
}
|
||||
}
|
||||
|
||||
if (siteId && allSites.length === 0) {
|
||||
// only add if there are not provided sites
|
||||
// Use the provided siteId directly, but verify it belongs to the org
|
||||
const [siteSingle] = await trx
|
||||
.select({ siteId: sites.siteId })
|
||||
.from(sites)
|
||||
.where(and(eq(sites.siteId, siteId), eq(sites.orgId, orgId)))
|
||||
.limit(1);
|
||||
if (siteSingle) {
|
||||
allSites.push(siteSingle);
|
||||
}
|
||||
}
|
||||
|
||||
if (allSites.length === 0) {
|
||||
throw new Error(
|
||||
`No valid sites found for private private resource ${resourceNiceId} in org ${orgId}`
|
||||
);
|
||||
}
|
||||
|
||||
if (existingResource) {
|
||||
let domainInfo:
|
||||
| { subdomain: string | null; domainId: string }
|
||||
@@ -215,9 +212,17 @@ export async function updateClientResources(
|
||||
enabled: true, // hardcoded for now
|
||||
// enabled: resourceData.enabled ?? true,
|
||||
alias: resourceData.alias || null,
|
||||
disableIcmp: resourceData["disable-icmp"],
|
||||
tcpPortRangeString: resourceData["tcp-ports"],
|
||||
udpPortRangeString: resourceData["udp-ports"],
|
||||
disableIcmp:
|
||||
resourceData["disable-icmp"] ||
|
||||
(resourceData.mode == "http" ? true : false), // default to true for http resources, otherwise false
|
||||
tcpPortRangeString:
|
||||
resourceData.mode == "http"
|
||||
? "443,80"
|
||||
: resourceData["tcp-ports"],
|
||||
udpPortRangeString:
|
||||
resourceData.mode == "http"
|
||||
? ""
|
||||
: resourceData["udp-ports"],
|
||||
fullDomain: resourceData["full-domain"] || null,
|
||||
subdomain: domainInfo ? domainInfo.subdomain : null,
|
||||
domainId: domainInfo ? domainInfo.domainId : null
|
||||
@@ -397,9 +402,17 @@ export async function updateClientResources(
|
||||
// enabled: resourceData.enabled ?? true,
|
||||
alias: resourceData.alias || null,
|
||||
aliasAddress: aliasAddress,
|
||||
disableIcmp: resourceData["disable-icmp"],
|
||||
tcpPortRangeString: resourceData["tcp-ports"],
|
||||
udpPortRangeString: resourceData["udp-ports"],
|
||||
disableIcmp:
|
||||
resourceData["disable-icmp"] ||
|
||||
(resourceData.mode == "http" ? true : false), // default to true for http resources, otherwise false
|
||||
tcpPortRangeString:
|
||||
resourceData.mode == "http"
|
||||
? "443,80"
|
||||
: resourceData["tcp-ports"],
|
||||
udpPortRangeString:
|
||||
resourceData.mode == "http"
|
||||
? ""
|
||||
: resourceData["udp-ports"],
|
||||
fullDomain: resourceData["full-domain"] || null,
|
||||
subdomain: domainInfo ? domainInfo.subdomain : null,
|
||||
domainId: domainInfo ? domainInfo.domainId : null
|
||||
|
||||
@@ -250,10 +250,31 @@ function extractFirstCert(pemBundle: string): string | null {
|
||||
return match ? match[0] : null;
|
||||
}
|
||||
|
||||
async function syncAcmeCerts(
|
||||
acmeJsonPath: string,
|
||||
resolver: string
|
||||
): Promise<void> {
|
||||
/**
|
||||
* Determine whether an ACME cert entry represents a wildcard cert by checking
|
||||
* both the primary domain (`main`) and the SANs. Some ACME clients (notably
|
||||
* Traefik) store the bare apex in `main` and only put the wildcard form in
|
||||
* `sans` (e.g. main="access.example.com", sans=["*.access.example.com"]).
|
||||
*/
|
||||
function detectWildcard(
|
||||
main: string,
|
||||
sans: string[] | undefined
|
||||
): { wildcard: boolean; wildcardSan: string | null } {
|
||||
if (main.startsWith("*.")) {
|
||||
return { wildcard: true, wildcardSan: null };
|
||||
}
|
||||
if (Array.isArray(sans)) {
|
||||
for (const san of sans) {
|
||||
if (typeof san !== "string") continue;
|
||||
if (san === `*.${main}` || san.startsWith("*.")) {
|
||||
return { wildcard: true, wildcardSan: san };
|
||||
}
|
||||
}
|
||||
}
|
||||
return { wildcard: false, wildcardSan: null };
|
||||
}
|
||||
|
||||
async function syncAcmeCerts(acmeJsonPath: string): Promise<void> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = fs.readFileSync(acmeJsonPath, "utf8");
|
||||
@@ -270,23 +291,41 @@ async function syncAcmeCerts(
|
||||
return;
|
||||
}
|
||||
|
||||
const resolverData = acmeJson[resolver];
|
||||
if (!resolverData || !Array.isArray(resolverData.Certificates)) {
|
||||
logger.debug(
|
||||
`acmeCertSync: no certificates found for resolver "${resolver}"`
|
||||
);
|
||||
const resolvers = Object.keys(acmeJson || {});
|
||||
if (resolvers.length === 0) {
|
||||
logger.debug(`acmeCertSync: no resolvers found in acme.json`);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const cert of resolverData.Certificates) {
|
||||
const domain = cert.domain?.main;
|
||||
const wildcard = domain.startsWith("*.");
|
||||
// Collect certificates from every resolver. If the same domain appears in
|
||||
// multiple resolvers, the last one wins (resolvers iterated in object order).
|
||||
const allCerts: AcmeCert[] = [];
|
||||
for (const resolver of resolvers) {
|
||||
const resolverData = acmeJson[resolver];
|
||||
if (!resolverData || !Array.isArray(resolverData.Certificates)) {
|
||||
logger.debug(
|
||||
`acmeCertSync: no certificates found for resolver "${resolver}"`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
logger.debug(
|
||||
`acmeCertSync: found ${resolverData.Certificates.length} certificate(s) for resolver "${resolver}"`
|
||||
);
|
||||
for (const cert of resolverData.Certificates) {
|
||||
allCerts.push(cert);
|
||||
}
|
||||
}
|
||||
|
||||
if (!domain) {
|
||||
for (const cert of allCerts) {
|
||||
const domain = cert?.domain?.main;
|
||||
|
||||
if (!domain || typeof domain !== "string") {
|
||||
logger.debug(`acmeCertSync: skipping cert with missing domain`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const { wildcard } = detectWildcard(domain, cert.domain?.sans);
|
||||
|
||||
if (!cert.certificate || !cert.key) {
|
||||
logger.debug(
|
||||
`acmeCertSync: skipping cert for ${domain} - empty certificate or key field`
|
||||
@@ -294,10 +333,17 @@ async function syncAcmeCerts(
|
||||
continue;
|
||||
}
|
||||
|
||||
const certPem = Buffer.from(cert.certificate, "base64").toString(
|
||||
"utf8"
|
||||
);
|
||||
const keyPem = Buffer.from(cert.key, "base64").toString("utf8");
|
||||
let certPem: string;
|
||||
let keyPem: string;
|
||||
try {
|
||||
certPem = Buffer.from(cert.certificate, "base64").toString("utf8");
|
||||
keyPem = Buffer.from(cert.key, "base64").toString("utf8");
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
`acmeCertSync: skipping cert for ${domain} - failed to base64-decode cert/key: ${err}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!certPem.trim() || !keyPem.trim()) {
|
||||
logger.debug(
|
||||
@@ -306,6 +352,39 @@ async function syncAcmeCerts(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate that the decoded data actually parses as a real X.509 cert
|
||||
// before we touch the database. This prevents importing partially-written
|
||||
// or corrupted entries from acme.json.
|
||||
const firstCertPemForValidation = extractFirstCert(certPem);
|
||||
if (!firstCertPemForValidation) {
|
||||
logger.debug(
|
||||
`acmeCertSync: skipping cert for ${domain} - no PEM certificate block found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let validatedX509: crypto.X509Certificate;
|
||||
try {
|
||||
validatedX509 = new crypto.X509Certificate(
|
||||
firstCertPemForValidation
|
||||
);
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
`acmeCertSync: skipping cert for ${domain} - invalid X.509 certificate: ${err}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sanity-check the private key parses too
|
||||
try {
|
||||
crypto.createPrivateKey(keyPem);
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
`acmeCertSync: skipping cert for ${domain} - invalid private key: ${err}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if cert already exists in DB
|
||||
const existing = await db
|
||||
.select()
|
||||
@@ -326,10 +405,11 @@ async function syncAcmeCerts(
|
||||
existing[0].certFile,
|
||||
config.getRawConfig().server.secret!
|
||||
);
|
||||
if (storedCertPem === certPem) {
|
||||
logger.debug(
|
||||
`acmeCertSync: cert for ${domain} is unchanged, skipping`
|
||||
);
|
||||
const wildcardUnchanged = existing[0].wildcard === wildcard;
|
||||
if (storedCertPem === certPem && wildcardUnchanged) {
|
||||
// logger.debug(
|
||||
// `acmeCertSync: cert for ${domain} is unchanged, skipping`
|
||||
// );
|
||||
continue;
|
||||
}
|
||||
// Cert has changed; capture old values so we can send a correct
|
||||
@@ -355,18 +435,16 @@ async function syncAcmeCerts(
|
||||
}
|
||||
}
|
||||
|
||||
// Parse cert expiry from the first cert in the PEM bundle
|
||||
// Parse cert expiry from the validated X.509 certificate
|
||||
let expiresAt: number | null = null;
|
||||
const firstCertPem = extractFirstCert(certPem);
|
||||
if (firstCertPem) {
|
||||
try {
|
||||
const x509 = new crypto.X509Certificate(firstCertPem);
|
||||
expiresAt = Math.floor(new Date(x509.validTo).getTime() / 1000);
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
`acmeCertSync: could not parse cert expiry for ${domain}: ${err}`
|
||||
);
|
||||
}
|
||||
try {
|
||||
expiresAt = Math.floor(
|
||||
new Date(validatedX509.validTo).getTime() / 1000
|
||||
);
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
`acmeCertSync: could not parse cert expiry for ${domain}: ${err}`
|
||||
);
|
||||
}
|
||||
|
||||
const encryptedCert = encrypt(
|
||||
@@ -468,20 +546,19 @@ export function initAcmeCertSync(): void {
|
||||
const acmeJsonPath =
|
||||
privateConfigData.acme?.acme_json_path ??
|
||||
"config/letsencrypt/acme.json";
|
||||
const resolver = privateConfigData.acme?.resolver ?? "letsencrypt";
|
||||
const intervalMs = privateConfigData.acme?.sync_interval_ms ?? 5000;
|
||||
|
||||
logger.debug(
|
||||
`acmeCertSync: starting ACME cert sync from "${acmeJsonPath}" using resolver "${resolver}" every ${intervalMs}ms`
|
||||
`acmeCertSync: starting ACME cert sync from "${acmeJsonPath}" across all resolvers every ${intervalMs}ms`
|
||||
);
|
||||
|
||||
// Run immediately on init, then on the configured interval
|
||||
syncAcmeCerts(acmeJsonPath, resolver).catch((err) => {
|
||||
syncAcmeCerts(acmeJsonPath).catch((err) => {
|
||||
logger.error(`acmeCertSync: error during initial sync: ${err}`);
|
||||
});
|
||||
|
||||
setInterval(() => {
|
||||
syncAcmeCerts(acmeJsonPath, resolver).catch((err) => {
|
||||
syncAcmeCerts(acmeJsonPath).catch((err) => {
|
||||
logger.error(`acmeCertSync: error during sync: ${err}`);
|
||||
});
|
||||
}, intervalMs);
|
||||
|
||||
@@ -19,12 +19,13 @@ import { eq, and, ne } from "drizzle-orm";
|
||||
|
||||
export async function getOrgTierData(
|
||||
orgId: string
|
||||
): Promise<{ tier: Tier | null; active: boolean }> {
|
||||
): Promise<{ tier: Tier | null; active: boolean; isTrial: boolean }> {
|
||||
let tier: Tier | null = null;
|
||||
let active = false;
|
||||
let isTrial = false;
|
||||
|
||||
if (build !== "saas") {
|
||||
return { tier, active };
|
||||
return { tier, active, isTrial };
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -35,7 +36,7 @@ export async function getOrgTierData(
|
||||
.limit(1);
|
||||
|
||||
if (!org) {
|
||||
return { tier, active };
|
||||
return { tier, active, isTrial };
|
||||
}
|
||||
|
||||
let orgIdToUse = org.orgId;
|
||||
@@ -44,7 +45,7 @@ export async function getOrgTierData(
|
||||
logger.warn(
|
||||
`Org ${orgId} is not a billing org and does not have a billingOrgId`
|
||||
);
|
||||
return { tier, active };
|
||||
return { tier, active, isTrial };
|
||||
}
|
||||
orgIdToUse = org.billingOrgId;
|
||||
}
|
||||
@@ -57,7 +58,7 @@ export async function getOrgTierData(
|
||||
.limit(1);
|
||||
|
||||
if (!customer) {
|
||||
return { tier, active };
|
||||
return { tier, active, isTrial };
|
||||
}
|
||||
|
||||
// Query for active subscriptions that are not license type
|
||||
@@ -84,11 +85,13 @@ export async function getOrgTierData(
|
||||
tier = subscription.type;
|
||||
active = true;
|
||||
}
|
||||
|
||||
isTrial = subscription.trial ?? false;
|
||||
}
|
||||
} catch (error) {
|
||||
// If org not found or error occurs, return null tier and inactive
|
||||
// This is acceptable behavior as per the function signature
|
||||
}
|
||||
|
||||
return { tier, active };
|
||||
return { tier, active, isTrial };
|
||||
}
|
||||
|
||||
@@ -102,7 +102,6 @@ export const privateConfigSchema = z.object({
|
||||
.string()
|
||||
.optional()
|
||||
.default("config/letsencrypt/acme.json"),
|
||||
resolver: z.string().optional().default("letsencrypt"),
|
||||
sync_interval_ms: z.number().optional().default(5000)
|
||||
})
|
||||
.optional(),
|
||||
|
||||
@@ -277,37 +277,37 @@ export async function getTraefikConfig(
|
||||
});
|
||||
});
|
||||
|
||||
// Query siteResources in HTTP mode with SSL enabled and aliases - cert generation / HTTPS edge
|
||||
const siteResourcesWithFullDomain = await db
|
||||
.select({
|
||||
siteResourceId: siteResources.siteResourceId,
|
||||
fullDomain: siteResources.fullDomain,
|
||||
mode: siteResources.mode
|
||||
})
|
||||
.from(siteResources)
|
||||
.innerJoin(
|
||||
siteNetworks,
|
||||
eq(siteResources.networkId, siteNetworks.networkId)
|
||||
)
|
||||
.innerJoin(sites, eq(siteNetworks.siteId, sites.siteId))
|
||||
.where(
|
||||
and(
|
||||
eq(siteResources.enabled, true),
|
||||
isNotNull(siteResources.fullDomain),
|
||||
eq(siteResources.mode, "http"),
|
||||
eq(siteResources.ssl, true),
|
||||
or(
|
||||
eq(sites.exitNodeId, exitNodeId),
|
||||
and(
|
||||
isNull(sites.exitNodeId),
|
||||
sql`(${siteTypes.includes("local") ? 1 : 0} = 1)`,
|
||||
eq(sites.type, "local"),
|
||||
sql`(${build != "saas" ? 1 : 0} = 1)`
|
||||
)
|
||||
),
|
||||
inArray(sites.type, siteTypes)
|
||||
let siteResourcesWithFullDomain: {
|
||||
siteResourceId: number;
|
||||
fullDomain: string | null;
|
||||
mode: "http" | "host" | "cidr";
|
||||
}[] = [];
|
||||
if (build == "enterprise") {
|
||||
// we dont want to do this on the cloud
|
||||
// Query siteResources in HTTP mode with SSL enabled and aliases - cert generation / HTTPS edge
|
||||
siteResourcesWithFullDomain = await db
|
||||
.select({
|
||||
siteResourceId: siteResources.siteResourceId,
|
||||
fullDomain: siteResources.fullDomain,
|
||||
mode: siteResources.mode
|
||||
})
|
||||
.from(siteResources)
|
||||
.innerJoin(
|
||||
siteNetworks,
|
||||
eq(siteResources.networkId, siteNetworks.networkId)
|
||||
)
|
||||
);
|
||||
.innerJoin(sites, eq(siteNetworks.siteId, sites.siteId))
|
||||
.where(
|
||||
and(
|
||||
eq(siteResources.enabled, true),
|
||||
isNotNull(siteResources.fullDomain),
|
||||
eq(siteResources.mode, "http"),
|
||||
eq(siteResources.ssl, true),
|
||||
eq(sites.exitNodeId, exitNodeId),
|
||||
inArray(sites.type, siteTypes)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
let validCerts: CertificateResult[] = [];
|
||||
if (privateConfig.getRawPrivateConfig().flags.use_pangolin_dns) {
|
||||
|
||||
@@ -30,8 +30,10 @@ import {
|
||||
userOrgRoles,
|
||||
siteProvisioningKeyOrg,
|
||||
siteProvisioningKeys,
|
||||
alertRules,
|
||||
targetHealthCheck
|
||||
} from "@server/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
|
||||
/**
|
||||
* Get the maximum allowed retention days for a given tier
|
||||
@@ -318,6 +320,14 @@ async function disableFeature(
|
||||
await disableSiteProvisioningKeys(orgId);
|
||||
break;
|
||||
|
||||
case TierFeature.AlertingRules:
|
||||
await disableAlertingRules(orgId);
|
||||
break;
|
||||
|
||||
case TierFeature.StandaloneHealthChecks:
|
||||
await disableStandaloneHealthChecks(orgId);
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.warn(
|
||||
`Unknown feature ${feature} for org ${orgId}, skipping`
|
||||
@@ -360,8 +370,7 @@ async function disableFullRbac(orgId: string): Promise<void> {
|
||||
async function disableSiteProvisioningKeys(orgId: string): Promise<void> {
|
||||
const rows = await db
|
||||
.select({
|
||||
siteProvisioningKeyId:
|
||||
siteProvisioningKeyOrg.siteProvisioningKeyId
|
||||
siteProvisioningKeyId: siteProvisioningKeyOrg.siteProvisioningKeyId
|
||||
})
|
||||
.from(siteProvisioningKeyOrg)
|
||||
.where(eq(siteProvisioningKeyOrg.orgId, orgId));
|
||||
@@ -525,6 +534,29 @@ async function disablePasswordExpirationPolicies(orgId: string): Promise<void> {
|
||||
logger.info(`Disabled password expiration policies for org ${orgId}`);
|
||||
}
|
||||
|
||||
async function disableAlertingRules(orgId: string): Promise<void> {
|
||||
await db
|
||||
.update(alertRules)
|
||||
.set({ enabled: false })
|
||||
.where(eq(alertRules.orgId, orgId));
|
||||
|
||||
logger.info(`Disabled all alert rules for org ${orgId}`);
|
||||
}
|
||||
|
||||
async function disableStandaloneHealthChecks(orgId: string): Promise<void> {
|
||||
await db
|
||||
.update(targetHealthCheck)
|
||||
.set({ hcEnabled: false })
|
||||
.where(
|
||||
and(
|
||||
eq(targetHealthCheck.orgId, orgId),
|
||||
isNull(targetHealthCheck.targetId)
|
||||
)
|
||||
);
|
||||
|
||||
logger.info(`Disabled standalone health checks for org ${orgId}`);
|
||||
}
|
||||
|
||||
async function disableAutoProvisioning(orgId: string): Promise<void> {
|
||||
// Get all IDP IDs for this org through the idpOrg join table
|
||||
const orgIdps = await db
|
||||
|
||||
@@ -174,6 +174,19 @@ export async function handleSubscriptionCreated(
|
||||
// TODO: update user in Sendy
|
||||
}
|
||||
}
|
||||
|
||||
// delete the trial subscrition if we have one
|
||||
await db
|
||||
.delete(subscriptions)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
subscriptions.customerId,
|
||||
subscription.customer as string
|
||||
),
|
||||
eq(subscriptions.trial, true)
|
||||
)
|
||||
);
|
||||
} else if (type === "license") {
|
||||
logger.debug(
|
||||
`License subscription created for org ${customer.orgId}, no lifecycle handling needed.`
|
||||
|
||||
@@ -165,7 +165,6 @@ authenticated.get(
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/certificate/:domainId/:domain",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyCertificateAccess,
|
||||
verifyUserHasAction(ActionsEnum.getCertificate),
|
||||
|
||||
@@ -67,24 +67,20 @@ if (build == "saas") {
|
||||
verifyApiKeyIsRoot,
|
||||
certificates.syncCertToNewts
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
`/org/:orgId/send-usage-notification`,
|
||||
verifyApiKeyIsRoot, // We are the only ones who can use root key so its fine
|
||||
org.sendUsageNotification
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
`/org/:orgId/send-trial-notification`,
|
||||
verifyApiKeyIsRoot,
|
||||
org.sendTrialNotification
|
||||
);
|
||||
}
|
||||
|
||||
authenticated.post(
|
||||
`/org/:orgId/send-usage-notification`,
|
||||
verifyApiKeyIsRoot, // We are the only ones who can use root key so its fine
|
||||
verifyApiKeyHasAction(ActionsEnum.sendUsageNotification),
|
||||
logActionAudit(ActionsEnum.sendUsageNotification),
|
||||
org.sendUsageNotification
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
`/org/:orgId/send-trial-notification`,
|
||||
verifyApiKeyIsRoot,
|
||||
verifyApiKeyHasAction(ActionsEnum.sendTrialNotification),
|
||||
logActionAudit(ActionsEnum.sendTrialNotification),
|
||||
org.sendTrialNotification
|
||||
);
|
||||
|
||||
authenticated.delete(
|
||||
"/idp/:idpId",
|
||||
verifyApiKeyIsRoot,
|
||||
|
||||
@@ -104,8 +104,9 @@ export async function deleteMyAccount(
|
||||
(r) => r.isBillingOrg && r.isOwner
|
||||
)?.orgId;
|
||||
if (primaryOrgId) {
|
||||
const { tier, active } = await getOrgTierData(primaryOrgId);
|
||||
if (active && tier) {
|
||||
const { tier, active, isTrial } =
|
||||
await getOrgTierData(primaryOrgId);
|
||||
if (active && tier && !isTrial) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, olms, users } from "@server/db";
|
||||
import { db, idp, idpOidcConfig, olms, users } from "@server/db";
|
||||
import { clients, currentFingerprint } from "@server/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -236,6 +236,9 @@ export type GetClientResponse = NonNullable<
|
||||
lastSeen: number | null;
|
||||
} | null;
|
||||
posture: PostureData | null;
|
||||
userType: string | null;
|
||||
idpName: string | null;
|
||||
idpVariant: string | null;
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
@@ -337,6 +340,30 @@ export async function getClient(
|
||||
: maskPostureDataWithPlaceholder(rawPosture)
|
||||
: null;
|
||||
|
||||
let userType: string | null = null;
|
||||
let idpName: string | null = null;
|
||||
let idpVariant: string | null = null;
|
||||
|
||||
if (client.clients.userId) {
|
||||
const [idpRow] = await db
|
||||
.select({
|
||||
userType: users.type,
|
||||
idpName: idp.name,
|
||||
idpVariant: idpOidcConfig.variant
|
||||
})
|
||||
.from(users)
|
||||
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
||||
.leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
|
||||
.where(eq(users.userId, client.clients.userId))
|
||||
.limit(1);
|
||||
|
||||
if (idpRow) {
|
||||
userType = idpRow.userType;
|
||||
idpName = idpRow.idpName;
|
||||
idpVariant = idpRow.idpVariant;
|
||||
}
|
||||
}
|
||||
|
||||
const data: GetClientResponse = {
|
||||
...client.clients,
|
||||
name: clientName,
|
||||
@@ -347,7 +374,10 @@ export async function getClient(
|
||||
userName: client.user?.name ?? null,
|
||||
userUsername: client.user?.username ?? null,
|
||||
fingerprint: fingerprintData,
|
||||
posture: postureData
|
||||
posture: postureData,
|
||||
userType,
|
||||
idpName,
|
||||
idpVariant
|
||||
};
|
||||
|
||||
return response<GetClientResponse>(res, {
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
clients,
|
||||
currentFingerprint,
|
||||
db,
|
||||
idp,
|
||||
idpOidcConfig,
|
||||
olms,
|
||||
orgs,
|
||||
roleClients,
|
||||
@@ -165,6 +167,9 @@ function queryUserDevicesBase() {
|
||||
userId: clients.userId,
|
||||
username: users.username,
|
||||
userEmail: users.email,
|
||||
userType: users.type,
|
||||
idpName: idp.name,
|
||||
idpVariant: idpOidcConfig.variant,
|
||||
niceId: clients.niceId,
|
||||
agent: olms.agent,
|
||||
approvalState: clients.approvalState,
|
||||
@@ -184,6 +189,8 @@ function queryUserDevicesBase() {
|
||||
.leftJoin(orgs, eq(clients.orgId, orgs.orgId))
|
||||
.leftJoin(olms, eq(clients.clientId, olms.clientId))
|
||||
.leftJoin(users, eq(clients.userId, users.userId))
|
||||
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
||||
.leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
|
||||
.leftJoin(currentFingerprint, eq(olms.olmId, currentFingerprint.olmId));
|
||||
}
|
||||
|
||||
|
||||
@@ -152,7 +152,7 @@ export type ResourceWithTargets = {
|
||||
siteId: number;
|
||||
siteName: string;
|
||||
siteNiceId: string;
|
||||
online: boolean;
|
||||
online?: boolean; // undefined for local sites
|
||||
}>;
|
||||
};
|
||||
|
||||
@@ -383,12 +383,8 @@ export async function listResources(
|
||||
.select({ resourceId: targets.resourceId })
|
||||
.from(targets)
|
||||
.innerJoin(sites, eq(targets.siteId, sites.siteId))
|
||||
.where(
|
||||
and(eq(sites.orgId, orgId), eq(sites.siteId, siteId))
|
||||
);
|
||||
conditions.push(
|
||||
inArray(resources.resourceId, resourcesWithSite)
|
||||
);
|
||||
.where(and(eq(sites.orgId, orgId), eq(sites.siteId, siteId)));
|
||||
conditions.push(inArray(resources.resourceId, resourcesWithSite));
|
||||
}
|
||||
|
||||
const baseQuery = queryResourcesBase().where(and(...conditions));
|
||||
@@ -426,7 +422,8 @@ export async function listResources(
|
||||
hcEnabled: targetHealthCheck.hcEnabled,
|
||||
siteName: sites.name,
|
||||
siteNiceId: sites.niceId,
|
||||
siteOnline: sites.online
|
||||
siteOnline: sites.online,
|
||||
siteType: sites.type
|
||||
})
|
||||
.from(targets)
|
||||
.where(inArray(targets.resourceId, resourceIdList))
|
||||
@@ -481,18 +478,19 @@ export async function listResources(
|
||||
siteId: number;
|
||||
siteName: string;
|
||||
siteNiceId: string;
|
||||
online: boolean;
|
||||
online?: boolean;
|
||||
}
|
||||
>();
|
||||
for (const t of raw) {
|
||||
if (typeof t.siteId !== "number" || siteById.has(t.siteId)) {
|
||||
continue;
|
||||
}
|
||||
const isLocal = t.siteType === "local";
|
||||
siteById.set(t.siteId, {
|
||||
siteId: t.siteId,
|
||||
siteName: t.siteName ?? "",
|
||||
siteNiceId: t.siteNiceId ?? "",
|
||||
online: Boolean(t.siteOnline)
|
||||
online: isLocal ? undefined : Boolean(t.siteOnline)
|
||||
});
|
||||
}
|
||||
entry.sites = Array.from(siteById.values());
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, Site, siteNetworks, siteResources } from "@server/db";
|
||||
import { newts, newtSessions, sites } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -77,17 +77,20 @@ export async function deleteSite(
|
||||
.where(eq(siteNetworks.siteId, siteId));
|
||||
|
||||
// loop through them
|
||||
for (const network of await networks) {
|
||||
const [siteResource] = await trx
|
||||
.select()
|
||||
.from(siteResources)
|
||||
.where(eq(siteResources.networkId, network.networkId));
|
||||
if (siteResource) {
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
siteResource,
|
||||
trx
|
||||
);
|
||||
}
|
||||
const updatedSiteResources = await trx
|
||||
.select()
|
||||
.from(siteResources)
|
||||
.where(
|
||||
inArray(
|
||||
siteResources.networkId,
|
||||
networks.map((n) => n.networkId)
|
||||
)
|
||||
);
|
||||
for (const siteResource of updatedSiteResources) {
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
siteResource,
|
||||
trx
|
||||
);
|
||||
}
|
||||
|
||||
// get the newt on the site by querying the newt table for siteId
|
||||
|
||||
@@ -31,7 +31,9 @@ let staleNewtVersion: string | null = null;
|
||||
|
||||
async function getLatestNewtVersion(): Promise<string | null> {
|
||||
try {
|
||||
const cachedVersion = await cache.get<string>("cache:latestNewtVersion");
|
||||
const cachedVersion = await cache.get<string>(
|
||||
"cache:latestNewtVersion"
|
||||
);
|
||||
if (cachedVersion) {
|
||||
return cachedVersion;
|
||||
}
|
||||
@@ -226,7 +228,10 @@ function querySitesBase() {
|
||||
);
|
||||
}
|
||||
|
||||
type SiteWithUpdateAvailable = Awaited<ReturnType<typeof querySitesBase>>[0] & {
|
||||
type SiteRowBase = Awaited<ReturnType<typeof querySitesBase>>[0];
|
||||
|
||||
type SiteWithUpdateAvailable = Omit<SiteRowBase, "online"> & {
|
||||
online?: SiteRowBase["online"]; // undefined for local sites
|
||||
newtUpdateAvailable?: boolean;
|
||||
};
|
||||
|
||||
@@ -338,7 +343,9 @@ export async function listSites(
|
||||
|
||||
// we need to add `as` so that drizzle filters the result as a subquery
|
||||
const countQuery = db.$count(
|
||||
querySitesBase().where(and(...conditions)).as("filtered_sites")
|
||||
querySitesBase()
|
||||
.where(and(...conditions))
|
||||
.as("filtered_sites")
|
||||
);
|
||||
|
||||
const siteListQuery = baseQuery
|
||||
@@ -397,9 +404,13 @@ export async function listSites(
|
||||
);
|
||||
}
|
||||
|
||||
const sitesPayload = sitesWithUpdates.map((site) =>
|
||||
site.type === "local" ? { ...site, online: undefined } : site
|
||||
);
|
||||
|
||||
return response<ListSitesResponse>(res, {
|
||||
data: {
|
||||
sites: sitesWithUpdates,
|
||||
sites: sitesPayload,
|
||||
pagination: {
|
||||
total: totalCount,
|
||||
pageSize,
|
||||
|
||||
@@ -46,7 +46,8 @@ const createSiteResourceSchema = z
|
||||
mode: z.enum(["host", "cidr", "http"]),
|
||||
ssl: z.boolean().optional(), // only used for http mode
|
||||
scheme: z.enum(["http", "https"]).optional(),
|
||||
siteIds: z.array(z.int()),
|
||||
siteIds: z.array(z.int()).optional(),
|
||||
siteId: z.number().int().positive().optional(), // DEPRECATED: for backward compatibility, we will convert this to siteIds array if provided
|
||||
// proxyPort: z.int().positive().optional(),
|
||||
destinationPort: z.int().positive().optional(),
|
||||
destination: z.string().min(1),
|
||||
@@ -132,6 +133,17 @@ const createSiteResourceSchema = z
|
||||
message:
|
||||
"HTTP mode requires scheme (http or https) and a valid destination port"
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
return (
|
||||
(data.siteIds !== undefined && data.siteIds.length > 0) ||
|
||||
data.siteId !== undefined
|
||||
);
|
||||
},
|
||||
{
|
||||
message: "At least one of siteIds or siteId must be provided"
|
||||
}
|
||||
);
|
||||
|
||||
export type CreateSiteResourceBody = z.infer<typeof createSiteResourceSchema>;
|
||||
@@ -187,7 +199,8 @@ export async function createSiteResource(
|
||||
const {
|
||||
name,
|
||||
niceId,
|
||||
siteIds,
|
||||
siteIds: siteIdsInput = [],
|
||||
siteId,
|
||||
mode,
|
||||
scheme,
|
||||
// proxyPort,
|
||||
@@ -208,6 +221,12 @@ export async function createSiteResource(
|
||||
subdomain
|
||||
} = parsedBody.data;
|
||||
|
||||
// Backward compatibility: merge deprecated siteId into siteIds array
|
||||
const siteIds = [...siteIdsInput];
|
||||
if (siteId !== undefined && !siteIds.includes(siteId)) {
|
||||
siteIds.push(siteId);
|
||||
}
|
||||
|
||||
if (mode == "http") {
|
||||
const hasHttpFeature = await isLicensedOrSubscribed(
|
||||
orgId,
|
||||
@@ -389,9 +408,10 @@ export async function createSiteResource(
|
||||
enabled,
|
||||
alias: alias ? alias.trim() : null,
|
||||
aliasAddress,
|
||||
tcpPortRangeString,
|
||||
udpPortRangeString,
|
||||
disableIcmp,
|
||||
tcpPortRangeString:
|
||||
mode == "http" ? "443,80" : tcpPortRangeString,
|
||||
udpPortRangeString: mode == "http" ? "" : udpPortRangeString,
|
||||
disableIcmp: disableIcmp || (mode == "http" ? true : false), // default to true for http resources, otherwise false
|
||||
domainId,
|
||||
subdomain: finalSubdomain,
|
||||
fullDomain
|
||||
@@ -476,11 +496,6 @@ export async function createSiteResource(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
newSiteResource,
|
||||
trx
|
||||
); // we need to call this because we added to the admin role
|
||||
});
|
||||
|
||||
if (!newSiteResource) {
|
||||
@@ -496,10 +511,32 @@ export async function createSiteResource(
|
||||
`Created site resource ${newSiteResource.siteResourceId} for org ${orgId}`
|
||||
);
|
||||
|
||||
if (ssl && mode === "http" && domainId && fullDomain && build != "oss") {
|
||||
if (
|
||||
ssl &&
|
||||
mode === "http" &&
|
||||
domainId &&
|
||||
fullDomain &&
|
||||
build != "oss"
|
||||
) {
|
||||
await createCertificate(domainId, fullDomain, db);
|
||||
}
|
||||
|
||||
// Run in the background after the response is sent. Wrapped in its
|
||||
// own transaction so it always executes on the primary — avoiding any
|
||||
// replica-lag issues while still allowing the HTTP response to return
|
||||
// early.
|
||||
db.transaction(async (trx) => {
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
newSiteResource!,
|
||||
trx
|
||||
);
|
||||
}).catch((err) => {
|
||||
logger.error(
|
||||
`Error rebuilding client associations for site resource ${newSiteResource!.siteResourceId}:`,
|
||||
err
|
||||
);
|
||||
});
|
||||
|
||||
return response(res, {
|
||||
data: newSiteResource,
|
||||
success: true,
|
||||
|
||||
@@ -63,17 +63,26 @@ export async function deleteSiteResource(
|
||||
);
|
||||
}
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
// Delete the site resource
|
||||
const [removedSiteResource] = await trx
|
||||
.delete(siteResources)
|
||||
.where(eq(siteResources.siteResourceId, siteResourceId))
|
||||
.returning();
|
||||
// Delete the site resource
|
||||
const [removedSiteResource] = await db
|
||||
.delete(siteResources)
|
||||
.where(eq(siteResources.siteResourceId, siteResourceId))
|
||||
.returning();
|
||||
|
||||
// Run in the background after the response is sent. Wrapped in its
|
||||
// own transaction so it always executes on the primary — avoiding any
|
||||
// replica-lag issues while still allowing the HTTP response to return
|
||||
// early.
|
||||
db.transaction(async (trx) => {
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
removedSiteResource,
|
||||
trx
|
||||
);
|
||||
}).catch((err) => {
|
||||
logger.error(
|
||||
`Error rebuilding client associations for site resource ${removedSiteResource!.siteResourceId}:`,
|
||||
err
|
||||
);
|
||||
});
|
||||
|
||||
logger.info(`Deleted site resource ${siteResourceId}`);
|
||||
|
||||
@@ -98,9 +98,11 @@ export type ListAllSiteResourcesByOrgResponse = PaginatedResponse<{
|
||||
*/
|
||||
function aggCol<T>(column: any) {
|
||||
if (DB_TYPE === "sqlite") {
|
||||
// json_group_array will include NULLs for left-joined missing rows;
|
||||
// we filter them out in transformSiteResourceRow keeping arrays aligned.
|
||||
return sql<T>`json_group_array(${column})`;
|
||||
}
|
||||
return sql<T>`array_agg(${column})`;
|
||||
return sql<T>`COALESCE(array_agg(${column}) FILTER (WHERE ${sites.siteId} IS NOT NULL), '{}')`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,16 +114,36 @@ function transformSiteResourceRow(row: any) {
|
||||
if (DB_TYPE !== "sqlite") {
|
||||
return row;
|
||||
}
|
||||
const siteIdsRaw = JSON.parse(row.siteIds) as (number | null)[];
|
||||
const siteNamesRaw = JSON.parse(row.siteNames) as (string | null)[];
|
||||
const siteNiceIdsRaw = JSON.parse(row.siteNiceIds) as (string | null)[];
|
||||
const siteAddressesRaw = JSON.parse(row.siteAddresses) as (string | null)[];
|
||||
const siteOnlinesRaw = JSON.parse(row.siteOnlines) as (0 | 1 | null)[];
|
||||
|
||||
// When a site resource has no associated sites (left join produced no
|
||||
// matches), the aggregated arrays will contain a single NULL entry. Strip
|
||||
// those out, keeping the parallel arrays aligned by siteId presence.
|
||||
const siteIds: number[] = [];
|
||||
const siteNames: string[] = [];
|
||||
const siteNiceIds: string[] = [];
|
||||
const siteAddresses: (string | null)[] = [];
|
||||
const siteOnlines: boolean[] = [];
|
||||
for (let i = 0; i < siteIdsRaw.length; i++) {
|
||||
if (siteIdsRaw[i] == null) continue;
|
||||
siteIds.push(siteIdsRaw[i] as number);
|
||||
siteNames.push((siteNamesRaw[i] ?? "") as string);
|
||||
siteNiceIds.push((siteNiceIdsRaw[i] ?? "") as string);
|
||||
siteAddresses.push(siteAddressesRaw[i] ?? null);
|
||||
siteOnlines.push(siteOnlinesRaw[i] === 1);
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
siteNames: JSON.parse(row.siteNames) as string[],
|
||||
siteNiceIds: JSON.parse(row.siteNiceIds) as string[],
|
||||
siteIds: JSON.parse(row.siteIds) as number[],
|
||||
siteAddresses: JSON.parse(row.siteAddresses) as (string | null)[],
|
||||
// SQLite stores booleans as 0/1 integers
|
||||
siteOnlines: (JSON.parse(row.siteOnlines) as (0 | 1)[]).map(
|
||||
(v) => v === 1
|
||||
) as boolean[]
|
||||
siteNames,
|
||||
siteNiceIds,
|
||||
siteIds,
|
||||
siteAddresses,
|
||||
siteOnlines
|
||||
};
|
||||
}
|
||||
|
||||
@@ -158,11 +180,11 @@ function querySiteResourcesBase() {
|
||||
siteOnlines: aggCol<boolean[]>(sites.online)
|
||||
})
|
||||
.from(siteResources)
|
||||
.innerJoin(
|
||||
.leftJoin(
|
||||
siteNetworks,
|
||||
eq(siteResources.networkId, siteNetworks.networkId)
|
||||
)
|
||||
.innerJoin(sites, eq(siteNetworks.siteId, sites.siteId))
|
||||
.leftJoin(sites, eq(siteNetworks.siteId, sites.siteId))
|
||||
.groupBy(siteResources.siteResourceId);
|
||||
}
|
||||
|
||||
@@ -215,6 +237,8 @@ export async function listAllSiteResourcesByOrg(
|
||||
const conditions = [and(eq(siteResources.orgId, orgId))];
|
||||
|
||||
if (siteId != null) {
|
||||
// Keep inner joins here: filtering by a specific site implies the
|
||||
// resource must have at least one matching site.
|
||||
const resourcesForSite = db
|
||||
.select({ id: siteResources.siteResourceId })
|
||||
.from(siteResources)
|
||||
|
||||
@@ -43,7 +43,8 @@ const updateSiteResourceParamsSchema = z.strictObject({
|
||||
const updateSiteResourceSchema = z
|
||||
.strictObject({
|
||||
name: z.string().min(1).max(255).optional(),
|
||||
siteIds: z.array(z.int()),
|
||||
siteIds: z.array(z.int()).optional(),
|
||||
siteId: z.int().positive().optional(),
|
||||
// niceId: z.string().min(1).max(255).regex(/^[a-zA-Z0-9-]+$/, "niceId can only contain letters, numbers, and dashes").optional(),
|
||||
niceId: z
|
||||
.string()
|
||||
@@ -142,6 +143,17 @@ const updateSiteResourceSchema = z
|
||||
message:
|
||||
"HTTP mode requires scheme (http or https) and a valid destination port"
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
return (
|
||||
(data.siteIds !== undefined && data.siteIds.length > 0) ||
|
||||
data.siteId !== undefined
|
||||
);
|
||||
},
|
||||
{
|
||||
message: "At least one of siteIds or siteId must be provided"
|
||||
}
|
||||
);
|
||||
|
||||
export type UpdateSiteResourceBody = z.infer<typeof updateSiteResourceSchema>;
|
||||
@@ -196,7 +208,8 @@ export async function updateSiteResource(
|
||||
const { siteResourceId } = parsedParams.data;
|
||||
const {
|
||||
name,
|
||||
siteIds, // because it can change
|
||||
siteIds: siteIdsInput = [], // because it can change
|
||||
siteId,
|
||||
niceId,
|
||||
mode,
|
||||
scheme,
|
||||
@@ -217,6 +230,12 @@ export async function updateSiteResource(
|
||||
subdomain
|
||||
} = parsedBody.data;
|
||||
|
||||
// Backward compatibility: merge deprecated siteId into siteIds array
|
||||
const siteIds = [...siteIdsInput];
|
||||
if (siteId !== undefined && !siteIds.includes(siteId)) {
|
||||
siteIds.push(siteId);
|
||||
}
|
||||
|
||||
// Check if site resource exists
|
||||
const [existingSiteResource] = await db
|
||||
.select()
|
||||
@@ -412,9 +431,6 @@ export async function updateSiteResource(
|
||||
})
|
||||
.returning();
|
||||
|
||||
// wait some time to allow for messages to be handled
|
||||
await new Promise((resolve) => setTimeout(resolve, 750));
|
||||
|
||||
const sshPamSet =
|
||||
isLicensedSshPam &&
|
||||
(authDaemonPort !== undefined ||
|
||||
@@ -440,9 +456,12 @@ export async function updateSiteResource(
|
||||
destinationPort,
|
||||
enabled,
|
||||
alias: alias ? alias.trim() : null,
|
||||
tcpPortRangeString,
|
||||
udpPortRangeString,
|
||||
disableIcmp,
|
||||
tcpPortRangeString:
|
||||
mode == "http" ? "443,80" : tcpPortRangeString,
|
||||
udpPortRangeString:
|
||||
mode == "http" ? "" : udpPortRangeString,
|
||||
disableIcmp:
|
||||
disableIcmp || (mode == "http" ? true : false), // default to true for http resources, otherwise false
|
||||
domainId,
|
||||
subdomain: finalSubdomain,
|
||||
fullDomain,
|
||||
@@ -534,11 +553,6 @@ export async function updateSiteResource(
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
updatedSiteResource,
|
||||
trx
|
||||
);
|
||||
} else {
|
||||
// Update the site resource
|
||||
const sshPamSet =
|
||||
@@ -668,7 +682,24 @@ export async function updateSiteResource(
|
||||
}
|
||||
|
||||
logger.info(`Updated site resource ${siteResourceId}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Background: wait for removal messages to propagate, then rebuild
|
||||
// associations for the re-created resource. Own transaction ensures
|
||||
// execution on the primary against fully committed state.
|
||||
(async () => {
|
||||
await db.transaction(async (trx) => {
|
||||
if (!updatedSiteResource) {
|
||||
throw new Error("No updated resource found after update");
|
||||
}
|
||||
if (sitesChanged) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 750));
|
||||
await rebuildClientAssociationsFromSiteResource(
|
||||
updatedSiteResource,
|
||||
trx
|
||||
);
|
||||
}
|
||||
await handleMessagingForUpdatedSiteResource(
|
||||
existingSiteResource,
|
||||
updatedSiteResource,
|
||||
@@ -678,7 +709,12 @@ export async function updateSiteResource(
|
||||
})),
|
||||
trx
|
||||
);
|
||||
}
|
||||
});
|
||||
})().catch((err) => {
|
||||
logger.error(
|
||||
`Error rebuilding client associations for site resource ${updatedSiteResource?.siteResourceId}:`,
|
||||
err
|
||||
);
|
||||
});
|
||||
|
||||
return response(res, {
|
||||
@@ -734,6 +770,9 @@ export async function handleMessagingForUpdatedSiteResource(
|
||||
const fullDomainChanged =
|
||||
existingSiteResource &&
|
||||
existingSiteResource.fullDomain !== updatedSiteResource.fullDomain;
|
||||
const sslChanged =
|
||||
existingSiteResource &&
|
||||
existingSiteResource.ssl !== updatedSiteResource.ssl;
|
||||
const portRangesChanged =
|
||||
existingSiteResource &&
|
||||
(existingSiteResource.tcpPortRangeString !==
|
||||
@@ -749,6 +788,7 @@ export async function handleMessagingForUpdatedSiteResource(
|
||||
destinationChanged ||
|
||||
aliasChanged ||
|
||||
fullDomainChanged ||
|
||||
sslChanged ||
|
||||
portRangesChanged ||
|
||||
destinationPortChanged
|
||||
) {
|
||||
@@ -765,9 +805,10 @@ export async function handleMessagingForUpdatedSiteResource(
|
||||
);
|
||||
}
|
||||
|
||||
// Only update targets on newt if destination changed
|
||||
// Only update targets on newt if these items change
|
||||
if (
|
||||
destinationChanged ||
|
||||
sslChanged || // we need to push a new cert if the ssl changed
|
||||
portRangesChanged ||
|
||||
fullDomainChanged || // if the domain changes we need to update the certs and stuff
|
||||
destinationPortChanged
|
||||
|
||||
@@ -16,6 +16,9 @@ export default async function migration() {
|
||||
thc."targetId",
|
||||
t."siteId",
|
||||
s."orgId",
|
||||
r."name" AS "resourceName",
|
||||
t."ip",
|
||||
t."port",
|
||||
thc."hcEnabled",
|
||||
thc."hcPath",
|
||||
thc."hcScheme",
|
||||
@@ -33,13 +36,17 @@ export default async function migration() {
|
||||
thc."hcTlsServerName"
|
||||
FROM "targetHealthCheck" thc
|
||||
JOIN "targets" t ON thc."targetId" = t."targetId"
|
||||
JOIN "sites" s ON t."siteId" = s."siteId"`
|
||||
JOIN "sites" s ON t."siteId" = s."siteId"
|
||||
JOIN "resources" r ON t."resourceId" = r."resourceId"`
|
||||
);
|
||||
const existingHealthChecks = healthChecksQuery.rows as {
|
||||
targetHealthCheckId: number;
|
||||
targetId: number;
|
||||
siteId: number;
|
||||
orgId: string;
|
||||
resourceName: string;
|
||||
ip: string;
|
||||
port: number;
|
||||
hcEnabled: boolean;
|
||||
hcPath: string | null;
|
||||
hcScheme: string | null;
|
||||
@@ -385,6 +392,7 @@ export default async function migration() {
|
||||
"targetId",
|
||||
"orgId",
|
||||
"siteId",
|
||||
"name",
|
||||
"hcEnabled",
|
||||
"hcPath",
|
||||
"hcScheme",
|
||||
@@ -405,6 +413,7 @@ export default async function migration() {
|
||||
${hc.targetId},
|
||||
${hc.orgId},
|
||||
${hc.siteId},
|
||||
${`Resource ${hc.resourceName} - ${hc.ip}:${hc.port}`},
|
||||
${hc.hcEnabled},
|
||||
${hc.hcPath},
|
||||
${hc.hcScheme},
|
||||
@@ -545,6 +554,72 @@ export default async function migration() {
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Recompute resource health by aggregating across the resource's targets'
|
||||
// target health checks, then update the resources.health column to match.
|
||||
try {
|
||||
const resourceTargetHealthQuery = await db.execute(
|
||||
sql`SELECT
|
||||
r."resourceId" AS "resourceId",
|
||||
thc."hcHealth" AS "hcHealth"
|
||||
FROM "resources" r
|
||||
LEFT JOIN "targets" t ON t."resourceId" = r."resourceId"
|
||||
LEFT JOIN "targetHealthCheck" thc ON thc."targetId" = t."targetId"`
|
||||
);
|
||||
const resourceTargetHealthRows =
|
||||
resourceTargetHealthQuery.rows as {
|
||||
resourceId: number;
|
||||
hcHealth: string | null;
|
||||
}[];
|
||||
|
||||
const resourceHealthMap = new Map<
|
||||
number,
|
||||
{ hasHealthy: boolean; hasUnhealthy: boolean; hasUnknown: boolean }
|
||||
>();
|
||||
for (const row of resourceTargetHealthRows) {
|
||||
const entry = resourceHealthMap.get(row.resourceId) ?? {
|
||||
hasHealthy: false,
|
||||
hasUnhealthy: false,
|
||||
hasUnknown: false
|
||||
};
|
||||
const status = row.hcHealth ?? "unknown";
|
||||
if (status === "healthy") entry.hasHealthy = true;
|
||||
else if (status === "unhealthy") entry.hasUnhealthy = true;
|
||||
else entry.hasUnknown = true;
|
||||
resourceHealthMap.set(row.resourceId, entry);
|
||||
}
|
||||
|
||||
let updatedResourceCount = 0;
|
||||
for (const [resourceId, flags] of resourceHealthMap.entries()) {
|
||||
let aggregated: "healthy" | "unhealthy" | "degraded" | "unknown";
|
||||
if (flags.hasHealthy && flags.hasUnhealthy) {
|
||||
aggregated = "degraded";
|
||||
} else if (flags.hasHealthy) {
|
||||
aggregated = "healthy";
|
||||
} else if (flags.hasUnhealthy) {
|
||||
aggregated = "unhealthy";
|
||||
} else {
|
||||
aggregated = "unknown";
|
||||
}
|
||||
|
||||
await db.execute(sql`
|
||||
UPDATE "resources"
|
||||
SET "health" = ${aggregated}
|
||||
WHERE "resourceId" = ${resourceId}
|
||||
`);
|
||||
updatedResourceCount++;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Recomputed health for ${updatedResourceCount} resource(s) based on target health checks`
|
||||
);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"Error while recomputing resource health from target health checks:",
|
||||
e
|
||||
);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Seed statusHistory for all existing health checks
|
||||
try {
|
||||
const healthChecksQuery = await db.execute(
|
||||
|
||||
@@ -22,6 +22,9 @@ export default async function migration() {
|
||||
thc."targetId",
|
||||
t."siteId",
|
||||
s."orgId",
|
||||
r."name" AS "resourceName",
|
||||
t."ip",
|
||||
t."port",
|
||||
thc."hcEnabled",
|
||||
thc."hcPath",
|
||||
thc."hcScheme",
|
||||
@@ -39,13 +42,17 @@ export default async function migration() {
|
||||
thc."hcTlsServerName"
|
||||
FROM 'targetHealthCheck' thc
|
||||
JOIN 'targets' t ON thc."targetId" = t."targetId"
|
||||
JOIN 'sites' s ON t."siteId" = s."siteId"`
|
||||
JOIN 'sites' s ON t."siteId" = s."siteId"
|
||||
JOIN 'resources' r ON t."resourceId" = r."resourceId"`
|
||||
)
|
||||
.all() as {
|
||||
targetHealthCheckId: number;
|
||||
targetId: number;
|
||||
siteId: number;
|
||||
orgId: string;
|
||||
resourceName: string;
|
||||
ip: string;
|
||||
port: number;
|
||||
hcEnabled: number;
|
||||
hcPath: string | null;
|
||||
hcScheme: string | null;
|
||||
@@ -255,7 +262,7 @@ export default async function migration() {
|
||||
).run();
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO '__new_siteResources'("siteResourceId", "orgId", "networkId", "defaultNetworkId", "niceId", "name", "ssl", "mode", "scheme", "proxyPort", "destinationPort", "destination", "enabled", "alias", "aliasAddress", "tcpPortRangeString", "udpPortRangeString", "disableIcmp", "authDaemonPort", "authDaemonMode", "domainId", "subdomain", "fullDomain") SELECT "siteResourceId", "orgId", NULL, NULL, "niceId", "name", 0, "mode", NULL, "proxyPort", "destinationPort", "destination", "enabled", "alias", "aliasAddress", "tcpPortRangeString", "udpPortRangeString", "disableIcmp", "authDaemonPort", "authDaemonMode", NULL, NULL, NULL FROM 'siteResources';
|
||||
INSERT INTO '__new_siteResources'("siteResourceId", "orgId", "networkId", "defaultNetworkId", "niceId", "name", "ssl", "mode", "scheme", "proxyPort", "destinationPort", "destination", "enabled", "alias", "aliasAddress", "tcpPortRangeString", "udpPortRangeString", "disableIcmp", "authDaemonPort", "authDaemonMode", "domainId", "subdomain", "fullDomain") SELECT "siteResourceId", "orgId", NULL, NULL, "niceId", "name", 0, "mode", NULL, "proxyPort", "destinationPort", "destination", "enabled", "alias", "aliasAddress", COALESCE("tcpPortRangeString", '*'), COALESCE("udpPortRangeString", '*'), COALESCE("disableIcmp", 0), "authDaemonPort", "authDaemonMode", NULL, NULL, NULL FROM 'siteResources';
|
||||
`
|
||||
).run();
|
||||
db.prepare(
|
||||
@@ -392,6 +399,7 @@ export default async function migration() {
|
||||
"targetId",
|
||||
"orgId",
|
||||
"siteId",
|
||||
"name",
|
||||
"hcEnabled",
|
||||
"hcPath",
|
||||
"hcScheme",
|
||||
@@ -407,7 +415,7 @@ export default async function migration() {
|
||||
"hcStatus",
|
||||
"hcHealth",
|
||||
"hcTlsServerName"
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
|
||||
const insertAll = db.transaction(() => {
|
||||
@@ -417,6 +425,7 @@ export default async function migration() {
|
||||
hc.targetId,
|
||||
hc.orgId,
|
||||
hc.siteId,
|
||||
`Resource ${hc.resourceName} - ${hc.ip}:${hc.port}`,
|
||||
hc.hcEnabled,
|
||||
hc.hcPath,
|
||||
hc.hcScheme,
|
||||
@@ -509,6 +518,70 @@ export default async function migration() {
|
||||
`Seeded statusHistory for ${allResources.length} resource(s)`
|
||||
);
|
||||
|
||||
// Recompute resource health by aggregating across the resource's
|
||||
// targets' target health checks, then update resources.health.
|
||||
const resourceTargetHealthRows = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
r."resourceId" AS "resourceId",
|
||||
thc."hcHealth" AS "hcHealth"
|
||||
FROM 'resources' r
|
||||
LEFT JOIN 'targets' t ON t."resourceId" = r."resourceId"
|
||||
LEFT JOIN 'targetHealthCheck' thc ON thc."targetId" = t."targetId"`
|
||||
)
|
||||
.all() as {
|
||||
resourceId: number;
|
||||
hcHealth: string | null;
|
||||
}[];
|
||||
|
||||
const resourceHealthMap = new Map<
|
||||
number,
|
||||
{
|
||||
hasHealthy: boolean;
|
||||
hasUnhealthy: boolean;
|
||||
hasUnknown: boolean;
|
||||
}
|
||||
>();
|
||||
for (const row of resourceTargetHealthRows) {
|
||||
const entry = resourceHealthMap.get(row.resourceId) ?? {
|
||||
hasHealthy: false,
|
||||
hasUnhealthy: false,
|
||||
hasUnknown: false
|
||||
};
|
||||
const status = row.hcHealth ?? "unknown";
|
||||
if (status === "healthy") entry.hasHealthy = true;
|
||||
else if (status === "unhealthy") entry.hasUnhealthy = true;
|
||||
else entry.hasUnknown = true;
|
||||
resourceHealthMap.set(row.resourceId, entry);
|
||||
}
|
||||
|
||||
const updateResourceHealth = db.prepare(
|
||||
`UPDATE 'resources' SET "health" = ? WHERE "resourceId" = ?`
|
||||
);
|
||||
const recomputeResourceHealth = db.transaction(() => {
|
||||
for (const [resourceId, flags] of resourceHealthMap.entries()) {
|
||||
let aggregated:
|
||||
| "healthy"
|
||||
| "unhealthy"
|
||||
| "degraded"
|
||||
| "unknown";
|
||||
if (flags.hasHealthy && flags.hasUnhealthy) {
|
||||
aggregated = "degraded";
|
||||
} else if (flags.hasHealthy) {
|
||||
aggregated = "healthy";
|
||||
} else if (flags.hasUnhealthy) {
|
||||
aggregated = "unhealthy";
|
||||
} else {
|
||||
aggregated = "unknown";
|
||||
}
|
||||
updateResourceHealth.run(aggregated, resourceId);
|
||||
}
|
||||
});
|
||||
recomputeResourceHealth();
|
||||
console.log(
|
||||
`Recomputed health for ${resourceHealthMap.size} resource(s) based on target health checks`
|
||||
);
|
||||
|
||||
// Seed statusHistory for all existing health checks
|
||||
const allHealthChecks = db
|
||||
.prepare(
|
||||
|
||||
@@ -96,6 +96,9 @@ export default async function ClientsPage(props: ClientsPageProps) {
|
||||
userId: client.userId,
|
||||
username: client.username,
|
||||
userEmail: client.userEmail,
|
||||
userType: client.userType ?? null,
|
||||
idpName: client.idpName ?? null,
|
||||
idpVariant: client.idpVariant ?? null,
|
||||
niceId: client.niceId,
|
||||
agent: client.agent,
|
||||
archived: Boolean(client.archived),
|
||||
|
||||
@@ -120,6 +120,7 @@ export default async function ProxyResourcesPage(
|
||||
: "not_protected",
|
||||
enabled: resource.enabled,
|
||||
domainId: resource.domainId || undefined,
|
||||
fullDomain: resource.fullDomain ?? null,
|
||||
ssl: resource.ssl,
|
||||
targets: resource.targets?.map((target) => ({
|
||||
targetId: target.targetId,
|
||||
|
||||
@@ -23,7 +23,7 @@ import { TanstackQueryProvider } from "@app/components/TanstackQueryProvider";
|
||||
import { TailwindIndicator } from "@app/components/TailwindIndicator";
|
||||
import { ViewportHeightFix } from "@app/components/ViewportHeightFix";
|
||||
import StoreInternalRedirect from "@app/components/StoreInternalRedirect";
|
||||
import { Inter, Mona_Sans } from "next/font/google";
|
||||
import localFont from "next/font/local";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: `Dashboard - ${process.env.BRANDING_APP_NAME || "Pangolin"}`,
|
||||
@@ -32,12 +32,30 @@ export const metadata: Metadata = {
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const inter = Inter({
|
||||
subsets: ["latin"]
|
||||
});
|
||||
|
||||
const monaSans = Mona_Sans({
|
||||
subsets: ["latin"]
|
||||
const monaSans = localFont({
|
||||
src: [
|
||||
{
|
||||
path: "../fonts/mona-sans/MonaSans-Regular.woff2",
|
||||
weight: "400",
|
||||
style: "normal"
|
||||
},
|
||||
{
|
||||
path: "../fonts/mona-sans/MonaSans-Medium.woff2",
|
||||
weight: "500",
|
||||
style: "normal"
|
||||
},
|
||||
{
|
||||
path: "../fonts/mona-sans/MonaSans-SemiBold.woff2",
|
||||
weight: "600",
|
||||
style: "normal"
|
||||
},
|
||||
{
|
||||
path: "../fonts/mona-sans/MonaSans-Bold.woff2",
|
||||
weight: "700",
|
||||
style: "normal"
|
||||
}
|
||||
],
|
||||
display: "swap"
|
||||
});
|
||||
|
||||
const fontClassName = monaSans.className;
|
||||
|
||||
@@ -399,11 +399,10 @@ function AuthPageSettings({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{env.flags.usePangolinDns &&
|
||||
(build === "enterprise" ||
|
||||
!isPaidUser(
|
||||
tierMatrix.loginPageDomain
|
||||
)) &&
|
||||
{build !== "oss" && (build === "enterprise" ||
|
||||
!isPaidUser(
|
||||
tierMatrix.loginPageDomain
|
||||
)) &&
|
||||
loginPage?.domainId &&
|
||||
loginPage?.fullDomain &&
|
||||
!hasUnsavedChanges && (
|
||||
|
||||
@@ -1,43 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Loader2, RotateCw } from "lucide-react";
|
||||
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";
|
||||
|
||||
type CertificateStatusProps = {
|
||||
orgId: string;
|
||||
domainId: string;
|
||||
fullDomain: string;
|
||||
autoFetch?: boolean;
|
||||
export type CertificateStatusContentProps = {
|
||||
cert: GetCertificateResponse | null;
|
||||
certLoading: boolean;
|
||||
certError: string | null;
|
||||
refreshing: boolean;
|
||||
refreshCert: () => Promise<void>;
|
||||
showLabel?: boolean;
|
||||
className?: string;
|
||||
onRefresh?: () => void;
|
||||
polling?: boolean;
|
||||
pollingInterval?: number;
|
||||
};
|
||||
|
||||
export default function CertificateStatus({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain,
|
||||
autoFetch = true,
|
||||
/** Presentation-only certificate row (shared hook state possible via props). */
|
||||
export function CertificateStatusContent({
|
||||
cert,
|
||||
certLoading,
|
||||
certError,
|
||||
refreshing,
|
||||
refreshCert,
|
||||
showLabel = true,
|
||||
className = "",
|
||||
onRefresh,
|
||||
polling = false,
|
||||
pollingInterval = 5000
|
||||
}: CertificateStatusProps) {
|
||||
onRefresh
|
||||
}: CertificateStatusContentProps) {
|
||||
const t = useTranslations();
|
||||
const { cert, certLoading, certError, refreshing, refreshCert } =
|
||||
useCertificate({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain,
|
||||
autoFetch,
|
||||
polling,
|
||||
pollingInterval
|
||||
});
|
||||
|
||||
const labelClass =
|
||||
"inline-flex shrink-0 items-center self-center text-sm font-medium leading-none";
|
||||
const valueClass = "inline-flex items-center gap-2 text-sm leading-none";
|
||||
|
||||
const handleRefresh = async () => {
|
||||
await refreshCert();
|
||||
@@ -74,13 +69,13 @@ export default function CertificateStatus({
|
||||
return (
|
||||
<div className={`flex items-center gap-2 ${className}`}>
|
||||
{showLabel && (
|
||||
<span className="text-sm font-medium">
|
||||
<span className={labelClass}>
|
||||
{t("certificateStatus")}:
|
||||
</span>
|
||||
)}
|
||||
<span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<Loader2
|
||||
className="h-3.5 w-3.5 shrink-0 animate-spin"
|
||||
<span className={valueClass}>
|
||||
<FileBadge
|
||||
className="h-4 w-4 shrink-0 animate-pulse text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
{t("loading")}
|
||||
@@ -93,11 +88,17 @@ export default function CertificateStatus({
|
||||
return (
|
||||
<div className={`flex items-center gap-2 ${className}`}>
|
||||
{showLabel && (
|
||||
<span className="text-sm font-medium">
|
||||
<span className={labelClass}>
|
||||
{t("certificateStatus")}:
|
||||
</span>
|
||||
)}
|
||||
<span className="text-sm text-red-500">{certError}</span>
|
||||
<span className={valueClass}>
|
||||
<FileBadge
|
||||
className="h-4 w-4 shrink-0 text-red-500"
|
||||
aria-hidden
|
||||
/>
|
||||
{certError}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -106,11 +107,15 @@ export default function CertificateStatus({
|
||||
return (
|
||||
<div className={`flex items-center gap-2 ${className}`}>
|
||||
{showLabel && (
|
||||
<span className="text-sm font-medium">
|
||||
<span className={labelClass}>
|
||||
{t("certificateStatus")}:
|
||||
</span>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground">
|
||||
<span className={valueClass}>
|
||||
<FileBadge
|
||||
className="h-4 w-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
{t("none", { defaultValue: "None" })}
|
||||
</span>
|
||||
</div>
|
||||
@@ -123,50 +128,102 @@ export default function CertificateStatus({
|
||||
return (
|
||||
<div className={`flex items-center gap-2 ${className}`}>
|
||||
{showLabel && (
|
||||
<span className="text-sm font-medium">
|
||||
{t("certificateStatus")}:
|
||||
</span>
|
||||
<span className={labelClass}>{t("certificateStatus")}:</span>
|
||||
)}
|
||||
{isPending ? (
|
||||
{isPending && !disableRestartButton ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={`h-auto p-0 text-sm ${getStatusColor(cert.status)}`}
|
||||
className="h-auto min-h-0 shrink-0 p-0 text-sm font-normal leading-none inline-flex items-center self-center"
|
||||
onClick={handleRefresh}
|
||||
disabled={refreshing || disableRestartButton}
|
||||
disabled={refreshing}
|
||||
title={t("restartCertificate", {
|
||||
defaultValue: "Restart Certificate"
|
||||
})}
|
||||
>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{cert.status.charAt(0).toUpperCase() + cert.status.slice(1)}
|
||||
<span className="inline-flex items-center gap-2 leading-none">
|
||||
<FileBadge
|
||||
className={`h-4 w-4 shrink-0 ${getStatusColor(cert.status)}`}
|
||||
aria-hidden
|
||||
/>
|
||||
{cert.status.charAt(0).toUpperCase() +
|
||||
cert.status.slice(1)}
|
||||
<RotateCw
|
||||
className={`h-3 w-3 ${refreshing ? "animate-spin" : ""}`}
|
||||
className={`h-3 w-3 shrink-0 ${refreshing ? "animate-spin" : ""}`}
|
||||
/>
|
||||
</span>
|
||||
</Button>
|
||||
) : (
|
||||
<span className={`text-sm ${getStatusColor(cert.status)}`}>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{cert.status.charAt(0).toUpperCase() + cert.status.slice(1)}
|
||||
{shouldShowRefreshButton(cert.status, cert.updatedAt) && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="p-0 w-3 h-auto align-middle"
|
||||
onClick={handleRefresh}
|
||||
disabled={refreshing || disableRestartButton}
|
||||
title={t("restartCertificate", {
|
||||
defaultValue: "Restart Certificate"
|
||||
})}
|
||||
>
|
||||
<RotateCw
|
||||
className={`w-3 h-3 ${refreshing ? "animate-spin" : ""}`}
|
||||
/>
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
<span className={valueClass}>
|
||||
<FileBadge
|
||||
className={`h-4 w-4 shrink-0 ${getStatusColor(cert.status)}`}
|
||||
aria-hidden
|
||||
/>
|
||||
{cert.status.charAt(0).toUpperCase() + cert.status.slice(1)}
|
||||
{shouldShowRefreshButton(cert.status, cert.updatedAt) &&
|
||||
!disableRestartButton ? (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="inline-flex h-auto min-h-0 w-3 shrink-0 items-center justify-center self-center p-0"
|
||||
onClick={handleRefresh}
|
||||
disabled={refreshing}
|
||||
title={t("restartCertificate", {
|
||||
defaultValue: "Restart Certificate"
|
||||
})}
|
||||
>
|
||||
<RotateCw
|
||||
className={`h-3 w-3 shrink-0 ${refreshing ? "animate-spin" : ""}`}
|
||||
/>
|
||||
</Button>
|
||||
) : null}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type CertificateStatusProps = {
|
||||
orgId: string;
|
||||
domainId: string;
|
||||
fullDomain: string;
|
||||
autoFetch?: boolean;
|
||||
showLabel?: boolean;
|
||||
className?: string;
|
||||
onRefresh?: () => void;
|
||||
polling?: boolean;
|
||||
pollingInterval?: number;
|
||||
};
|
||||
|
||||
export default function CertificateStatus({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain,
|
||||
autoFetch = true,
|
||||
showLabel = true,
|
||||
className = "",
|
||||
onRefresh,
|
||||
polling = false,
|
||||
pollingInterval = 5000
|
||||
}: CertificateStatusProps) {
|
||||
const hook = useCertificate({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain,
|
||||
autoFetch,
|
||||
polling,
|
||||
pollingInterval
|
||||
});
|
||||
|
||||
return (
|
||||
<CertificateStatusContent
|
||||
cert={hook.cert}
|
||||
certLoading={hook.certLoading}
|
||||
certError={hook.certError}
|
||||
refreshing={hook.refreshing}
|
||||
refreshCert={hook.refreshCert}
|
||||
showLabel={showLabel}
|
||||
className={className}
|
||||
onRefresh={onRefresh}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
InfoSections,
|
||||
InfoSectionTitle
|
||||
} from "@app/components/InfoSection";
|
||||
import IdpTypeBadge from "@app/components/IdpTypeBadge";
|
||||
import { getUserDisplayName } from "@app/lib/getUserDisplayName";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
@@ -36,7 +37,24 @@ export default function SiteInfoCard({}: ClientInfoCardProps) {
|
||||
{userDisplayName ? t("user") : t("identifier")}
|
||||
</InfoSectionTitle>
|
||||
<InfoSectionContent>
|
||||
{userDisplayName || client.niceId}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span>{userDisplayName || client.niceId}</span>
|
||||
{userDisplayName &&
|
||||
(client.userType ?? "internal") !==
|
||||
"internal" && (
|
||||
<IdpTypeBadge
|
||||
type={client.userType ?? "oidc"}
|
||||
name={
|
||||
client.idpName?.trim()
|
||||
? client.idpName
|
||||
: t("idpNameInternal")
|
||||
}
|
||||
variant={
|
||||
client.idpVariant ?? undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</InfoSectionContent>
|
||||
</InfoSection>
|
||||
<InfoSection>
|
||||
|
||||
@@ -37,11 +37,8 @@ import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Selectedsite, SitesSelector } from "@app/components/site-selector";
|
||||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||
|
||||
import CreateInternalResourceDialog from "@app/components/CreateInternalResourceDialog";
|
||||
import EditInternalResourceDialog from "@app/components/EditInternalResourceDialog";
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { PaginationState } from "@tanstack/react-table";
|
||||
import { ControlledDataTable } from "./ui/controlled-data-table";
|
||||
import { useNavigationContext } from "@app/hooks/useNavigationContext";
|
||||
@@ -54,6 +51,8 @@ import {
|
||||
ResourceSitesStatusCell,
|
||||
type ResourceSiteRow
|
||||
} from "@app/components/ResourceSitesStatusCell";
|
||||
import { ResourceAccessCertIndicator } from "@app/components/ResourceAccessCertIndicator";
|
||||
import { build } from "@server/build";
|
||||
|
||||
export type InternalResourceSiteRow = ResourceSiteRow;
|
||||
|
||||
@@ -206,7 +205,11 @@ export default function ClientResourcesTable({
|
||||
const { siteNames, siteNiceIds, orgId } = resourceRow;
|
||||
|
||||
if (!siteNames || siteNames.length === 0) {
|
||||
return <span>-</span>;
|
||||
return (
|
||||
<span className="text-muted-foreground">
|
||||
{t("noSites", { defaultValue: "No sites" })}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (siteNames.length === 1) {
|
||||
@@ -439,13 +442,34 @@ export default function ClientResourcesTable({
|
||||
);
|
||||
}
|
||||
if (resourceRow.mode === "http") {
|
||||
const url = `${resourceRow.ssl ? "https" : "http"}://${resourceRow.fullDomain}`;
|
||||
const domainId = resourceRow.domainId;
|
||||
const fullDomain = resourceRow.fullDomain;
|
||||
const url = `${resourceRow.ssl ? "https" : "http"}://${fullDomain}`;
|
||||
const did =
|
||||
build !== "oss" &&
|
||||
resourceRow.ssl &&
|
||||
domainId != null &&
|
||||
domainId !== "" &&
|
||||
fullDomain != null &&
|
||||
fullDomain !== "";
|
||||
|
||||
return (
|
||||
<CopyToClipboard
|
||||
text={url}
|
||||
isLink={isSafeUrlForLink(url)}
|
||||
displayText={url}
|
||||
/>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{did ? (
|
||||
<ResourceAccessCertIndicator
|
||||
orgId={resourceRow.orgId}
|
||||
domainId={domainId}
|
||||
fullDomain={fullDomain}
|
||||
/>
|
||||
) : null}
|
||||
<div className="">
|
||||
<CopyToClipboard
|
||||
text={url}
|
||||
isLink={isSafeUrlForLink(url)}
|
||||
displayText={url}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <span>-</span>;
|
||||
|
||||
@@ -485,6 +485,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
|
||||
onSelectSite={(site) => {
|
||||
setSelectedSite(site);
|
||||
}}
|
||||
filterTypes={["newt"]}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
@@ -55,6 +55,7 @@ import { MachinesSelector } from "./machines-selector";
|
||||
import DomainPicker from "@app/components/DomainPicker";
|
||||
import { SwitchInput } from "@app/components/SwitchInput";
|
||||
import CertificateStatus from "@app/components/CertificateStatus";
|
||||
import { build } from "@server/build";
|
||||
|
||||
// --- Helpers (shared) ---
|
||||
|
||||
@@ -156,7 +157,7 @@ export type InternalResourceData = {
|
||||
const tagSchema = z.object({ id: z.string(), text: z.string() });
|
||||
|
||||
function buildSelectedSitesForResource(
|
||||
resource: InternalResourceData,
|
||||
resource: InternalResourceData
|
||||
): Selectedsite[] {
|
||||
return resource.siteIds.map((siteId, idx) => ({
|
||||
name: resource.siteNames[idx] ?? "",
|
||||
@@ -609,9 +610,7 @@ export function InternalResourceForm({
|
||||
users: [],
|
||||
clients: []
|
||||
});
|
||||
setSelectedSites(
|
||||
buildSelectedSitesForResource(resource)
|
||||
);
|
||||
setSelectedSites(buildSelectedSitesForResource(resource));
|
||||
setTcpPortMode(
|
||||
getPortModeFromString(resource.tcpPortRangeString)
|
||||
);
|
||||
@@ -800,7 +799,9 @@ export function InternalResourceForm({
|
||||
);
|
||||
field.onChange(
|
||||
sites.map(
|
||||
(s) =>
|
||||
(
|
||||
s
|
||||
) =>
|
||||
s.siteId
|
||||
)
|
||||
);
|
||||
@@ -822,15 +823,21 @@ export function InternalResourceForm({
|
||||
[
|
||||
{
|
||||
value: "host",
|
||||
label: t(modeHostKey)
|
||||
label: t(
|
||||
modeHostKey
|
||||
)
|
||||
},
|
||||
{
|
||||
value: "cidr",
|
||||
label: t(modeCidrKey)
|
||||
label: t(
|
||||
modeCidrKey
|
||||
)
|
||||
},
|
||||
{
|
||||
value: "http",
|
||||
label: t(modeHttpKey)
|
||||
label: t(
|
||||
modeHttpKey
|
||||
)
|
||||
}
|
||||
];
|
||||
return (
|
||||
@@ -839,7 +846,9 @@ export function InternalResourceForm({
|
||||
{t(modeLabelKey)}
|
||||
</FormLabel>
|
||||
<OptionSelect<InternalResourceMode>
|
||||
options={modeOptions}
|
||||
options={
|
||||
modeOptions
|
||||
}
|
||||
value={field.value}
|
||||
onChange={
|
||||
field.onChange
|
||||
@@ -899,7 +908,9 @@ export function InternalResourceForm({
|
||||
field.value ??
|
||||
"http"
|
||||
}
|
||||
disabled={httpSectionDisabled}
|
||||
disabled={
|
||||
httpSectionDisabled
|
||||
}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger className="w-full">
|
||||
@@ -940,7 +951,10 @@ export function InternalResourceForm({
|
||||
<Input
|
||||
{...field}
|
||||
className="w-full"
|
||||
disabled={isHttpMode && httpSectionDisabled}
|
||||
disabled={
|
||||
isHttpMode &&
|
||||
httpSectionDisabled
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -996,7 +1010,9 @@ export function InternalResourceForm({
|
||||
field.value ??
|
||||
""
|
||||
}
|
||||
disabled={httpSectionDisabled}
|
||||
disabled={
|
||||
httpSectionDisabled
|
||||
}
|
||||
onChange={(e) => {
|
||||
const raw =
|
||||
e.target
|
||||
@@ -1031,7 +1047,9 @@ export function InternalResourceForm({
|
||||
</div>
|
||||
|
||||
{isHttpMode && (
|
||||
<PaidFeaturesAlert tiers={tierMatrix.httpPrivateResources} />
|
||||
<PaidFeaturesAlert
|
||||
tiers={tierMatrix.httpPrivateResources}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isHttpMode ? (
|
||||
@@ -1044,55 +1062,61 @@ export function InternalResourceForm({
|
||||
{t(httpConfigurationDescriptionKey)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={httpSectionDisabled ? "pointer-events-none opacity-50" : undefined}>
|
||||
<DomainPicker
|
||||
key={
|
||||
variant === "edit" && siteResourceId
|
||||
? `http-domain-${siteResourceId}`
|
||||
: "http-domain-create"
|
||||
<div
|
||||
className={
|
||||
httpSectionDisabled
|
||||
? "pointer-events-none opacity-50"
|
||||
: undefined
|
||||
}
|
||||
orgId={orgId}
|
||||
cols={2}
|
||||
hideFreeDomain
|
||||
defaultSubdomain={
|
||||
httpConfigSubdomain ?? undefined
|
||||
}
|
||||
defaultDomainId={
|
||||
httpConfigDomainId ?? undefined
|
||||
}
|
||||
defaultFullDomain={
|
||||
httpConfigFullDomain ?? undefined
|
||||
}
|
||||
onDomainChange={(res) => {
|
||||
if (res === null) {
|
||||
>
|
||||
<DomainPicker
|
||||
key={
|
||||
variant === "edit" && siteResourceId
|
||||
? `http-domain-${siteResourceId}`
|
||||
: "http-domain-create"
|
||||
}
|
||||
orgId={orgId}
|
||||
cols={2}
|
||||
hideFreeDomain
|
||||
defaultSubdomain={
|
||||
httpConfigSubdomain ?? undefined
|
||||
}
|
||||
defaultDomainId={
|
||||
httpConfigDomainId ?? undefined
|
||||
}
|
||||
defaultFullDomain={
|
||||
httpConfigFullDomain ?? undefined
|
||||
}
|
||||
onDomainChange={(res) => {
|
||||
if (res === null) {
|
||||
form.setValue(
|
||||
"httpConfigSubdomain",
|
||||
null
|
||||
);
|
||||
form.setValue(
|
||||
"httpConfigDomainId",
|
||||
null
|
||||
);
|
||||
form.setValue(
|
||||
"httpConfigFullDomain",
|
||||
null
|
||||
);
|
||||
return;
|
||||
}
|
||||
form.setValue(
|
||||
"httpConfigSubdomain",
|
||||
null
|
||||
res.subdomain ?? null
|
||||
);
|
||||
form.setValue(
|
||||
"httpConfigDomainId",
|
||||
null
|
||||
res.domainId
|
||||
);
|
||||
form.setValue(
|
||||
"httpConfigFullDomain",
|
||||
null
|
||||
res.fullDomain
|
||||
);
|
||||
return;
|
||||
}
|
||||
form.setValue(
|
||||
"httpConfigSubdomain",
|
||||
res.subdomain ?? null
|
||||
);
|
||||
form.setValue(
|
||||
"httpConfigDomainId",
|
||||
res.domainId
|
||||
);
|
||||
form.setValue(
|
||||
"httpConfigFullDomain",
|
||||
res.fullDomain
|
||||
);
|
||||
}}
|
||||
/>
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<FormField
|
||||
@@ -1103,7 +1127,9 @@ export function InternalResourceForm({
|
||||
<FormControl>
|
||||
<SwitchInput
|
||||
id="internal-resource-ssl"
|
||||
label={t(enableSslLabelKey)}
|
||||
label={t(
|
||||
enableSslLabelKey
|
||||
)}
|
||||
description={t(
|
||||
enableSslDescriptionKey
|
||||
)}
|
||||
@@ -1111,7 +1137,9 @@ export function InternalResourceForm({
|
||||
onCheckedChange={
|
||||
field.onChange
|
||||
}
|
||||
disabled={httpSectionDisabled}
|
||||
disabled={
|
||||
httpSectionDisabled
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
@@ -1120,15 +1148,22 @@ export function InternalResourceForm({
|
||||
{variant === "edit" &&
|
||||
resource?.domainId &&
|
||||
httpConfigFullDomain &&
|
||||
httpConfigDomainId ===
|
||||
resource.domainId &&
|
||||
httpConfigFullDomain ===
|
||||
resource.fullDomain &&
|
||||
build != "oss" &&
|
||||
form.watch("ssl") && (
|
||||
<div className="flex items-center gap-1 pt-1">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<span className="text-sm font-medium">
|
||||
{t("certificateStatus")}:
|
||||
</span>
|
||||
<CertificateStatus
|
||||
orgId={resource.orgId}
|
||||
domainId={resource.domainId}
|
||||
fullDomain={httpConfigFullDomain}
|
||||
fullDomain={
|
||||
httpConfigFullDomain
|
||||
}
|
||||
autoFetch={true}
|
||||
showLabel={false}
|
||||
polling={true}
|
||||
|
||||
@@ -64,6 +64,8 @@ import z from "zod";
|
||||
import { ColumnFilterButton } from "./ColumnFilterButton";
|
||||
import { ControlledDataTable } from "./ui/controlled-data-table";
|
||||
import UptimeMiniBar from "./UptimeMiniBar";
|
||||
import { ResourceAccessCertIndicator } from "@app/components/ResourceAccessCertIndicator";
|
||||
import { build } from "@server/build";
|
||||
|
||||
export type TargetHealth = {
|
||||
targetId: number;
|
||||
@@ -86,6 +88,8 @@ export type ResourceRow = {
|
||||
proxyPort: number | null;
|
||||
enabled: boolean;
|
||||
domainId?: string;
|
||||
/** Hostname for certificate API (without scheme); distinct from `domain` URL shown in Access column */
|
||||
fullDomain?: string | null;
|
||||
ssl: boolean;
|
||||
targetHost?: string;
|
||||
targetPort?: number;
|
||||
@@ -266,7 +270,7 @@ export default function ProxyResourcesTable({
|
||||
<StatusIcon status={overallStatus} />
|
||||
<span className="text-sm">
|
||||
{overallStatus === "healthy" &&
|
||||
t("resourcesTableHealthy")}
|
||||
t("resourcesTableHealthy")}
|
||||
{overallStatus === "degraded" &&
|
||||
t("resourcesTableDegraded")}
|
||||
{overallStatus === "unhealthy" &&
|
||||
@@ -488,7 +492,12 @@ export default function ProxyResourcesTable({
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const resourceRow = row.original;
|
||||
return <TargetStatusCell targets={resourceRow.targets} healthStatus={resourceRow.health} />;
|
||||
return (
|
||||
<TargetStatusCell
|
||||
targets={resourceRow.targets}
|
||||
healthStatus={resourceRow.health}
|
||||
/>
|
||||
);
|
||||
},
|
||||
sortingFn: (rowA, rowB) => {
|
||||
const statusA = rowA.original.health;
|
||||
@@ -520,24 +529,52 @@ export default function ProxyResourcesTable({
|
||||
header: () => <span className="p-3">{t("access")}</span>,
|
||||
cell: ({ row }) => {
|
||||
const resourceRow = row.original;
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
{!resourceRow.http ? (
|
||||
|
||||
if (!resourceRow.http) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<CopyToClipboard
|
||||
text={resourceRow.proxyPort?.toString() || ""}
|
||||
isLink={false}
|
||||
/>
|
||||
) : !resourceRow.domainId ? (
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!resourceRow.domainId) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<InfoPopup
|
||||
info={t("domainNotFoundDescription")}
|
||||
text={t("domainNotFound")}
|
||||
/>
|
||||
) : (
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const domainId = resourceRow.domainId;
|
||||
const certHostname = resourceRow.fullDomain;
|
||||
const showHttpsCertIndicator =
|
||||
build !== "oss" &&
|
||||
resourceRow.ssl &&
|
||||
certHostname != null &&
|
||||
certHostname !== "";
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{showHttpsCertIndicator ? (
|
||||
<ResourceAccessCertIndicator
|
||||
orgId={resourceRow.orgId}
|
||||
domainId={domainId}
|
||||
fullDomain={certHostname}
|
||||
/>
|
||||
) : null}
|
||||
<div className="">
|
||||
<CopyToClipboard
|
||||
text={resourceRow.domain}
|
||||
isLink={true}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
179
src/components/ResourceAccessCertIndicator.tsx
Normal file
179
src/components/ResourceAccessCertIndicator.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
"use client";
|
||||
|
||||
import { CertificateStatusContent } from "@app/components/CertificateStatus";
|
||||
import {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent
|
||||
} from "@app/components/ui/popover";
|
||||
import { useCertificate } from "@app/hooks/useCertificate";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { FileBadge } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode
|
||||
} from "react";
|
||||
|
||||
type ResourceAccessCertIndicatorProps = {
|
||||
orgId: string;
|
||||
domainId: string;
|
||||
fullDomain: string;
|
||||
};
|
||||
|
||||
function getStatusColor(status: string) {
|
||||
switch (status) {
|
||||
case "valid":
|
||||
return "text-green-500";
|
||||
case "pending":
|
||||
case "requested":
|
||||
return "text-yellow-500";
|
||||
case "expired":
|
||||
case "failed":
|
||||
return "text-red-500";
|
||||
default:
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
}
|
||||
|
||||
/** Compact cert icon + hover popover with full certificate status (shared by proxy and client resource tables). */
|
||||
export function ResourceAccessCertIndicator({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain
|
||||
}: ResourceAccessCertIndicatorProps) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const certificate = useCertificate({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain,
|
||||
autoFetch: true,
|
||||
polling: open,
|
||||
pollingInterval: 5000
|
||||
});
|
||||
|
||||
const { cert, certLoading, certError, refreshing, fetchCert } = certificate;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
void fetchCert(false);
|
||||
}, [open, fetchCert]);
|
||||
|
||||
const clearCloseTimer = useCallback(() => {
|
||||
if (closeTimerRef.current != null) {
|
||||
clearTimeout(closeTimerRef.current);
|
||||
closeTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const scheduleClose = useCallback(() => {
|
||||
clearCloseTimer();
|
||||
closeTimerRef.current = setTimeout(() => setOpen(false), 280);
|
||||
}, [clearCloseTimer]);
|
||||
|
||||
const handleEnterOpen = useCallback(() => {
|
||||
clearCloseTimer();
|
||||
setOpen(true);
|
||||
}, [clearCloseTimer]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => clearCloseTimer();
|
||||
}, [clearCloseTimer]);
|
||||
|
||||
let triggerBody: ReactNode;
|
||||
if (certLoading) {
|
||||
triggerBody = (
|
||||
<div
|
||||
className={cn(
|
||||
"h-4 w-4 shrink-0 rounded-[2px] animate-pulse",
|
||||
"bg-neutral-200 dark:bg-neutral-700"
|
||||
)}
|
||||
aria-busy="true"
|
||||
aria-label={t("loading")}
|
||||
/>
|
||||
);
|
||||
} else if (refreshing) {
|
||||
triggerBody = (
|
||||
<FileBadge
|
||||
className={cn(
|
||||
"h-4 w-4 shrink-0 animate-spin",
|
||||
cert ? getStatusColor(cert.status) : "text-muted-foreground"
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
);
|
||||
} else if (certError) {
|
||||
triggerBody = (
|
||||
<FileBadge className="h-4 w-4 shrink-0 text-red-500" aria-hidden />
|
||||
);
|
||||
} else if (cert) {
|
||||
triggerBody = (
|
||||
<FileBadge
|
||||
className={cn("h-4 w-4", getStatusColor(cert.status))}
|
||||
aria-hidden
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
triggerBody = (
|
||||
<FileBadge
|
||||
className="h-4 w-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverAnchor asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center shrink-0 rounded-[2px] outline-offset-2",
|
||||
"focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",
|
||||
certError && "text-red-500"
|
||||
)}
|
||||
onMouseEnter={handleEnterOpen}
|
||||
onMouseLeave={scheduleClose}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setOpen((v) => !v);
|
||||
}}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="dialog"
|
||||
aria-label={t("certificateStatus")}
|
||||
>
|
||||
{triggerBody}
|
||||
</button>
|
||||
</PopoverAnchor>
|
||||
<PopoverContent
|
||||
className="w-72 p-4"
|
||||
align="start"
|
||||
side="bottom"
|
||||
sideOffset={6}
|
||||
onMouseEnter={clearCloseTimer}
|
||||
onMouseLeave={scheduleClose}
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<CertificateStatusContent
|
||||
cert={certificate.cert}
|
||||
certLoading={certificate.certLoading}
|
||||
certError={certificate.certError}
|
||||
refreshing={certificate.refreshing}
|
||||
refreshCert={certificate.refreshCert}
|
||||
showLabel
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("certificateStatusAutoRefreshHint")}
|
||||
</p>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { ShieldCheck, ShieldOff, Eye, EyeOff, CheckCircle2, XCircle, Clock } from "lucide-react";
|
||||
import {
|
||||
ShieldCheck,
|
||||
ShieldOff,
|
||||
Eye,
|
||||
EyeOff,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Clock
|
||||
} from "lucide-react";
|
||||
import { useResourceContext } from "@app/hooks/useResourceContext";
|
||||
import CopyToClipboard from "@app/components/CopyToClipboard";
|
||||
import {
|
||||
@@ -13,7 +21,7 @@ import {
|
||||
import { useTranslations } from "next-intl";
|
||||
import CertificateStatus from "@app/components/CertificateStatus";
|
||||
import { toUnicode } from "punycode";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { build } from "@server/build";
|
||||
|
||||
type ResourceInfoBoxType = {};
|
||||
|
||||
@@ -28,7 +36,7 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
{/* 4 cols because of the certs */}
|
||||
<InfoSections cols={resource.http ? 6 : 5}>
|
||||
<InfoSections cols={resource.http && build != "oss" ? 6 : 5}>
|
||||
<InfoSection>
|
||||
<InfoSectionTitle>{t("identifier")}</InfoSectionTitle>
|
||||
<InfoSectionContent>
|
||||
@@ -61,12 +69,12 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
|
||||
authInfo.whitelist ||
|
||||
authInfo.headerAuth ? (
|
||||
<div className="flex items-start space-x-2">
|
||||
<ShieldCheck className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-500" />
|
||||
<ShieldCheck className="w-4 h-4 flex-shrink-0 text-green-500" />
|
||||
<span>{t("protected")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center space-x-2 text-yellow-500">
|
||||
<ShieldOff className="w-4 h-4 flex-shrink-0" />
|
||||
<div className="flex items-center space-x-2">
|
||||
<ShieldOff className="w-4 h-4 flex-shrink-0 text-yellow-500" />
|
||||
<span>{t("notProtected")}</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -137,7 +145,8 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
|
||||
{/* Certificate Status Column */}
|
||||
{resource.http &&
|
||||
resource.domainId &&
|
||||
resource.fullDomain && (
|
||||
resource.fullDomain &&
|
||||
build != "oss" && (
|
||||
<InfoSection>
|
||||
<InfoSectionTitle>
|
||||
{t("certificateStatus", {
|
||||
@@ -177,8 +186,9 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
|
||||
<span>{t("resourcesTableUnhealthy")}</span>
|
||||
</div>
|
||||
)}
|
||||
{(!resource.health || resource.health === "unknown") && (
|
||||
<div className="flex items-center space-x-2 text-muted-foreground">
|
||||
{(!resource.health ||
|
||||
resource.health === "unknown") && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Clock className="w-4 h-4 flex-shrink-0" />
|
||||
<span>{t("resourcesTableUnknown")}</span>
|
||||
</div>
|
||||
|
||||
@@ -16,10 +16,10 @@ export type ResourceSiteRow = {
|
||||
siteId: number;
|
||||
siteName: string;
|
||||
siteNiceId: string;
|
||||
online: boolean;
|
||||
online?: boolean | null;
|
||||
};
|
||||
|
||||
type AggregateSitesStatus = "allOnline" | "partial" | "allOffline";
|
||||
type AggregateSitesStatus = "allOnline" | "partial" | "allOffline" | "unknown";
|
||||
|
||||
function aggregateSitesStatus(
|
||||
resourceSites: ResourceSiteRow[]
|
||||
@@ -27,8 +27,17 @@ function aggregateSitesStatus(
|
||||
if (resourceSites.length === 0) {
|
||||
return "allOffline";
|
||||
}
|
||||
const onlineCount = resourceSites.filter((rs) => rs.online).length;
|
||||
if (onlineCount === resourceSites.length) return "allOnline";
|
||||
|
||||
const knownStatuses = resourceSites
|
||||
.map((rs) => rs.online)
|
||||
.filter((status): status is boolean => typeof status === "boolean");
|
||||
|
||||
if (knownStatuses.length === 0) {
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const onlineCount = knownStatuses.filter(Boolean).length;
|
||||
if (onlineCount === knownStatuses.length) return "allOnline";
|
||||
if (onlineCount > 0) return "partial";
|
||||
return "allOffline";
|
||||
}
|
||||
@@ -40,8 +49,10 @@ function aggregateStatusDotClass(status: AggregateSitesStatus): string {
|
||||
case "partial":
|
||||
return "bg-yellow-500";
|
||||
case "allOffline":
|
||||
default:
|
||||
return "bg-neutral-500";
|
||||
case "unknown":
|
||||
default:
|
||||
return "border border-muted-foreground/50 bg-transparent";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +95,7 @@ export function ResourceSitesStatusCell({
|
||||
<DropdownMenuContent align="start" className="min-w-56">
|
||||
{resourceSites.map((site) => {
|
||||
const isOnline = site.online;
|
||||
const hasKnownStatus = typeof isOnline === "boolean";
|
||||
return (
|
||||
<DropdownMenuItem key={site.siteId} asChild>
|
||||
<Link
|
||||
@@ -94,9 +106,11 @@ export function ResourceSitesStatusCell({
|
||||
<div
|
||||
className={cn(
|
||||
"h-2 w-2 shrink-0 rounded-full",
|
||||
isOnline
|
||||
? "bg-green-500"
|
||||
: "bg-neutral-500"
|
||||
!hasKnownStatus
|
||||
? "border border-muted-foreground/50 bg-transparent"
|
||||
: isOnline
|
||||
? "bg-green-500"
|
||||
: "bg-neutral-500"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">
|
||||
@@ -106,12 +120,16 @@ export function ResourceSitesStatusCell({
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 capitalize",
|
||||
isOnline
|
||||
hasKnownStatus && isOnline
|
||||
? "text-green-600"
|
||||
: "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{isOnline ? t("online") : t("offline")}
|
||||
{!hasKnownStatus
|
||||
? t("resourcesTableUnknown")
|
||||
: isOnline
|
||||
? t("online")
|
||||
: t("offline")}
|
||||
</span>
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
|
||||
@@ -60,7 +60,7 @@ export type SiteRow = {
|
||||
type: "newt" | "wireguard" | "local";
|
||||
newtVersion?: string;
|
||||
newtUpdateAvailable?: boolean;
|
||||
online: boolean;
|
||||
online?: boolean | null;
|
||||
address?: string;
|
||||
exitNodeName?: string;
|
||||
exitNodeEndpoint?: string;
|
||||
|
||||
@@ -35,6 +35,7 @@ import { useMemo, useState, useTransition } from "react";
|
||||
import { useDebouncedCallback } from "use-debounce";
|
||||
import ClientDownloadBanner from "./ClientDownloadBanner";
|
||||
import { ColumnFilterButton } from "./ColumnFilterButton";
|
||||
import IdpTypeBadge from "./IdpTypeBadge";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { ControlledDataTable } from "./ui/controlled-data-table";
|
||||
|
||||
@@ -52,6 +53,9 @@ export type ClientRow = {
|
||||
userId: string | null;
|
||||
username: string | null;
|
||||
userEmail: string | null;
|
||||
userType: string | null;
|
||||
idpName: string | null;
|
||||
idpVariant: string | null;
|
||||
niceId: string;
|
||||
agent: string | null;
|
||||
approvalState: "approved" | "pending" | "denied" | null;
|
||||
@@ -370,17 +374,30 @@ export default function UserDevicesTable({
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return r.userId ? (
|
||||
<Link
|
||||
href={`/${r.orgId}/settings/access/users/${r.userId}`}
|
||||
>
|
||||
<Button variant="outline" size="sm">
|
||||
{getUserDisplayName({
|
||||
email: r.userEmail,
|
||||
username: r.username
|
||||
}) || r.userId}
|
||||
<ArrowUpRight className="ml-2 h-3 w-3" />
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href={`/${r.orgId}/settings/access/users/${r.userId}`}
|
||||
>
|
||||
<Button variant="outline" size="sm">
|
||||
{getUserDisplayName({
|
||||
email: r.userEmail,
|
||||
username: r.username
|
||||
}) || r.userId}
|
||||
<ArrowUpRight className="ml-2 h-3 w-3" />
|
||||
</Button>
|
||||
</Link>
|
||||
{(r.userType ?? "internal") !== "internal" && (
|
||||
<IdpTypeBadge
|
||||
type={r.userType ?? "oidc"}
|
||||
name={
|
||||
r.idpName?.trim()
|
||||
? r.idpName
|
||||
: t("idpNameInternal")
|
||||
}
|
||||
variant={r.idpVariant ?? undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
"-"
|
||||
);
|
||||
|
||||
@@ -111,11 +111,13 @@ export function MultiSitesSelector({
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{site.name}
|
||||
</span>
|
||||
<SiteOnlineStatus
|
||||
type={site.type}
|
||||
online={site.online}
|
||||
t={t}
|
||||
/>
|
||||
{site.online != null && (
|
||||
<SiteOnlineStatus
|
||||
type={site.type}
|
||||
online={site.online}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
|
||||
@@ -104,7 +104,7 @@ export function ResourceTargetAddressItem({
|
||||
role="combobox"
|
||||
className={cn(
|
||||
"w-45 justify-between text-sm border-r pr-4 rounded-none h-8 hover:bg-transparent",
|
||||
"rounded-l-md rounded-r-xs",
|
||||
"",
|
||||
!proxyTarget.siteId && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
@@ -142,7 +142,7 @@ export function ResourceTargetAddressItem({
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 px-2 w-17.5 border-none bg-transparent shadow-none data-[state=open]:bg-transparent rounded-xs">
|
||||
<SelectTrigger className="h-8 px-2 w-17.5 border-none bg-transparent shadow-none data-[state=open]:bg-transparent rounded-none">
|
||||
{proxyTarget.method || "http"}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
|
||||
@@ -124,11 +124,13 @@ export function SitesSelector({
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{site.name}
|
||||
</span>
|
||||
<SiteOnlineStatus
|
||||
type={site.type}
|
||||
online={site.online}
|
||||
t={t}
|
||||
/>
|
||||
{site.online != null && (
|
||||
<SiteOnlineStatus
|
||||
type={site.type}
|
||||
online={site.online}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
|
||||
BIN
src/fonts/mona-sans/MonaSans-Bold.ttf
Normal file
BIN
src/fonts/mona-sans/MonaSans-Bold.ttf
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-Bold.woff2
Normal file
BIN
src/fonts/mona-sans/MonaSans-Bold.woff2
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-Italic-VariableFont_wdth,wght.ttf
Normal file
BIN
src/fonts/mona-sans/MonaSans-Italic-VariableFont_wdth,wght.ttf
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-Medium.ttf
Normal file
BIN
src/fonts/mona-sans/MonaSans-Medium.ttf
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-Medium.woff2
Normal file
BIN
src/fonts/mona-sans/MonaSans-Medium.woff2
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-Regular.ttf
Normal file
BIN
src/fonts/mona-sans/MonaSans-Regular.ttf
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-Regular.woff2
Normal file
BIN
src/fonts/mona-sans/MonaSans-Regular.woff2
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-SemiBold.ttf
Normal file
BIN
src/fonts/mona-sans/MonaSans-SemiBold.ttf
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-SemiBold.woff2
Normal file
BIN
src/fonts/mona-sans/MonaSans-SemiBold.woff2
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSans-VariableFont_wdth,wght.ttf
Normal file
BIN
src/fonts/mona-sans/MonaSans-VariableFont_wdth,wght.ttf
Normal file
Binary file not shown.
BIN
src/fonts/mona-sans/MonaSansVF[wdth,wght,opsz,ital].woff2
Normal file
BIN
src/fonts/mona-sans/MonaSansVF[wdth,wght,opsz,ital].woff2
Normal file
Binary file not shown.
@@ -20,7 +20,7 @@ type UseCertificateReturn = {
|
||||
certLoading: boolean;
|
||||
certError: string | null;
|
||||
refreshing: boolean;
|
||||
fetchCert: () => Promise<void>;
|
||||
fetchCert: (showLoading?: boolean) => Promise<void>;
|
||||
refreshCert: () => Promise<void>;
|
||||
clearCert: () => void;
|
||||
};
|
||||
@@ -102,15 +102,33 @@ export function useCertificate({
|
||||
}
|
||||
}, [autoFetch, orgId, domainId, fullDomain, fetchCert]);
|
||||
|
||||
// Polling effect
|
||||
useEffect(() => {
|
||||
if (!polling || !orgId || !domainId || !fullDomain) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
fetchCert(false); // Don't show loading for polling
|
||||
}, pollingInterval);
|
||||
const POLL_JITTER_MS = 1000;
|
||||
let cancelled = false;
|
||||
let timeoutId: ReturnType<typeof setTimeout>;
|
||||
|
||||
return () => clearInterval(interval);
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user