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:
Team Dark Devil committed 2026-11-21 00:06:55 +06:00
1 parent 5c977d6977
commit 8132087085
52 files changed
+4434 -407

No files matched your search

+125 -7
View File
@@ -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(
+4
View File
@@ -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
View File
@@ -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);
}
/**