feat(auth): enhance security and audit logging
- Integrate webhook alerts for admin login lockouts. - Implement detailed audit logging for login, logout, and setup actions. - Improve client revocation event tracking. - Standardize error handling in profile updates. - Enforce 'operator' role for event API access.
This commit is contained in:
1 parent
5c977d6977
commit
8132087085
52 files changed
+4434
-407
No files matched your search
@@ -5,7 +5,17 @@ import net from "node:net";
|
||||
*/
|
||||
|
||||
export function stripIpv6MappedPrefix(ip: string): string {
|
||||
const trimmed = String(ip || "").trim();
|
||||
let trimmed = String(ip || "").trim();
|
||||
if (!trimmed) return "";
|
||||
if (trimmed.startsWith("[") && trimmed.includes("]")) {
|
||||
trimmed = trimmed.slice(1, trimmed.indexOf("]"));
|
||||
} else if (/^\d{1,3}(?:\.\d{1,3}){3}:\d+$/.test(trimmed)) {
|
||||
trimmed = trimmed.slice(0, trimmed.lastIndexOf(":"));
|
||||
}
|
||||
const pctIndex = trimmed.indexOf("%");
|
||||
if (pctIndex !== -1) {
|
||||
trimmed = trimmed.slice(0, pctIndex);
|
||||
}
|
||||
if (trimmed.toLowerCase().startsWith("::ffff:")) {
|
||||
const candidate = trimmed.slice(7);
|
||||
if (net.isIPv4(candidate)) {
|
||||
@@ -142,6 +152,7 @@ export function isClientIpAllowed(
|
||||
return entries.includes("*");
|
||||
}
|
||||
|
||||
const clientFamily = net.isIP(cleanClientIp);
|
||||
const clientIpv4Int = ipv4ToUint32(cleanClientIp);
|
||||
const isLoopbackClient =
|
||||
cleanClientIp === "127.0.0.1" || cleanClientIp.toLowerCase() === "::1";
|
||||
@@ -153,13 +164,47 @@ export function isClientIpAllowed(
|
||||
const [ruleIpRaw, prefixRaw] = rule.split("/");
|
||||
const ruleIp = stripIpv6MappedPrefix(ruleIpRaw);
|
||||
const prefix = Number(prefixRaw);
|
||||
const ruleIpv4Int = ipv4ToUint32(ruleIp);
|
||||
const ruleFamily = net.isIP(ruleIp);
|
||||
|
||||
if (clientIpv4Int !== null && ruleIpv4Int !== null && prefix >= 0 && prefix <= 32) {
|
||||
if (
|
||||
clientFamily === 4 &&
|
||||
ruleFamily === 4 &&
|
||||
Number.isInteger(prefix) &&
|
||||
prefix >= 0 &&
|
||||
prefix <= 32
|
||||
) {
|
||||
if (prefix === 0) return true;
|
||||
const mask = prefix === 32 ? 0xffffffff : (~((1 << (32 - prefix)) - 1)) >>> 0;
|
||||
if ((clientIpv4Int & mask) >>> 0 === (ruleIpv4Int & mask) >>> 0) {
|
||||
return true;
|
||||
try {
|
||||
const bl = new net.BlockList();
|
||||
bl.addSubnet(ruleIp, prefix, "ipv4");
|
||||
if (bl.check(cleanClientIp, "ipv4")) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
const ruleIpv4Int = ipv4ToUint32(ruleIp);
|
||||
if (clientIpv4Int !== null && ruleIpv4Int !== null) {
|
||||
const mask = prefix === 32 ? 0xffffffff : (~((1 << (32 - prefix)) - 1)) >>> 0;
|
||||
if ((clientIpv4Int & mask) >>> 0 === (ruleIpv4Int & mask) >>> 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
clientFamily === 6 &&
|
||||
ruleFamily === 6 &&
|
||||
Number.isInteger(prefix) &&
|
||||
prefix >= 0 &&
|
||||
prefix <= 128
|
||||
) {
|
||||
if (prefix === 0) return true;
|
||||
try {
|
||||
const bl = new net.BlockList();
|
||||
bl.addSubnet(ruleIp, prefix, "ipv6");
|
||||
if (bl.check(cleanClientIp, "ipv6")) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed IPv6 subnet
|
||||
}
|
||||
}
|
||||
continue;
|
||||
|
||||
@@ -26,8 +26,10 @@ export interface StorageFileMeta {
|
||||
}
|
||||
|
||||
export interface DiskUsageSnapshot {
|
||||
available: boolean;
|
||||
usedPct: number;
|
||||
availableBytes: number;
|
||||
freeBytes: number;
|
||||
totalBytes: number;
|
||||
checkedAt: number;
|
||||
}
|
||||
@@ -85,7 +87,9 @@ export class CSVStorageManager {
|
||||
}
|
||||
|
||||
public static extractDateFromFilename(filename: string): string {
|
||||
return filename.replace(/\.csv(?:\.gz)?$/, '').split('-part')[0];
|
||||
return String(filename || '')
|
||||
.replace(/\.csv(?:\.gz)?$/i, '')
|
||||
.replace(/(?:-(?:part|gz)\d+)+$/i, '');
|
||||
}
|
||||
|
||||
public static clearRowCountCache(): void {
|
||||
@@ -1073,8 +1077,10 @@ export class CSVStorageManager {
|
||||
)
|
||||
: 0;
|
||||
const snapshot: DiskUsageSnapshot = {
|
||||
available: totalBytes > 0,
|
||||
usedPct,
|
||||
availableBytes,
|
||||
freeBytes: availableBytes,
|
||||
totalBytes,
|
||||
checkedAt: now,
|
||||
};
|
||||
@@ -1082,8 +1088,10 @@ export class CSVStorageManager {
|
||||
return snapshot;
|
||||
} catch {
|
||||
const fallback: DiskUsageSnapshot = {
|
||||
available: false,
|
||||
usedPct: 0,
|
||||
availableBytes: 0,
|
||||
freeBytes: 0,
|
||||
totalBytes: 0,
|
||||
checkedAt: now,
|
||||
};
|
||||
|
||||
@@ -92,12 +92,33 @@ type SettingsGlobals = typeof globalThis & {
|
||||
__dataStackLastSettingsBridgeSync?: SettingsBridgeSyncStatus;
|
||||
__dataStackLastPruneMeta?: { days: number; ranAtMs: number };
|
||||
__dataStackLastCompressMeta?: { days: number; ranAtMs: number };
|
||||
__dataStackMaintenanceTimer?: ReturnType<typeof setInterval>;
|
||||
__dataStackMaintenanceIntervalMs?: number;
|
||||
__dataStackMaintenanceRunning?: boolean;
|
||||
__dataStackArchivePruneInFlight?: boolean;
|
||||
__dataStackCompressInFlight?: boolean;
|
||||
};
|
||||
|
||||
const PRUNE_COOLDOWN_MS = 60 * 60 * 1000;
|
||||
const COMPRESS_COOLDOWN_MS = 60 * 60 * 1000;
|
||||
const DEFAULT_MAINTENANCE_INTERVAL_MS = 15 * 60 * 1000;
|
||||
const globals = globalThis as SettingsGlobals;
|
||||
|
||||
function resolveMaintenanceIntervalMs(overrideMs?: number): number {
|
||||
if (
|
||||
typeof overrideMs === "number" &&
|
||||
Number.isFinite(overrideMs) &&
|
||||
overrideMs >= 20
|
||||
) {
|
||||
return Math.floor(overrideMs);
|
||||
}
|
||||
const envVal = Number(process.env.DATASTACK_MAINTENANCE_INTERVAL_MS);
|
||||
if (Number.isFinite(envVal) && envVal >= 1000) {
|
||||
return Math.floor(envVal);
|
||||
}
|
||||
return DEFAULT_MAINTENANCE_INTERVAL_MS;
|
||||
}
|
||||
|
||||
function getDefaultSettings(): AdminSettings {
|
||||
return {
|
||||
serverPort: Number(process.env.PORT_SOCKET) || 4000,
|
||||
@@ -257,10 +278,167 @@ export class SettingsManager {
|
||||
);
|
||||
}
|
||||
|
||||
public static isMaintenanceSchedulerActive(): boolean {
|
||||
return Boolean(globals.__dataStackMaintenanceTimer);
|
||||
}
|
||||
|
||||
public static ensureMaintenanceScheduler(intervalMs?: number): boolean {
|
||||
const effectiveIntervalMs = resolveMaintenanceIntervalMs(intervalMs);
|
||||
if (globals.__dataStackMaintenanceTimer) {
|
||||
if (
|
||||
intervalMs === undefined ||
|
||||
globals.__dataStackMaintenanceIntervalMs === effectiveIntervalMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
clearInterval(globals.__dataStackMaintenanceTimer);
|
||||
delete globals.__dataStackMaintenanceTimer;
|
||||
}
|
||||
|
||||
const timer = setInterval(() => {
|
||||
void this.runScheduledMaintenanceTick().catch((err) => {
|
||||
console.warn(
|
||||
"[DataStack Storage] Periodic maintenance tick failed:",
|
||||
err,
|
||||
);
|
||||
});
|
||||
}, effectiveIntervalMs);
|
||||
timer.unref?.();
|
||||
globals.__dataStackMaintenanceTimer = timer;
|
||||
globals.__dataStackMaintenanceIntervalMs = effectiveIntervalMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static stopMaintenanceScheduler(): void {
|
||||
if (globals.__dataStackMaintenanceTimer) {
|
||||
clearInterval(globals.__dataStackMaintenanceTimer);
|
||||
delete globals.__dataStackMaintenanceTimer;
|
||||
}
|
||||
delete globals.__dataStackMaintenanceIntervalMs;
|
||||
globals.__dataStackMaintenanceRunning = false;
|
||||
}
|
||||
|
||||
public static stopMaintenanceSchedulerForTests(): void {
|
||||
this.stopMaintenanceScheduler();
|
||||
globals.__dataStackArchivePruneInFlight = false;
|
||||
globals.__dataStackCompressInFlight = false;
|
||||
}
|
||||
|
||||
public static async runScheduledMaintenanceTick(options?: {
|
||||
forceCompress?: boolean;
|
||||
forcePrune?: boolean;
|
||||
skipDbSync?: boolean;
|
||||
}): Promise<{
|
||||
ran: boolean;
|
||||
skippedReason?: string;
|
||||
compressed: boolean;
|
||||
archivedOrPruned: boolean;
|
||||
}> {
|
||||
if (globals.__dataStackMaintenanceRunning) {
|
||||
return {
|
||||
ran: false,
|
||||
skippedReason: "ALREADY_RUNNING",
|
||||
compressed: false,
|
||||
archivedOrPruned: false,
|
||||
};
|
||||
}
|
||||
|
||||
globals.__dataStackMaintenanceRunning = true;
|
||||
try {
|
||||
const hasConfiguredDb = Boolean(process.env.DATABASE_URL?.trim());
|
||||
if (hasConfiguredDb && !options?.skipDbSync) {
|
||||
await this.syncFromDatabase(true);
|
||||
}
|
||||
|
||||
const dbReadyForMaintenance =
|
||||
!hasConfiguredDb || globals.__dataStackSettingsHydrated === true;
|
||||
if (!dbReadyForMaintenance) {
|
||||
return {
|
||||
ran: false,
|
||||
skippedReason: "DB_UNHYDRATED",
|
||||
compressed: false,
|
||||
archivedOrPruned: false,
|
||||
};
|
||||
}
|
||||
|
||||
const settings = getSettingsState();
|
||||
const now = Date.now();
|
||||
let compressed = false;
|
||||
let archivedOrPruned = false;
|
||||
|
||||
if (
|
||||
settings.compressAfterDays > 0 &&
|
||||
!globals.__dataStackCompressInFlight
|
||||
) {
|
||||
const prevComp = globals.__dataStackLastCompressMeta;
|
||||
const shouldCompress =
|
||||
Boolean(options?.forceCompress) ||
|
||||
!prevComp ||
|
||||
prevComp.days !== settings.compressAfterDays ||
|
||||
now - prevComp.ranAtMs >= COMPRESS_COOLDOWN_MS;
|
||||
if (shouldCompress) {
|
||||
globals.__dataStackLastCompressMeta = {
|
||||
days: settings.compressAfterDays,
|
||||
ranAtMs: now,
|
||||
};
|
||||
globals.__dataStackCompressInFlight = true;
|
||||
try {
|
||||
await CSVStorageManager.compressOldPartitionsAsync(
|
||||
settings.compressAfterDays,
|
||||
);
|
||||
compressed = true;
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[DataStack Storage] Scheduled partition compression failed:",
|
||||
err,
|
||||
);
|
||||
} finally {
|
||||
globals.__dataStackCompressInFlight = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
settings.autoPruneDays > 0 &&
|
||||
!globals.__dataStackArchivePruneInFlight
|
||||
) {
|
||||
const prevPrune = globals.__dataStackLastPruneMeta;
|
||||
const shouldPrune =
|
||||
Boolean(options?.forcePrune) ||
|
||||
!prevPrune ||
|
||||
prevPrune.days !== settings.autoPruneDays ||
|
||||
now - prevPrune.ranAtMs >= PRUNE_COOLDOWN_MS;
|
||||
if (shouldPrune) {
|
||||
globals.__dataStackLastPruneMeta = {
|
||||
days: settings.autoPruneDays,
|
||||
ranAtMs: now,
|
||||
};
|
||||
globals.__dataStackArchivePruneInFlight = true;
|
||||
try {
|
||||
await this.executeArchiveAndPrune(settings);
|
||||
archivedOrPruned = true;
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[DataStack Storage] Scheduled partition prune/archive failed:",
|
||||
err,
|
||||
);
|
||||
} finally {
|
||||
globals.__dataStackArchivePruneInFlight = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { ran: true, compressed, archivedOrPruned };
|
||||
} finally {
|
||||
globals.__dataStackMaintenanceRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static applyRuntimeSettings(
|
||||
settings: AdminSettings,
|
||||
forcePrune = false,
|
||||
forceCompress = false,
|
||||
skipBackgroundMaintenance = false,
|
||||
) {
|
||||
SecurityEngine.maxEventsPerSec = settings.maxEventsPerSec;
|
||||
SecurityEngine.enableIdempotency = settings.enableIdempotency;
|
||||
@@ -271,11 +449,19 @@ export class SettingsManager {
|
||||
AuthService.setSecret(settings.jwtSecret);
|
||||
}
|
||||
CSVStorageManager.maxFileSizeBytes = settings.fileRotationMb * 1024 * 1024;
|
||||
this.ensureMaintenanceScheduler();
|
||||
if (skipBackgroundMaintenance) {
|
||||
return;
|
||||
}
|
||||
const hasConfiguredDb = Boolean(process.env.DATABASE_URL?.trim());
|
||||
const dbReadyForMaintenance =
|
||||
!hasConfiguredDb || globals.__dataStackSettingsHydrated === true;
|
||||
|
||||
if (settings.compressAfterDays > 0 && dbReadyForMaintenance) {
|
||||
if (
|
||||
settings.compressAfterDays > 0 &&
|
||||
dbReadyForMaintenance &&
|
||||
!globals.__dataStackCompressInFlight
|
||||
) {
|
||||
const prevComp = globals.__dataStackLastCompressMeta;
|
||||
const now = Date.now();
|
||||
const shouldCompress =
|
||||
@@ -288,18 +474,27 @@ export class SettingsManager {
|
||||
days: settings.compressAfterDays,
|
||||
ranAtMs: now,
|
||||
};
|
||||
globals.__dataStackCompressInFlight = true;
|
||||
void CSVStorageManager.compressOldPartitionsAsync(
|
||||
settings.compressAfterDays,
|
||||
).catch((err) => {
|
||||
console.warn(
|
||||
"[DataStack Storage] Background partition compression failed:",
|
||||
err,
|
||||
);
|
||||
});
|
||||
)
|
||||
.catch((err) => {
|
||||
console.warn(
|
||||
"[DataStack Storage] Background partition compression failed:",
|
||||
err,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
globals.__dataStackCompressInFlight = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.autoPruneDays > 0 && dbReadyForMaintenance) {
|
||||
if (
|
||||
settings.autoPruneDays > 0 &&
|
||||
dbReadyForMaintenance &&
|
||||
!globals.__dataStackArchivePruneInFlight
|
||||
) {
|
||||
const prev = globals.__dataStackLastPruneMeta;
|
||||
const now = Date.now();
|
||||
const shouldPrune =
|
||||
@@ -312,17 +507,24 @@ export class SettingsManager {
|
||||
days: settings.autoPruneDays,
|
||||
ranAtMs: now,
|
||||
};
|
||||
void this.executeArchiveAndPrune(settings).catch((err) => {
|
||||
console.warn(
|
||||
"[DataStack Storage] Background async partition prune/archive failed:",
|
||||
err,
|
||||
);
|
||||
});
|
||||
globals.__dataStackArchivePruneInFlight = true;
|
||||
void this.executeArchiveAndPrune(settings)
|
||||
.catch((err) => {
|
||||
console.warn(
|
||||
"[DataStack Storage] Background async partition prune/archive failed:",
|
||||
err,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
globals.__dataStackArchivePruneInFlight = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async syncFromDatabase(): Promise<AdminSettings | null> {
|
||||
private static async syncFromDatabase(
|
||||
skipBackgroundMaintenance = false,
|
||||
): Promise<AdminSettings | null> {
|
||||
const pool = DatabaseEngine.getPool();
|
||||
if (!pool) return null;
|
||||
|
||||
@@ -414,7 +616,12 @@ export class SettingsManager {
|
||||
};
|
||||
globals.__dataStackAdminSettings = loaded;
|
||||
globals.__dataStackSettingsHydrated = true;
|
||||
this.applyRuntimeSettings(loaded);
|
||||
this.applyRuntimeSettings(
|
||||
loaded,
|
||||
false,
|
||||
false,
|
||||
skipBackgroundMaintenance,
|
||||
);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
@@ -625,6 +832,19 @@ export class SettingsManager {
|
||||
process.env.INGESTION_INTERNAL_URL || "http://127.0.0.1:4000"
|
||||
).replace(/\/$/, "");
|
||||
|
||||
let decryptedWebhookSecret = "";
|
||||
if (settings.webhookSecretEnc) {
|
||||
try {
|
||||
decryptedWebhookSecret = decryptSecret(settings.webhookSecretEnc);
|
||||
} catch (vaultErr: unknown) {
|
||||
console.warn(
|
||||
"[DataStack Bridge] Stored webhook secret could not be decrypted during Port 4000 settings sync; continuing with empty webhook secret:",
|
||||
vaultErr instanceof Error ? vaultErr.message : vaultErr,
|
||||
);
|
||||
decryptedWebhookSecret = "";
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${ingestionBaseUrl}/internal/settings-sync`, {
|
||||
method: "POST",
|
||||
@@ -645,6 +865,7 @@ export class SettingsManager {
|
||||
diskPauseThresholdPct: settings.diskPauseThresholdPct,
|
||||
enableWebhookAlerts: settings.enableWebhookAlerts,
|
||||
webhookUrl: settings.webhookUrl,
|
||||
webhookSecret: decryptedWebhookSecret,
|
||||
webhookCooldownSec: settings.webhookCooldownSec,
|
||||
...(jwtSecretChanged ? { jwtSecret: settings.jwtSecret } : {}),
|
||||
}),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { SettingsManager } from '../adminSettings/settingsManager';
|
||||
import { SDKManager } from '../sdk/sdkManager';
|
||||
import { CSVStorageManager } from '../Storage/csvStorage';
|
||||
import { DataBufferEngine } from '../data/buffer';
|
||||
import { isClientTokenExpired } from '../Security/ipAllowlist';
|
||||
import {
|
||||
SecurityEngine,
|
||||
getInternalIngestionHeaders,
|
||||
@@ -20,7 +21,13 @@ export class ApiEngine {
|
||||
DataBufferEngine.getBufferStatsAsync(),
|
||||
SDKManager.listClientsAsync(),
|
||||
]);
|
||||
const activeClients = clients.filter((c) => c.status === 'active').length;
|
||||
const nowMs = Date.now();
|
||||
const expiredClients = clients.filter(
|
||||
(c) => c.status === 'active' && isClientTokenExpired(c.expiresAt, nowMs),
|
||||
).length;
|
||||
const activeClients = clients.filter(
|
||||
(c) => c.status === 'active' && !isClientTokenExpired(c.expiresAt, nowMs),
|
||||
).length;
|
||||
let activeSockets = 0;
|
||||
let ingestionLocalBufferSize = 0;
|
||||
let ingestionRedisBufferSize = 0;
|
||||
@@ -129,6 +136,7 @@ export class ApiEngine {
|
||||
activeSockets,
|
||||
totalClients: clients.length,
|
||||
activeClients,
|
||||
expiredClients,
|
||||
bufferStats,
|
||||
storageStats,
|
||||
diskUsage,
|
||||
|
||||
+125
-7
@@ -913,7 +913,11 @@ export async function updateAdminAccount({
|
||||
currentPassword,
|
||||
);
|
||||
if (!authCheck.authenticated) {
|
||||
return { ok: false as const, error: "Current password is incorrect." };
|
||||
return {
|
||||
ok: false as const,
|
||||
error: "Current password is incorrect.",
|
||||
code: "INVALID_PASSWORD" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const cleanEmail = nextEmail.trim().toLowerCase();
|
||||
@@ -926,6 +930,18 @@ export async function updateAdminAccount({
|
||||
if (pool) {
|
||||
await ensureAdminTable();
|
||||
if (authCheck.memberId === "owner-1") {
|
||||
const teamCollision = await pool.query(
|
||||
`SELECT 1 FROM admin_team_members WHERE LOWER(email) = $1 LIMIT 1`,
|
||||
[cleanEmail],
|
||||
);
|
||||
if (teamCollision.rowCount && teamCollision.rowCount > 0) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `An administrator with email '${cleanEmail}' already exists.`,
|
||||
code: "ADMIN_EMAIL_CONFLICT" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const updated = await pool.query(
|
||||
`UPDATE admin_users
|
||||
SET email = $1,
|
||||
@@ -937,7 +953,11 @@ export async function updateAdminAccount({
|
||||
[cleanEmail, salt, passwordHash],
|
||||
);
|
||||
if (!updated.rowCount || updated.rowCount === 0) {
|
||||
return { ok: false as const, error: "Admin account not found." };
|
||||
return {
|
||||
ok: false as const,
|
||||
error: "Admin account not found.",
|
||||
code: "ACCOUNT_NOT_FOUND" as const,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true as const,
|
||||
@@ -948,6 +968,30 @@ export async function updateAdminAccount({
|
||||
};
|
||||
}
|
||||
|
||||
const ownerCollision = await pool.query(
|
||||
`SELECT 1 FROM admin_users WHERE id = 1 AND LOWER(email) = $1 LIMIT 1`,
|
||||
[cleanEmail],
|
||||
);
|
||||
if (ownerCollision.rowCount && ownerCollision.rowCount > 0) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `An administrator with email '${cleanEmail}' already exists.`,
|
||||
code: "ADMIN_EMAIL_CONFLICT" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const peerCollision = await pool.query(
|
||||
`SELECT 1 FROM admin_team_members WHERE LOWER(email) = $1 AND id <> $2 LIMIT 1`,
|
||||
[cleanEmail, authCheck.memberId],
|
||||
);
|
||||
if (peerCollision.rowCount && peerCollision.rowCount > 0) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `An administrator with email '${cleanEmail}' already exists.`,
|
||||
code: "ADMIN_EMAIL_CONFLICT" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const updatedMember = await pool.query(
|
||||
`UPDATE admin_team_members
|
||||
SET email = $1,
|
||||
@@ -960,7 +1004,11 @@ export async function updateAdminAccount({
|
||||
[cleanEmail, salt, passwordHash, authCheck.memberId],
|
||||
);
|
||||
if (!updatedMember.rowCount || updatedMember.rowCount === 0) {
|
||||
return { ok: false as const, error: "Team account not found." };
|
||||
return {
|
||||
ok: false as const,
|
||||
error: "Team account not found.",
|
||||
code: "ACCOUNT_NOT_FOUND" as const,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true as const,
|
||||
@@ -972,6 +1020,16 @@ export async function updateAdminAccount({
|
||||
}
|
||||
|
||||
if (authCheck.memberId === "owner-1") {
|
||||
for (const peer of getInMemoryTeamMap().values()) {
|
||||
if (peer.email.toLowerCase() === cleanEmail) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `An administrator with email '${cleanEmail}' already exists.`,
|
||||
code: "ADMIN_EMAIL_CONFLICT" as const,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const existing = await getOrInitInMemoryAdmin();
|
||||
const nextVersion = existing.tokenVersion + 1;
|
||||
globals.__dataStackInMemoryAdmin = {
|
||||
@@ -991,10 +1049,32 @@ export async function updateAdminAccount({
|
||||
};
|
||||
}
|
||||
|
||||
const inMemOwner = await getOrInitInMemoryAdmin();
|
||||
if (inMemOwner.email.toLowerCase() === cleanEmail) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `An administrator with email '${cleanEmail}' already exists.`,
|
||||
code: "ADMIN_EMAIL_CONFLICT" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const teamMap = getInMemoryTeamMap();
|
||||
const member = teamMap.get(authCheck.memberId);
|
||||
if (!member) {
|
||||
return { ok: false as const, error: "Team account not found." };
|
||||
return {
|
||||
ok: false as const,
|
||||
error: "Team account not found.",
|
||||
code: "ACCOUNT_NOT_FOUND" as const,
|
||||
};
|
||||
}
|
||||
for (const peer of teamMap.values()) {
|
||||
if (peer.id !== member.id && peer.email.toLowerCase() === cleanEmail) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `An administrator with email '${cleanEmail}' already exists.`,
|
||||
code: "ADMIN_EMAIL_CONFLICT" as const,
|
||||
};
|
||||
}
|
||||
}
|
||||
const nextVersion = member.tokenVersion + 1;
|
||||
teamMap.set(member.id, {
|
||||
@@ -1014,12 +1094,23 @@ export async function updateAdminAccount({
|
||||
};
|
||||
}
|
||||
|
||||
export async function revokeAdminSessions(memberId?: string): Promise<number> {
|
||||
export async function revokeAdminSessions(
|
||||
target?: string | { memberId?: string; email?: string },
|
||||
): Promise<number> {
|
||||
const explicitMemberId =
|
||||
typeof target === "string"
|
||||
? target.trim()
|
||||
: target?.memberId?.trim() || "";
|
||||
const explicitEmail =
|
||||
typeof target === "object" && target !== null
|
||||
? target.email?.trim().toLowerCase() || ""
|
||||
: "";
|
||||
const effectiveMemberId =
|
||||
memberId || globals.__dataStackLastVerifiedMemberId || "owner-1";
|
||||
explicitMemberId ||
|
||||
(!explicitEmail ? globals.__dataStackLastVerifiedMemberId || "owner-1" : "");
|
||||
const pool = getPool();
|
||||
|
||||
if (effectiveMemberId !== "owner-1" && effectiveMemberId !== "1") {
|
||||
if (effectiveMemberId && effectiveMemberId !== "owner-1" && effectiveMemberId !== "1") {
|
||||
if (pool) {
|
||||
await ensureAdminTable();
|
||||
const updated = await pool.query(
|
||||
@@ -1045,6 +1136,33 @@ export async function revokeAdminSessions(memberId?: string): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
if (explicitEmail) {
|
||||
if (pool) {
|
||||
await ensureAdminTable();
|
||||
const updatedByEmail = await pool.query(
|
||||
`UPDATE admin_team_members
|
||||
SET token_version = COALESCE(token_version, 1) + 1,
|
||||
updated_at = NOW()
|
||||
WHERE LOWER(email) = $1
|
||||
RETURNING token_version`,
|
||||
[explicitEmail],
|
||||
);
|
||||
if (updatedByEmail.rowCount && updatedByEmail.rowCount > 0) {
|
||||
return Number(updatedByEmail.rows[0].token_version) || 1;
|
||||
}
|
||||
} else {
|
||||
const teamMap = getInMemoryTeamMap();
|
||||
for (const member of teamMap.values()) {
|
||||
if (member.email.toLowerCase() === explicitEmail) {
|
||||
member.tokenVersion += 1;
|
||||
member.updatedAt = new Date();
|
||||
teamMap.set(member.id, member);
|
||||
return member.tokenVersion;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pool) {
|
||||
await ensureAdminTable();
|
||||
const updated = await pool.query(
|
||||
|
||||
@@ -2,7 +2,9 @@ import { randomBytes } from "node:crypto";
|
||||
import { DatabaseEngine } from "@/core/Database/database";
|
||||
|
||||
export type AuditActionType =
|
||||
| "ADMIN_SETUP"
|
||||
| "ADMIN_LOGIN"
|
||||
| "ADMIN_LOGOUT"
|
||||
| "ADMIN_PROFILE_UPDATED"
|
||||
| "ADMIN_PASSWORD_UPDATED"
|
||||
| "TEAM_MEMBER_CREATED"
|
||||
@@ -11,9 +13,11 @@ export type AuditActionType =
|
||||
| "TEAM_MEMBER_DELETED"
|
||||
| "CLIENT_CREATED"
|
||||
| "CLIENT_UPDATED"
|
||||
| "CLIENT_REVOKED"
|
||||
| "CLIENT_TOKEN_ROTATED"
|
||||
| "CLIENT_DELETED"
|
||||
| "SETTINGS_UPDATED"
|
||||
| "STORAGE_FLUSH_TRIGGERED"
|
||||
| "S3_ARCHIVE_TRIGGERED"
|
||||
| "WEBHOOK_TEST_TRIGGERED"
|
||||
| string;
|
||||
|
||||
+17
-10
@@ -47,10 +47,13 @@ export class AuthService {
|
||||
|
||||
/**
|
||||
* Generates a signed JWT for client SDK authentication.
|
||||
* When `expiresIn` is null/omitted, no hardcoded JWT `exp` claim is embedded so
|
||||
* database-backed `client_sdks.expires_at` (including "Never expires" or >30d
|
||||
* policies and live expiry extensions) remains the authoritative expiry check.
|
||||
*/
|
||||
public static generateClientToken(
|
||||
payload: { clientId: string; name?: string; rateLimit?: number },
|
||||
expiresIn = "30d",
|
||||
expiresIn?: string | number | null,
|
||||
): string {
|
||||
if (!this.isConfigured()) {
|
||||
throw new Error(
|
||||
@@ -58,15 +61,19 @@ export class AuthService {
|
||||
);
|
||||
}
|
||||
|
||||
return jwt.sign(
|
||||
{
|
||||
clientId: payload.clientId,
|
||||
name: payload.name || payload.clientId,
|
||||
rateLimit: payload.rateLimit || 100,
|
||||
},
|
||||
this.secret,
|
||||
{ expiresIn: expiresIn as jwt.SignOptions["expiresIn"] },
|
||||
);
|
||||
const tokenBody = {
|
||||
clientId: payload.clientId,
|
||||
name: payload.name || payload.clientId,
|
||||
rateLimit: payload.rateLimit || 100,
|
||||
};
|
||||
|
||||
if (expiresIn !== undefined && expiresIn !== null && expiresIn !== "") {
|
||||
return jwt.sign(tokenBody, this.secret, {
|
||||
expiresIn: expiresIn as jwt.SignOptions["expiresIn"],
|
||||
});
|
||||
}
|
||||
|
||||
return jwt.sign(tokenBody, this.secret);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+48
-30
@@ -540,11 +540,14 @@ export class SDKManager {
|
||||
const allowedIps = typeof data.allowedIps === "string" ? data.allowedIps.trim() : "";
|
||||
const expiresAt = data.expiresAt ? String(data.expiresAt) : null;
|
||||
|
||||
const token = AuthService.generateClientToken({
|
||||
clientId: safeClientId,
|
||||
name: data.name.trim(),
|
||||
rateLimit,
|
||||
});
|
||||
const token = AuthService.generateClientToken(
|
||||
{
|
||||
clientId: safeClientId,
|
||||
name: data.name.trim(),
|
||||
rateLimit,
|
||||
},
|
||||
null,
|
||||
);
|
||||
|
||||
const newClient: ClientSDK = {
|
||||
clientId: safeClientId,
|
||||
@@ -637,11 +640,14 @@ export class SDKManager {
|
||||
const allowedIps = typeof data.allowedIps === "string" ? data.allowedIps.trim() : "";
|
||||
const expiresAt = data.expiresAt ? String(data.expiresAt) : null;
|
||||
|
||||
const token = AuthService.generateClientToken({
|
||||
clientId: safeClientId,
|
||||
name: data.name.trim(),
|
||||
rateLimit,
|
||||
});
|
||||
const token = AuthService.generateClientToken(
|
||||
{
|
||||
clientId: safeClientId,
|
||||
name: data.name.trim(),
|
||||
rateLimit,
|
||||
},
|
||||
null,
|
||||
);
|
||||
|
||||
const newClient: ClientSDK = {
|
||||
clientId: safeClientId,
|
||||
@@ -674,11 +680,14 @@ export class SDKManager {
|
||||
const updated: ClientSDK = {
|
||||
...client,
|
||||
secret: this.generateClientSecret(normalizedId),
|
||||
token: AuthService.generateClientToken({
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
rateLimit: client.rateLimit,
|
||||
}),
|
||||
token: AuthService.generateClientToken(
|
||||
{
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
rateLimit: client.rateLimit,
|
||||
},
|
||||
null,
|
||||
),
|
||||
};
|
||||
|
||||
getClientsMap().set(normalizedId, updated);
|
||||
@@ -724,11 +733,14 @@ export class SDKManager {
|
||||
const updated: ClientSDK = {
|
||||
...existing,
|
||||
secret: this.generateClientSecret(normalizedId),
|
||||
token: AuthService.generateClientToken({
|
||||
clientId: existing.clientId,
|
||||
name: existing.name,
|
||||
rateLimit: existing.rateLimit,
|
||||
}),
|
||||
token: AuthService.generateClientToken(
|
||||
{
|
||||
clientId: existing.clientId,
|
||||
name: existing.name,
|
||||
rateLimit: existing.rateLimit,
|
||||
},
|
||||
null,
|
||||
),
|
||||
};
|
||||
|
||||
await this.persistClientCredentials(updated);
|
||||
@@ -1170,11 +1182,14 @@ export class SDKManager {
|
||||
public static resignAllClientTokens(): void {
|
||||
const map = getClientsMap();
|
||||
for (const [clientId, client] of map.entries()) {
|
||||
client.token = AuthService.generateClientToken({
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
rateLimit: client.rateLimit,
|
||||
});
|
||||
client.token = AuthService.generateClientToken(
|
||||
{
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
rateLimit: client.rateLimit,
|
||||
},
|
||||
null,
|
||||
);
|
||||
map.set(clientId, client);
|
||||
void this.persistClientCredentials(client).catch((err) => {
|
||||
console.error("[DataStack SDK] Background re-sign DB persist failed:", err);
|
||||
@@ -1188,11 +1203,14 @@ export class SDKManager {
|
||||
for (const client of clients) {
|
||||
const updated: ClientSDK = {
|
||||
...client,
|
||||
token: AuthService.generateClientToken({
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
rateLimit: client.rateLimit,
|
||||
}),
|
||||
token: AuthService.generateClientToken(
|
||||
{
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
rateLimit: client.rateLimit,
|
||||
},
|
||||
null,
|
||||
),
|
||||
};
|
||||
await this.persistClientCredentials(updated);
|
||||
map.set(updated.clientId, updated);
|
||||
|
||||
Reference in new issue
Block a user