Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adds more reporting data #733

Merged
merged 1 commit into from
Jan 29, 2025
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
4 changes: 3 additions & 1 deletion apps/api/src/auth/services/auth.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,16 @@ export class AuthInterceptor implements HonoInterceptor {
if (anonymousUserId) {
const currentUser = await this.userRepository.findAnonymousById(anonymousUserId);
await this.auth(currentUser);
c.set("user", currentUser);
return await next();
}

const userId = bearer && (await this.getValidUserId(bearer, c));

if (userId) {
const currentUser = await this.userRepository.findByUserId(userId);
this.auth(currentUser);
await this.auth(currentUser);
c.set("user", currentUser);
return await next();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,24 @@
import { singleton } from "tsyringe";
import { ZodError } from "zod";

import { AuthService } from "@src/auth/services/auth.service";
import { InjectSentry, Sentry } from "@src/core/providers/sentry.provider";
import { SentryEventService } from "@src/core/services/sentry-event/sentry-event.service";
import { ClientInfoContextVariables } from "@src/middlewares/clientInfoMiddleware";

@singleton()
export class HonoErrorHandlerService {
private readonly logger = LoggerService.forContext("ErrorHandler");

constructor(
@InjectSentry() private readonly sentry: Sentry,
private readonly sentryEventService: SentryEventService
private readonly sentryEventService: SentryEventService,
private readonly authService: AuthService
) {
this.handle = this.handle.bind(this);
}

async handle<E extends Env = any>(error: Error, c: Context<E>): Promise<Response> {

Check warning on line 27 in apps/api/src/core/services/hono-error-handler/hono-error-handler.service.ts

View workflow job for this annotation

GitHub Actions / validate-n-build

Unexpected any. Specify a different type
this.logger.error(error);

if (isHttpError(error)) {
Expand All @@ -47,13 +50,34 @@
}
}

private async getSentryEvent<E extends Env = any>(error: Error, c: Context<E>): Promise<Event> {
private async getSentryEvent<
E extends {
Variables: ClientInfoContextVariables;
} = any
>(error: Error, c: Context<E>): Promise<Event> {
const event = this.sentry.addRequestDataToEvent(this.sentryEventService.toEvent(error), {
method: c.req.method,
url: c.req.url,
headers: omit(Object.fromEntries(c.req.raw.headers), ["x-anonymous-user-id"]),
body: await this.getSentryEventRequestBody(c)
});

const { currentUser } = this.authService;

if (currentUser) {
event.user = {
id: currentUser.id
};
}

const clientInfo = c.get("clientInfo");

if (clientInfo) {
event.fingerprint = [clientInfo.fingerprint];
event.user = event.user || {};
event.user.ip_address = clientInfo.ip;
}

const currentSpan = trace.getSpan(context.active());

if (currentSpan) {
Expand Down
54 changes: 43 additions & 11 deletions apps/api/src/core/services/http-logger/http-logger.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ import { singleton } from "tsyringe";

import type { HonoInterceptor } from "@src/core/types/hono-interceptor.type";

type HttpRequestLog = {
httpRequest: {
requestMethod: string;
requestUrl: string;
status: number;
userAgent?: string;
referrer?: string;
protocol?: string;
remoteIp?: string;
duration: string;
};
fingerprint?: string;
userId?: string;
};

@singleton()
export class HttpLoggerService implements HonoInterceptor {
private readonly logger = LoggerService.forContext("HTTP");
Expand All @@ -12,18 +27,35 @@ export class HttpLoggerService implements HonoInterceptor {
return async (c: Context, next: Next) => {
const timer = performance.now();

await next();
this.logger.info({
httpRequest: {
requestMethod: c.req.method,
requestUrl: c.req.url,
status: c.res.status,
userAgent: c.req.header("user-agent"),
referrer: c.req.raw.referrer,
protocol: c.req.header("x-forwarded-proto"),
duration: `${(performance.now() - timer).toFixed(3)}ms`
try {
await next();
} finally {
const clientInfo = c.get("clientInfo");
const currentUser = c.get("user");

const log: HttpRequestLog = {
httpRequest: {
requestMethod: c.req.method,
requestUrl: c.req.url,
status: c.res.status,
referrer: c.req.raw.referrer,
protocol: c.req.header("x-forwarded-proto"),
duration: `${(performance.now() - timer).toFixed(3)}ms`
}
};

if (clientInfo) {
log.httpRequest.userAgent = clientInfo.userAgent;
ygrishajev marked this conversation as resolved.
Show resolved Hide resolved
log.httpRequest.remoteIp = clientInfo.ip;
log.fingerprint = clientInfo.fingerprint;
}
});

if (currentUser) {
log.userId = currentUser.id;
}

this.logger.info(log);
}
};
}
}
12 changes: 5 additions & 7 deletions apps/api/src/middlewares/clientInfoMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ import { createMiddleware } from "hono/factory";
import { getSentry } from "@src/core/providers/sentry.provider";

export type ClientInfoContextVariables = {
clientInfo:
| {
ip: string;
userAgent: string | undefined;
fingerprint: string | undefined;
}
| undefined;
clientInfo?: {
ip: string;
userAgent: string | undefined;
fingerprint: string | undefined;
};
};

export const clientInfoMiddleware = createMiddleware<{
Expand Down
Loading