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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"start": "node dist/server.js",
"start:worker": "node dist/workers/index.js",
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"lint": "eslint . --max-warnings=0",
"lint:fix": "eslint . --fix",
"audit": "pnpm audit --audit-level=high",
"format": "prettier --write .",
Expand Down
14 changes: 2 additions & 12 deletions src/modules/admin/interface/routes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
import { authenticate, ok, requireRole } from '../../../shared/http/index.js';
import { UnauthorizedError } from '../../../shared/errors/index.js';
import { authenticate, ok, requireRole, requireUser } from '../../../shared/http/index.js';
import type { AdminUser, AuditLogEntry, DisputeReviewItem } from '../domain/index.js';
import type {
createListAuditLogUseCase,
Expand Down Expand Up @@ -49,15 +48,6 @@ function serializeAuditLogEntry(entry: AuditLogEntry) {
};
}

function requireUserId(request: { user?: { id: string } }): string {
if (!request.user) {
// Unreachable in practice — every route below attaches `authenticate`
// as a preHandler, which throws before a handler body ever runs.
throw new UnauthorizedError('Authentication required');
}
return request.user.id;
}

const adminOnly = [authenticate, requireRole('ADMIN')];

export function createAdminRoutes(useCases: AdminUseCases): FastifyPluginAsyncZod {
Expand Down Expand Up @@ -92,7 +82,7 @@ export function createAdminRoutes(useCases: AdminUseCases): FastifyPluginAsyncZo
},
async (request, reply) => {
const user = await useCases.updateUserRole({
actorId: requireUserId(request),
actorId: requireUser(request).id,
userId: request.params.id,
role: request.body.role,
});
Expand Down
28 changes: 8 additions & 20 deletions src/modules/deliveries/application/sync-delivery-from-event.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress, parseBigIntId } from '../../../shared/events/index.js';
import type { DeliveryContractReader, DeliveryRepository } from '../domain/index.js';

export interface SyncDeliveryFromEventDeps {
Expand Down Expand Up @@ -29,15 +30,15 @@ export function createSyncDeliveryFromEventUseCase(deps: SyncDeliveryFromEventDe

switch (topic) {
case 'delivery_created': {
const chainDeliveryId = parseDeliveryId(payload[0]);
const chainDeliveryId = parseBigIntId(payload[0]);
if (chainDeliveryId === null) return;
const record = await deps.contractReader.getDelivery(chainDeliveryId);
await deps.deliveryRepository.create(record);
return;
}

case 'driver_assigned': {
const chainDeliveryId = parseDeliveryId(payload[0]);
const chainDeliveryId = parseBigIntId(payload[0]);
const driverAddress = parseAddress(payload[1]);
if (chainDeliveryId === null || driverAddress === null) return;
await deps.deliveryRepository.updateStatus(chainDeliveryId, {
Expand All @@ -48,7 +49,7 @@ export function createSyncDeliveryFromEventUseCase(deps: SyncDeliveryFromEventDe
}

case 'DeliveryInTransit': {
const chainDeliveryId = parseDeliveryId(payload[0]);
const chainDeliveryId = parseBigIntId(payload[0]);
if (chainDeliveryId === null) return;
await deps.deliveryRepository.updateStatus(chainDeliveryId, {
status: 'IN_TRANSIT',
Expand All @@ -58,7 +59,7 @@ export function createSyncDeliveryFromEventUseCase(deps: SyncDeliveryFromEventDe
}

case 'delivery_confirmed': {
const chainDeliveryId = parseDeliveryId(payload[0]);
const chainDeliveryId = parseBigIntId(payload[0]);
if (chainDeliveryId === null) return;
// The on-chain event carries no timestamp of its own — the
// indexer's ledger-close time is the best available on-chain
Expand All @@ -71,14 +72,14 @@ export function createSyncDeliveryFromEventUseCase(deps: SyncDeliveryFromEventDe
}

case 'delivery_cancelled': {
const chainDeliveryId = parseDeliveryId(payload[0]);
const chainDeliveryId = parseBigIntId(payload[0]);
if (chainDeliveryId === null) return;
await deps.deliveryRepository.updateStatus(chainDeliveryId, { status: 'CANCELLED' });
return;
}

case 'delivery_disputed': {
const chainDeliveryId = parseDeliveryId(payload[0]);
const chainDeliveryId = parseBigIntId(payload[0]);
if (chainDeliveryId === null) return;
await deps.deliveryRepository.updateStatus(chainDeliveryId, { status: 'DISPUTED' });
return;
Expand All @@ -91,17 +92,4 @@ export function createSyncDeliveryFromEventUseCase(deps: SyncDeliveryFromEventDe
return;
}
};
}

function parseDeliveryId(value: unknown): bigint | null {
if (typeof value !== 'string' && typeof value !== 'number') return null;
try {
return BigInt(value);
} catch {
return null;
}
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
}
18 changes: 3 additions & 15 deletions src/modules/disputes/application/sync-dispute-from-event.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress, parseBigIntId } from '../../../shared/events/index.js';
import type { DisputeEscrowStateReader, DisputeRepository } from '../domain/index.js';

export interface SyncDisputeFromEventDeps {
Expand Down Expand Up @@ -120,7 +121,7 @@ async function handleEscrowEvent(
// not the tuple-wrapped DeliveryId dispute_resolution_contract uses —
// verified against escrow_contract/lib.rs (same convention the `escrow`
// module's own handler relies on).
const chainDeliveryId = parseBareDeliveryId(event.topic[1]);
const chainDeliveryId = parseBigIntId(event.topic[1]);
if (chainDeliveryId === null) return;

if (event.topic[0] === 'delivery_disputed') {
Expand Down Expand Up @@ -250,18 +251,5 @@ function parseTupleWrappedDeliveryId(value: unknown): bigint | null {
return null;
}
if (!Array.isArray(parsed) || parsed.length !== 1) return null;
return parseBareDeliveryId(parsed[0]);
}

function parseBareDeliveryId(value: unknown): bigint | null {
if (typeof value !== 'string' && typeof value !== 'number') return null;
try {
return BigInt(value);
} catch {
return null;
}
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
return parseBigIntId(parsed[0]);
}
16 changes: 1 addition & 15 deletions src/modules/disputes/interface/routes.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
import { authenticate, ok } from '../../../shared/http/index.js';
import { UnauthorizedError } from '../../../shared/errors/index.js';
import { authenticate, ok, requireUser } from '../../../shared/http/index.js';
import type { EvidenceWithVerification, GetDisputeResult } from '../application/index.js';
import type { UserRole } from '../domain/index.js';
import type {
createBuildDisputeTransactionsUseCases,
createDownloadEvidenceUseCase,
Expand Down Expand Up @@ -58,18 +56,6 @@ function serializeDispute(result: GetDisputeResult) {
};
}

function requireUser(request: { user?: { id: string; role: UserRole } }): {
id: string;
role: UserRole;
} {
if (!request.user) {
// Unreachable in practice — both routes below attach `authenticate` as
// a preHandler, which throws before a handler body ever runs.
throw new UnauthorizedError('Authentication required');
}
return request.user;
}

export function createDisputeRoutes(useCases: DisputeUseCases, config: DisputeRoutesConfig): FastifyPluginAsyncZod {
const uploadEvidenceBodySchemaWithLimit = createUploadEvidenceBodySchema(config.evidenceMaxBytes);
return async function disputeRoutes(app) {
Expand Down
16 changes: 2 additions & 14 deletions src/modules/escrow/application/sync-escrow-from-event.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress, parseBigIntId } from '../../../shared/events/index.js';
import type { EscrowContractReader, EscrowRepository } from '../domain/index.js';

export interface SyncEscrowFromEventDeps {
Expand Down Expand Up @@ -28,7 +29,7 @@ export function createSyncEscrowFromEventUseCase(deps: SyncEscrowFromEventDeps)
}

const eventName = event.topic[0];
const chainDeliveryId = parseDeliveryId(event.topic[1]);
const chainDeliveryId = parseBigIntId(event.topic[1]);
if (chainDeliveryId === null) return;

const payload = Array.isArray(event.payload) ? event.payload : [];
Expand Down Expand Up @@ -95,19 +96,6 @@ export function createSyncEscrowFromEventUseCase(deps: SyncEscrowFromEventDeps)
};
}

function parseDeliveryId(value: unknown): bigint | null {
if (typeof value !== 'string' && typeof value !== 'number') return null;
try {
return BigInt(value);
} catch {
return null;
}
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}

function parseAmount(value: unknown): bigint | null {
if (typeof value !== 'string' && typeof value !== 'number') return null;
try {
Expand Down
16 changes: 2 additions & 14 deletions src/modules/fleet/application/sync-fleet-from-event.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress, parseBigIntId } from '../../../shared/events/index.js';
import type { FleetRepository } from '../domain/index.js';

export interface SyncFleetFromEventDeps {
Expand Down Expand Up @@ -28,7 +29,7 @@ export function createSyncFleetFromEventUseCase(deps: SyncFleetFromEventDeps) {

const eventName = event.topic[0];
const payload = Array.isArray(event.payload) ? event.payload : [];
const chainFleetId = parseFleetId(payload[0]);
const chainFleetId = parseBigIntId(payload[0]);
if (chainFleetId === null) return;

switch (eventName) {
Expand Down Expand Up @@ -76,16 +77,3 @@ export function createSyncFleetFromEventUseCase(deps: SyncFleetFromEventDeps) {
}
};
}

function parseFleetId(value: unknown): bigint | null {
if (typeof value !== 'string' && typeof value !== 'number') return null;
try {
return BigInt(value);
} catch {
return null;
}
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress } from '../../../shared/events/index.js';
import type { ActorActivityRepository, RecordActivityInput } from '../domain/index.js';

export interface RecordActorActivityFromEventDeps {
Expand Down Expand Up @@ -72,7 +73,3 @@ function resolveActivity(event: BlockchainEventEnvelope): RecordActivityInput |
return null;
}
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress, parseBigIntId } from '../../../shared/events/index.js';
import { logger } from '../../../shared/logger/index.js';
import type {
DeliveryParties,
Expand Down Expand Up @@ -256,13 +257,11 @@ async function resolveCandidates(
}
}

/** Same numeric encoding as {@link parseBigIntId}, but notifications keys its
* read model by the decimal *string* form of the id. */
function parseId(value: unknown): string | null {
if (typeof value !== 'string' && typeof value !== 'number') return null;
try {
return BigInt(value).toString();
} catch {
return null;
}
const parsed = parseBigIntId(value);
return parsed === null ? null : parsed.toString();
}

/** `dispute_resolution_contract`'s tuple-wrapped `DeliveryId` arrives as the
Expand All @@ -279,7 +278,3 @@ function parseTupleWrappedId(value: unknown): string | null {
if (!Array.isArray(parsed) || parsed.length !== 1) return null;
return parseId(parsed[0]);
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
18 changes: 3 additions & 15 deletions src/modules/notifications/interface/routes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
import { authenticate, ok } from '../../../shared/http/index.js';
import { UnauthorizedError } from '../../../shared/errors/index.js';
import { authenticate, ok, requireUser } from '../../../shared/http/index.js';
import type { Notification } from '../domain/index.js';
import type {
createGetNotificationUseCase,
Expand Down Expand Up @@ -30,17 +29,6 @@ function serializeNotification(notification: Notification) {
};
}

function requireUserId(request: { user?: { id: string } }): string {
if (!request.user) {
// Unreachable in practice — both routes below attach `authenticate` as
// a preHandler, which throws before a handler body ever runs. This
// exists so `request.user.id` is never accessed through a non-null
// assertion further down (same pattern as `users/interface/routes.ts`).
throw new UnauthorizedError('Authentication required');
}
return request.user.id;
}

export function createNotificationsRoutes(useCases: NotificationsUseCases): FastifyPluginAsyncZod {
return async function notificationsRoutes(app) {
app.get(
Expand All @@ -56,7 +44,7 @@ export function createNotificationsRoutes(useCases: NotificationsUseCases): Fast
async (request, reply) => {
const { status, limit, before } = request.query;
const { items, nextCursor, limit: appliedLimit } = await useCases.listNotifications({
userId: requireUserId(request),
userId: requireUser(request).id,
...(status && { status }),
...(limit !== undefined && { limit }),
...(before !== undefined && { before }),
Expand All @@ -79,7 +67,7 @@ export function createNotificationsRoutes(useCases: NotificationsUseCases): Fast
},
async (request, reply) => {
const notification = await useCases.getNotification({
userId: requireUserId(request),
userId: requireUser(request).id,
notificationId: request.params.id,
});
void reply.status(200).send(ok(serializeNotification(notification)));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockchainEventEnvelope } from '../../../shared/events/index.js';
import { parseAddress } from '../../../shared/events/index.js';
import { logger } from '../../../shared/logger/index.js';
import type {
DriverProfileRepository,
Expand Down Expand Up @@ -95,7 +96,3 @@ async function refreshDriverProfile(

await deps.driverProfileRepository.upsert(address, fields);
}

function parseAddress(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
Loading
Loading