Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/common/services/log.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const MAX_STRING_LENGTH = 500;
const MAX_SCRUB_DEPTH = 8;
/** ip_address column is varchar(45) — a full IPv6 textual address. */
const MAX_IP_LENGTH = 45;
/** user_agent column is varchar(512); truncate anything longer before persisting. */
const MAX_USER_AGENT_LENGTH = 512;

/**
* Shared audit-trail writer (BE-ADM-609). Persists admin_logs rows for the
Expand Down Expand Up @@ -44,6 +46,7 @@ export class LogService {
// Capture request-derived data synchronously: the request object may be
// recycled by the framework before the deferred insert runs.
const ipAddress = this.extractIpAddress(req);
const userAgent = this.extractUserAgent(req);
const scrubbedMetadata = metadata ? this.scrubObject(metadata, 0) : {};

setImmediate(() => {
Expand All @@ -55,6 +58,7 @@ export class LogService {
action_type: actionType,
description,
ip_address: ipAddress,
user_agent: userAgent,
status,
metadata: scrubbedMetadata,
});
Expand Down Expand Up @@ -84,6 +88,18 @@ export class LogService {
return clientIp ? clientIp.slice(0, MAX_IP_LENGTH) : null;
}

/** Captures the raw User-Agent header; the read side parses it into a device label. */
private extractUserAgent(req: Request | null): string | null {
if (!req) {
return null;
}

// The 'user-agent' header is a single-value header (string | undefined).
const userAgent = req.headers?.['user-agent'];

return userAgent ? userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null;
}

/** FR-4: redact sensitive keys and truncate oversized strings, recursively. */
private scrubObject(value: Record<string, unknown>, depth: number): Record<string, unknown> {
const scrubbed: Record<string, unknown> = {};
Expand Down
25 changes: 25 additions & 0 deletions src/common/services/tests/log.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,36 @@ describe('LogService', () => {
action_type: AdminLogActionType.LOGIN,
description: 'User logged in',
ip_address: '127.0.0.1',
user_agent: null,
status: AdminLogStatus.SUCCESS,
metadata: {},
});
});

it('captures the User-Agent header when present', async () => {
const req = makeRequest({
headers: { 'user-agent': 'Mozilla/5.0 (Macintosh) Chrome/134.0.0.0 Safari/537.36' },
} as Partial<Request>);

service.log('user-1', AdminLogActionType.LOGIN, 'x', req, AdminLogStatus.SUCCESS);
await flushImmediates();

expect(mockAdminLogRepository.create).toHaveBeenCalledWith(
expect.objectContaining({
user_agent: 'Mozilla/5.0 (Macintosh) Chrome/134.0.0.0 Safari/537.36',
}),
);
});

it('stores a null user_agent when the header is absent', async () => {
service.log('user-1', AdminLogActionType.LOGIN, 'x', makeRequest(), AdminLogStatus.SUCCESS);
await flushImmediates();

expect(mockAdminLogRepository.create).toHaveBeenCalledWith(
expect.objectContaining({ user_agent: null }),
);
});
Comment thread
ibraheembello marked this conversation as resolved.

it('AC-04 / FR-2: returns before the database write starts', () => {
service.log('user-1', AdminLogActionType.LOGIN, 'x', null, AdminLogStatus.SUCCESS);

Expand Down
21 changes: 21 additions & 0 deletions src/database/migrations/1781308800000-AddUserAgentToAdminLogs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

/**
* Adds the raw User-Agent capture column to admin_logs. The value is parsed into
* a "Browser Major · OS Version" device label on read; storing it raw lets the
* parser improve later without a backfill. Nullable: non-HTTP actions and older
* rows have no user agent. varchar(512) comfortably fits real-world UA strings.
*/
export class AddUserAgentToAdminLogs1781308800000 implements MigrationInterface {
name = 'AddUserAgentToAdminLogs1781308800000';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "admin_logs" ADD COLUMN IF NOT EXISTS "user_agent" character varying(512)`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "admin_logs" DROP COLUMN IF EXISTS "user_agent"`);
}
}
2 changes: 2 additions & 0 deletions src/modules/admin/logs/actions/admin-logs-list.action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface RawAdminLogRow {
log_action_type: AdminLogActionType;
log_description: string;
log_ip_address: string | null;
log_user_agent: string | null;
log_status: AdminLogStatus;
log_created_at: Date;
}
Expand All @@ -45,6 +46,7 @@ export class AdminLogsListAction {
.addSelect('log.action_type', 'log_action_type')
.addSelect('log.description', 'log_description')
.addSelect('log.ip_address', 'log_ip_address')
.addSelect('log.user_agent', 'log_user_agent')
.addSelect('log.status', 'log_status')
.addSelect('log.created_at', 'log_created_at');

Expand Down
3 changes: 2 additions & 1 deletion src/modules/admin/logs/admin-logs.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { AdminAuthModule } from '../auth/admin-auth.module';
import { AdminLogsListAction } from './actions/admin-logs-list.action';
import { AdminLogsController } from './admin-logs.controller';
import { AdminLogsService } from './admin-logs.service';
import { GeoLocationService } from './services/geo-location.service';

@Module({
imports: [RedisModule, AdminAuthModule],
controllers: [AdminLogsController],
providers: [AdminLogsService, AdminLogsListAction],
providers: [AdminLogsService, AdminLogsListAction, GeoLocationService],
})
export class AdminLogsModule {}
16 changes: 13 additions & 3 deletions src/modules/admin/logs/admin-logs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import * as SYS_MSG from '../../../constants/system.messages';
import { AdminLogsListAction, RawAdminLogRow } from './actions/admin-logs-list.action';
import { GetAdminLogsQueryDto } from './dto/get-admin-logs-query.dto';
import { AdminLogItem, AdminLogsListMeta, AdminLogsListResponse } from './interfaces/admin-logs.interfaces';
import { GeoLocationService } from './services/geo-location.service';
import { formatDevice } from './utils/parse-user-agent.util';

const MAX_PER_PAGE = 50;
const DEFAULT_PAGE = 1;
Expand All @@ -13,7 +15,10 @@ const DATE_ONLY_LENGTH = 10;

@Injectable()
export class AdminLogsService {
constructor(private readonly adminLogsListAction: AdminLogsListAction) {}
constructor(
private readonly adminLogsListAction: AdminLogsListAction,
private readonly geoLocationService: GeoLocationService,
) {}

/** Returns the paginated, filtered audit-log feed, newest first. */
async listLogs(dto: GetAdminLogsQueryDto): Promise<AdminLogsListResponse> {
Expand Down Expand Up @@ -49,11 +54,14 @@ export class AdminLogsService {
...(capped ? { capped: true } : {}),
};

return { data: rows.map((row) => this.toLogItem(row)), meta };
// Resolve every row's location in one deduplicated pass before mapping.
const locations = await this.geoLocationService.resolveMany(rows.map((row) => row.log_ip_address));

return { data: rows.map((row, index) => this.toLogItem(row, locations[index])), meta };
}

/** Maps a raw joined row to the FR-3 response shape (EC-01: never a null reference). */
private toLogItem(row: RawAdminLogRow): AdminLogItem {
private toLogItem(row: RawAdminLogRow, location: string | null): AdminLogItem {
return {
id: row.log_id,
user_id: row.log_user_id,
Expand All @@ -62,6 +70,8 @@ export class AdminLogsService {
action_type: row.log_action_type,
description: row.log_description,
ip_address: row.log_ip_address,
location,
device: formatDevice(row.log_user_agent),
created_at: row.log_created_at,
status: row.log_status,
};
Expand Down
11 changes: 9 additions & 2 deletions src/modules/admin/logs/docs/admin-logs-swagger.doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ export function GetAdminLogsDocs(): ReturnType<typeof applyDecorators> {
'Returns the paginated audit trail of user and system activity, newest first. ' +
'Filter by action_type, status and created_at date range; search matches the ' +
'acting user by full_name or email. Entries whose user was deleted display ' +
'`Deleted User` with a null email. per_page values above 50 are silently ' +
'capped and flagged via `meta.capped`. Requires a valid admin JWT.',
'`Deleted User` with a null email. `location` is derived from `ip_address` ' +
'(format `Region, CC`) and `device` is parsed from the captured user agent ' +
'(format `Browser Major · OS Version`); either is null when it cannot be ' +
'resolved. per_page values above 50 are silently capped and flagged via ' +
'`meta.capped`. Requires a valid admin JWT.',
}),
ApiOkResponse({
description: 'Logs retrieved successfully',
Expand All @@ -37,6 +40,8 @@ export function GetAdminLogsDocs(): ReturnType<typeof applyDecorators> {
action_type: 'login',
description: 'User logged in',
ip_address: '102.89.33.21',
location: 'Lagos, NG',
device: 'Chrome 134 · macOS 10.15.7',
created_at: '2026-06-06T09:15:00.000Z',
status: 'success',
},
Expand All @@ -48,6 +53,8 @@ export function GetAdminLogsDocs(): ReturnType<typeof applyDecorators> {
action_type: 'account_deleted',
description: 'User deleted their account',
ip_address: '102.89.33.22',
location: 'Abuja, NG',
device: 'Safari 17 · iOS 17.1',
created_at: '2026-06-05T18:42:00.000Z',
status: 'success',
},
Expand Down
4 changes: 4 additions & 0 deletions src/modules/admin/logs/entities/admin-log.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export class AdminLog {
@Column({ type: 'varchar', length: 45, nullable: true })
ip_address: string | null;

/** Raw User-Agent header captured at write time; parsed into a device label on read. */
@Column({ type: 'varchar', length: 512, nullable: true })
user_agent: string | null;

@Index()
@Column({ type: 'varchar', length: 10 })
status: AdminLogStatus;
Expand Down
4 changes: 4 additions & 0 deletions src/modules/admin/logs/interfaces/admin-logs.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ export interface AdminLogItem {
action_type: AdminLogActionType;
description: string;
ip_address: string | null;
/** "Region, CC" derived from ip_address, or null when it cannot be resolved. */
location: string | null;
/** "Browser Major · OS Version" parsed from the stored user agent, or null. */
device: string | null;
created_at: Date;
status: AdminLogStatus;
}
Expand Down
113 changes: 113 additions & 0 deletions src/modules/admin/logs/services/geo-location.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { Injectable, Logger } from '@nestjs/common';

/** Shape of the fields we read from the keyless geo-IP endpoint (freeipapi.com). */
interface GeoLookupResponse {
regionName?: string;
countryCode?: string;
}

/**
* Resolves an IP address to a compact "Region, CC" label (for example "Lagos, NG")
* for the admin logs feed.
*
* Uses freeipapi.com, a keyless HTTPS geo-IP endpoint, over the built-in fetch.
* The offline geo-IP database that would have made this dependency-free of a
* network call is a new package, which the team blocks, so we look it up at read
* time instead. Results are cached per IP for the process lifetime, and every
* failure path degrades to null so the logs endpoint never fails when lookup is
* unavailable.
*/
@Injectable()
export class GeoLocationService {
private readonly logger = new Logger(GeoLocationService.name);
private readonly cache = new Map<string, string | null>();

private static readonly ENDPOINT = 'https://freeipapi.com/api/json';
private static readonly LOOKUP_TIMEOUT_MS = 2000;

/** Resolves a single IP, using and populating the per-process cache. */
async resolve(ip: string | null): Promise<string | null> {
if (!ip || this.isNonRoutable(ip)) {
return null;
}

const cached = this.cache.get(ip);
if (cached !== undefined) {
return cached;
}

const location = await this.lookup(ip);
this.cache.set(ip, location);
return location;
}

/**
* Resolves many IPs at once, deduplicating lookups, and returns labels aligned
* one-to-one with the input order (null entries stay null).
*/
async resolveMany(ips: Array<string | null>): Promise<Array<string | null>> {
const unique = [...new Set(ips.filter((ip): ip is string => Boolean(ip)))];
await Promise.all(unique.map((ip) => this.resolve(ip)));
return ips.map((ip) => (ip ? (this.cache.get(ip) ?? null) : null));
}

private async lookup(ip: string): Promise<string | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), GeoLocationService.LOOKUP_TIMEOUT_MS);

try {
const response = await fetch(`${GeoLocationService.ENDPOINT}/${ip}`, {
signal: controller.signal,
});

if (!response.ok) {
return null;
}

const body = (await response.json()) as GeoLookupResponse;
return this.format(body);
} catch (error: unknown) {
const detail = error instanceof Error ? error.message : String(error);
this.logger.warn(`Geo lookup failed for ${ip}: ${detail}`);
return null;
} finally {
clearTimeout(timer);
}
}

private format(body: GeoLookupResponse): string | null {
const region = this.clean(body.regionName);
const country = this.clean(body.countryCode);

if (!country) {
return null;
}

return region ? `${region}, ${country}` : country;
}

/** Normalises a field, treating blanks and the provider's "-"/"Unknown" as absent. */
private clean(value: string | undefined): string | null {
const trimmed = value?.trim();

if (!trimmed || trimmed === '-' || trimmed.toLowerCase() === 'unknown') {
return null;
}

return trimmed;
}

/** Private, loopback and link-local addresses have no public geolocation. */
private isNonRoutable(ip: string): boolean {
return (
ip === '127.0.0.1' ||
ip === '::1' ||
ip.startsWith('10.') ||
ip.startsWith('192.168.') ||
ip.startsWith('169.254.') ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(ip) ||
ip.startsWith('fc') ||
ip.startsWith('fd')
);
Comment thread
ibraheembello marked this conversation as resolved.
}
}
2 changes: 2 additions & 0 deletions src/modules/admin/logs/tests/admin-logs.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const MOCK_LIST_RESPONSE = {
action_type: AdminLogActionType.LOGIN,
description: 'User logged in',
ip_address: '102.89.33.21',
location: 'Lagos, NG',
device: 'Chrome 134 · macOS 10.15.7',
created_at: new Date('2026-06-06T09:15:00.000Z'),
status: AdminLogStatus.SUCCESS,
},
Expand Down
Loading
Loading