Compare commits

..

6 Commits

54 changed files with 1194 additions and 148 deletions

View File

@@ -43,7 +43,7 @@ QR + URL for **sent** cases and started lab-origin cases; focus page `/lab-case/
## API errors
Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `getUserFacingError`. Unexpected 500s / client crashes: GlitchTip via Sentry SDKs (`SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN`). Skill: `.cursor/skills/api-errors/SKILL.md`. Appointments/working hours: client IANA `timeZone` (never Node local `getHours()`).
Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `getUserFacingError`. Unexpected 500s / client crashes: GlitchTip via Sentry SDKs (`SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN`) — one failure, one event, and each 5xx wrapper passes `{ cause }`. Rule: `.cursor/rules/error-tracking.mdc`. Skill: `.cursor/skills/api-errors/SKILL.md`. Appointments/working hours: client IANA `timeZone` (never Node local `getHours()`).
## Notifications (inbox + live tabs)

View File

@@ -1,20 +1,31 @@
---
description: GlitchTip error tracking via Sentry SDKs — 500s only, no PHI
description: GlitchTip error tracking via Sentry SDKs — one failure one event, cause on each 5xx wrapper, no PHI
alwaysApply: true
---
# Error tracking (GlitchTip)
Self-hosted GlitchTip at `https://errors.wixur.ir`. Apps use official Sentry SDKs (`@sentry/nestjs`, `@sentry/nextjs`) pointed at that DSN — not sentry.io.
Self-hosted GlitchTip at `https://errors.wixur.ir`. Apps use official Sentry SDKs (`@sentry/nestjs`, `@sentry/nextjs`) pointed at that DSN — not sentry.io. SDK stays on **10.x**: GlitchTip ignores `span` items, and SDK 11 streams spans by default.
## What to report
- Backend: HTTP **500+** in `HttpExceptionFilter` only. Do **not** send `AppException` 4xx.
- Frontend: render crashes (`error.tsx` / `global-error.tsx`) and axios **5xx / network** failures only.
- No session replay. Scrub cookies, JWT, request bodies, emails.
- **One failure, one event.** Backend: HTTP 5xx in `HttpExceptionFilter`. Frontend: only failures that have no backend event — no response (network, timeout), or a 5xx without a backend error body (`reportUnexpectedApiFailure.ts`). The frontend does not report a backend 5xx, a 4xx, or a canceled request.
- A 5xx wrapper passes the original error: `new InternalServerErrorException('…', { cause: error })`, `new AppException(code, status, undefined, cause)`. A `catch` lets an `HttpException` pass first.
- Work that runs detached from the response uses `reportBackgroundFailure(task, error)` (`common/observability/report-failure.ts`), or `notifyInBackground(...)` for inbox notifications. Never `.catch(() => undefined)` on work that matters. A `catch` that logs and continues uses `reportHandledFailure(operation, error)`.
- Frontend: a caught error that is not an `ApiError` is a bug. `getUserFacingError` reports it once per error object. `Button` reports a rejected `onClick`. `error.tsx` / `global-error.tsx` capture only an error without a `digest` (the server already sent that one).
- No session replay. No `tracesSampleRate` yet (spans are a later step): errors still share a `trace_id`.
## Context on each event
`SentryContextInterceptor` (backend) and `useAuth` (frontend) set `user.id` and `organization_id`; the frontend also sets `organization_type` and `route`. `beforeSend` adds `http_status` and `error_code`, and names an `AppException` by its code.
## No sensitive data
`beforeSend` / `beforeBreadcrumb` (`backend/src/common/observability/sentry-options.ts`, `frontend/src/lib/error-tracking/sentrySharedOptions.ts`) remove cookies, JWT, request bodies, query strings, share-link tokens, emails, mobile numbers, and IP addresses. Never log an OTP code, API key, token, or patient data: console output becomes a breadcrumb. Nest `Logger` is **not** connected to Sentry (one log line prints the voice transcript) — keep it that way.
## Config
- Backend DSN: `SENTRY_DSN` in `backend.env` / `backend.staging.env` (runtime).
- Frontend DSN: `NEXT_PUBLIC_SENTRY_DSN` baked at Docker build (Gitea var `NEXT_PUBLIC_SENTRY_DSN`).
- Backend DSN: `SENTRY_DSN` in `backend.env` / `backend.staging.env` (runtime). Release: `SENTRY_RELEASE` = image tag.
- Frontend DSN: `NEXT_PUBLIC_SENTRY_DSN` baked at Docker build (Gitea var). Release: `SENTRY_RELEASE` build arg.
- Source maps: Gitea secret `SENTRY_AUTH_TOKEN` + vars `SENTRY_ORG`, `SENTRY_PROJECT_BACKEND`, `SENTRY_PROJECT_FRONTEND`. The token needs the scopes `org:read`, `project:read`, `project:releases`. Empty = no upload, and the build continues.
- Empty DSN = tracking off (local default).

View File

@@ -33,6 +33,17 @@ catch (err: unknown) {
3. Do not use `err.message` or `(err as Error).message` for user display.
## Unexpected errors (5xx)
Rule: `.cursor/rules/error-tracking.mdc`.
1. Let an `HttpException` pass first: `if (error instanceof HttpException) { throw error; }`
2. Wrap with the cause: `new InternalServerErrorException('What failed', { cause: error })` or `new AppException(code, status, undefined, error)`. A wrapper without the cause hides the real error from the tracker.
3. Give each wrapper its own message. Two causes with one message make one issue in GlitchTip.
4. Work that is not awaited: `reportBackgroundFailure('task-name', error)` — never an unhandled rejection or `.catch(() => undefined)`.
5. A `catch` that logs and continues: `reportHandledFailure('operation', error)`.
6. Log with `this.logger`, not `console`. Never log a secret or patient data.
## Axios shape
Parsed in `lib/api/client` — expects `{ success: false, error: { code, details? } }`.

View File

@@ -11,6 +11,9 @@
# CLONE_HOST git clone, e.g. 127.0.0.1:3000
# COM_PUBLIC_BASE_URL https://nudentic.com (required; no trailing slash)
# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN
# SENTRY_ORG, SENTRY_PROJECT_BACKEND, SENTRY_PROJECT_FRONTEND
# GlitchTip slugs for the source map upload (empty = no upload).
# Secret SENTRY_AUTH_TOKEN: GlitchTip auth token for that upload.
# NODE_IMAGE_SOURCE extra base-image ref(s) for seed/resolve
# NPM_REGISTRY default http://host.docker.internal:4873
# PROD_REGISTRY_HOST Linux pull host, e.g. wixur.ir:3000
@@ -128,6 +131,10 @@ jobs:
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Build and push backend (:tag-com only)
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_BACKEND }}
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:COM_IMAGE_TAG
@@ -151,6 +158,9 @@ jobs:
--add-host "host.docker.internal:host-gateway" `
--build-arg "NODE_IMAGE=$nodeImage" `
--build-arg "NPM_REGISTRY=$npmReg" `
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
-t "$prefix/dyolink-backend:$tag" ./backend
if ($LASTEXITCODE -eq 0) { $ok = $true; break }
if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) }
@@ -163,6 +173,9 @@ jobs:
env:
COM_PUBLIC_BASE_URL: ${{ vars.COM_PUBLIC_BASE_URL }}
NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_FRONTEND }}
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:COM_IMAGE_TAG
@@ -194,6 +207,10 @@ jobs:
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
--build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
--build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=production" `
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
--build-arg "SENTRY_RELEASE=$tag" `
--build-arg "NODE_IMAGE=$nodeImage" `
--build-arg "NPM_REGISTRY=$npmReg" `
-t "$prefix/dyolink-frontend:$tag" `

View File

@@ -13,12 +13,15 @@
# CLONE_HOST git clone, e.g. 127.0.0.1:3000
# PROD_PUBLIC_BASE_URL https://nudentic.ir (no trailing slash)
# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN
# SENTRY_ORG, SENTRY_PROJECT_BACKEND, SENTRY_PROJECT_FRONTEND
# GlitchTip slugs for the source map upload (empty = no upload)
# NODE_IMAGE_SOURCE extra base-image ref(s) for seed/resolve
# NPM_REGISTRY default http://host.docker.internal:4873 (Verdaccio on Windows)
# PROD_REGISTRY_HOST Linux pull host, e.g. wixur.ir:3000 (HTTP; insecure-registries on the VPS)
# PROD_INFRA_DIR /opt/dyolink/infrastructure
#
# Secrets (in addition to REGISTRY_USERNAME / REGISTRY_PASSWORD):
# SENTRY_AUTH_TOKEN GlitchTip auth token for the source map upload (optional)
# PROD_SSH_HOST Linux public IP or hostname
# PROD_SSH_USER e.g. dyolink
# PROD_SSH_KEY OpenSSH private key (full PEM)
@@ -151,6 +154,10 @@ jobs:
- name: Build and push backend (tag only, not :latest)
if: steps.gate.outputs.skip != 'true'
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_BACKEND }}
run: |
$ErrorActionPreference = 'Stop'
$dispatchTag = '${{ github.event.inputs.tag }}'.Trim()
@@ -175,6 +182,9 @@ jobs:
--add-host "host.docker.internal:host-gateway" `
--build-arg "NODE_IMAGE=$nodeImage" `
--build-arg "NPM_REGISTRY=$npmReg" `
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
-t "$prefix/dyolink-backend:$tag" ./backend
if ($LASTEXITCODE -eq 0) { $ok = $true; break }
if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) }
@@ -188,6 +198,9 @@ jobs:
env:
PROD_PUBLIC_BASE_URL: ${{ vars.PROD_PUBLIC_BASE_URL }}
NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_FRONTEND }}
run: |
$ErrorActionPreference = 'Stop'
$dispatchTag = '${{ github.event.inputs.tag }}'.Trim()
@@ -218,6 +231,10 @@ jobs:
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
--build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
--build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=production" `
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
--build-arg "SENTRY_RELEASE=$tag" `
--build-arg "NODE_IMAGE=$nodeImage" `
--build-arg "NPM_REGISTRY=$npmReg" `
-t "$prefix/dyolink-frontend:$tag" `

View File

@@ -11,6 +11,9 @@
# REGISTRY_OWNER Gitea user or org that owns the packages
# PUBLIC_BASE_URL URL users open in the browser, e.g. http://wixur.ir (no trailing slash, no :8088)
# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN (https://…@errors.wixur.ir/…)
# SENTRY_ORG, SENTRY_PROJECT_BACKEND, SENTRY_PROJECT_FRONTEND
# GlitchTip slugs for the source map upload (empty = no upload).
# Secret SENTRY_AUTH_TOKEN: GlitchTip auth token for that upload.
# DEPLOY_SECRETS_DIR absolute path on runner, e.g. C:/dyolink/secrets
#
# Optional:
@@ -121,6 +124,10 @@ jobs:
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Build and push backend
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_BACKEND }}
run: |
$ErrorActionPreference = 'Stop'
$tag = "${{ github.sha }}".Substring(0, 7)
@@ -148,6 +155,9 @@ jobs:
--add-host "host.docker.internal:host-gateway" `
--build-arg "NODE_IMAGE=$nodeImage" `
--build-arg "NPM_REGISTRY=$npmReg" `
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
-t "$prefix/dyolink-backend:$tag" `
-t "$prefix/dyolink-backend:latest" `
./backend
@@ -164,6 +174,9 @@ jobs:
env:
PUBLIC_BASE_URL: ${{ vars.PUBLIC_BASE_URL }}
NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_FRONTEND }}
run: |
$ErrorActionPreference = 'Stop'
$tag = "${{ github.sha }}".Substring(0, 7)
@@ -191,6 +204,10 @@ jobs:
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
--build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
--build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=staging" `
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
--build-arg "SENTRY_RELEASE=$tag" `
--build-arg "NODE_IMAGE=$nodeImage" `
--build-arg "NPM_REGISTRY=$npmReg" `
-t "$prefix/dyolink-frontend:$tag" `

View File

@@ -96,7 +96,7 @@ backend/src/
prisma/ → schema, migrations, seed
```
Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpected 500s: GlitchTip (`SENTRY_DSN`). Never throw raw strings for user-facing failures.
Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpected 500s: GlitchTip (`SENTRY_DSN`) — one failure, one event; each 5xx wrapper passes `{ cause }` (rule: `.cursor/rules/error-tracking.mdc`). Never throw raw strings for user-facing failures.
**AdminJS:** Manual resource allowlist in `backend/src/admin/resources.ts`. **Whenever `schema.prisma` changes**, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite `@@id` must not be registered (list 500) — including `LabCaseAttachment`. Single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock` **are** registered. `LabCase.listedAt` is trigger-maintained (list/filter/show only; never write). Rule: `.cursor/rules/adminjs.mdc`.

View File

@@ -40,6 +40,20 @@ RUN npm run prisma:generate
RUN npm run build
RUN npm prune --omit=dev
# Source maps for GlitchTip (Debug IDs). Skipped without SENTRY_AUTH_TOKEN;
# a failed upload does not stop the build.
ARG SENTRY_AUTH_TOKEN
ARG SENTRY_URL=https://errors.wixur.ir
ARG SENTRY_ORG
ARG SENTRY_PROJECT
RUN if [ -z "$SENTRY_AUTH_TOKEN" ]; then \
echo "SENTRY_AUTH_TOKEN not set: skip source map upload"; \
else \
{ npm exec --yes --package=@sentry/cli@2.58.6 -- sentry-cli sourcemaps inject dist \
&& npm exec --yes --package=@sentry/cli@2.58.6 -- sentry-cli sourcemaps upload dist; } \
|| echo "WARN: source map upload failed; stack traces stay compiled"; \
fi
# ============================================
# STAGE 2: PRODUCTION STAGE

View File

@@ -28,6 +28,8 @@ import { VoiceModule } from './modules/voice/voice.module';
import { BillingModule } from './modules/billing/billing.module';
import { SubscriptionModule } from './modules/subscription/subscription.module';
import { SubscriptionWriteInterceptor } from './modules/subscription/subscription-write.interceptor';
import { SentryContextInterceptor } from './common/observability/sentry-context.interceptor';
import { SentryLifecycle } from './common/observability/sentry-lifecycle';
@Module({
imports: [
@@ -77,7 +79,10 @@ import { SubscriptionWriteInterceptor } from './modules/subscription/subscriptio
controllers: [AppController],
providers: [
AppService,
// First, so that its tags are on the scope for each later interceptor and handler.
{ provide: APP_INTERCEPTOR, useClass: SentryContextInterceptor },
{ provide: APP_INTERCEPTOR, useClass: SubscriptionWriteInterceptor },
SentryLifecycle,
],
})
export class AppModule {}

View File

@@ -11,7 +11,12 @@ export class AppException extends HttpException {
code: ErrorCodeValue,
status: HttpStatus,
details?: ValidationErrorDetail[] | unknown,
cause?: unknown,
) {
super({ code, details } satisfies AppErrorResponse, status);
super(
{ code, details } satisfies AppErrorResponse,
status,
cause === undefined ? undefined : { cause },
);
}
}

View File

@@ -0,0 +1,47 @@
import { Logger } from '@nestjs/common';
import * as Sentry from '@sentry/nestjs';
const fallbackLogger = new Logger('FailureReport');
function logFailure(
kind: string,
name: string,
error: unknown,
logger?: Logger,
context?: Record<string, string>,
): void {
const details =
context && Object.keys(context).length > 0
? ` ${JSON.stringify(context)}`
: '';
(logger ?? fallbackLogger).error(
`${kind} "${name}" failed${details}`,
error instanceof Error ? error.stack : String(error),
);
}
/** A failure of work that runs detached from the response (fire-and-forget calls, timers). */
export function reportBackgroundFailure(
task: string,
error: unknown,
logger?: Logger,
context?: Record<string, string>,
): void {
logFailure('Background task', task, error, logger, context);
Sentry.captureException(error, {
tags: { background_task: task, ...context },
});
}
/** A failure that the code handled (the user still gets a response) but that must be visible. */
export function reportHandledFailure(
operation: string,
error: unknown,
logger?: Logger,
context?: Record<string, string>,
): void {
logFailure('Handled failure', operation, error, logger, context);
Sentry.captureException(error, {
tags: { handled: 'true', operation, ...context },
});
}

View File

@@ -0,0 +1,32 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import * as Sentry from '@sentry/nestjs';
import { Observable } from 'rxjs';
type RequestWithUser = { user?: { id?: string; organizationId?: string } };
/**
* Puts the user and the organization of the request on each event.
* Runs after the guards, so `request.user` is set.
*/
@Injectable()
export class SentryContextInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const user = context
.switchToHttp()
.getRequest<RequestWithUser | undefined>()?.user;
if (user?.id) {
Sentry.setUser({ id: user.id });
if (user.organizationId) {
Sentry.setTag('organization_id', user.organizationId);
}
}
return next.handle();
}
}

View File

@@ -0,0 +1,10 @@
import { Injectable, type OnApplicationShutdown } from '@nestjs/common';
import * as Sentry from '@sentry/nestjs';
/** Drains the event queue on SIGTERM. Needs `app.enableShutdownHooks()`. */
@Injectable()
export class SentryLifecycle implements OnApplicationShutdown {
async onApplicationShutdown(): Promise<void> {
await Sentry.close(2000);
}
}

View File

@@ -0,0 +1,199 @@
import { HttpStatus, InternalServerErrorException } from '@nestjs/common';
import type { Breadcrumb, ErrorEvent } from '@sentry/core';
import { AppException } from '../errors/app.exception';
import { ErrorCode } from '../errors/error-codes';
import {
beforeSend,
buildSentryOptions,
filterBreadcrumb,
redactSensitiveText,
scrubUrl,
} from './sentry-options';
describe('sentry options', () => {
describe('scrubUrl', () => {
it('given a URL with a query string and a hash, when scrubUrl runs, then only the path stays', () => {
expect(scrubUrl('http://host/api/patients?q=0912&x=1#top')).toBe(
'http://host/api/patients',
);
});
it('given the path of a share link, when scrubUrl runs, then the token segment is masked', () => {
expect(
scrubUrl('http://host/api/lab-cases/access/abc123/tasks?x=1'),
).toBe('http://host/api/lab-cases/access/[token]/tasks');
});
});
describe('redactSensitiveText', () => {
it('given text with an email address and mobile numbers, when redactSensitiveText runs, then all are masked', () => {
expect(
redactSensitiveText('No user for a@b.co, 09120000000 or +989120000000'),
).toBe('No user for [email], [mobile] or [mobile]');
});
it('given text with ordinary numbers, when redactSensitiveText runs, then the numbers stay', () => {
expect(redactSensitiveText('status 500, id 123456789012')).toBe(
'status 500, id 123456789012',
);
});
});
describe('beforeSend', () => {
const makeEvent = () =>
({
exception: {
values: [{ type: 'AppException', value: 'App Exception' }],
},
request: {
url: 'http://host/api/lab-cases/access/abc?token=1',
query_string: 'token=1',
cookies: { accessToken: 'JWT' },
data: '{"password":"x"}',
headers: { cookie: 'a=b', authorization: 'Bearer x', host: 'host' },
},
user: {
id: 'u1',
email: 'a@b.co',
ip_address: '203.0.113.9',
username: 'amin',
},
tags: {},
}) as unknown as ErrorEvent;
it('given an event with cookies, body, query string, and user contact data, when beforeSend runs, then that data is gone', () => {
const result = beforeSend(makeEvent(), {
originalException: new Error('x'),
});
expect(result?.request).toEqual({
url: 'http://host/api/lab-cases/access/[token]',
headers: { host: 'host' },
});
expect(result?.user).toEqual({ id: 'u1' });
});
it('given an AppException with status 502, when beforeSend runs, then the exception is named by its error code and the status is tagged', () => {
const exception = new AppException(
ErrorCode.VOICE_EXTRACT_FAILED,
HttpStatus.BAD_GATEWAY,
);
const result = beforeSend(makeEvent(), { originalException: exception });
expect(result?.exception?.values?.[0].value).toBe('VOICE_EXTRACT_FAILED');
expect(result?.tags).toEqual({
http_status: '502',
error_code: 'VOICE_EXTRACT_FAILED',
});
});
it('given a Nest 5xx with its own message, when beforeSend runs, then the message stays and the status is tagged', () => {
const exception = new InternalServerErrorException(
'Failed to get profile',
);
const event = {
exception: { values: [{ type: 'Error', value: 'db down' }] },
tags: {},
} as unknown as ErrorEvent;
const result = beforeSend(event, { originalException: exception });
expect(result?.exception?.values?.[0].value).toBe('db down');
expect(result?.tags).toEqual({ http_status: '500' });
});
it('given an exception message with an email address and a mobile number, when beforeSend runs, then both are masked', () => {
const event = {
exception: {
values: [{ type: 'Error', value: 'No user a@b.co 09120000000' }],
},
} as unknown as ErrorEvent;
expect(
beforeSend(event, { originalException: new Error('x') })?.exception
?.values?.[0].value,
).toBe('No user [email] [mobile]');
});
it('given a route name with a share-link token, when beforeSend runs, then the token is masked', () => {
const event = {
transaction: 'GET /api/lab-cases/access/abc123/tasks',
} as unknown as ErrorEvent;
expect(
beforeSend(event, { originalException: new Error('x') })?.transaction,
).toBe('GET /api/lab-cases/access/[token]/tasks');
});
});
describe('filterBreadcrumb', () => {
it('given console output of level log or info in production, when the breadcrumb is filtered, then it is dropped', () => {
expect(
filterBreadcrumb(
{ category: 'console', level: 'log', message: 'x' },
true,
),
).toBeNull();
expect(
filterBreadcrumb(
{ category: 'console', level: 'info', message: 'x' },
true,
),
).toBeNull();
});
it('given console output of level log outside production, when the breadcrumb is filtered, then it stays', () => {
expect(
filterBreadcrumb(
{ category: 'console', level: 'log', message: 'x' },
false,
),
).not.toBeNull();
});
it('given console output of level error in production, when the breadcrumb is filtered, then it stays', () => {
expect(
filterBreadcrumb(
{ category: 'console', level: 'error', message: 'x' },
true,
),
).not.toBeNull();
});
it('given a request breadcrumb with a query string in its URL, when the breadcrumb is filtered, then the query string is gone', () => {
const breadcrumb = {
category: 'xhr',
level: 'info',
data: { url: '/api/patients?q=john' },
} as Breadcrumb;
filterBreadcrumb(breadcrumb, false);
expect(breadcrumb.data).toEqual({ url: '/api/patients' });
});
});
describe('buildSentryOptions', () => {
it('given no DSN, when the options are built, then the SDK is off and no tracing option is set', () => {
const options = buildSentryOptions({ NODE_ENV: 'production' });
expect(options.dsn).toBeUndefined();
expect(options.sendDefaultPii).toBe(false);
expect(options).not.toHaveProperty('tracesSampleRate');
expect(options).not.toHaveProperty('tracesSampler');
});
it('given a DSN, an environment, and a release, when the options are built, then all three are read', () => {
const options = buildSentryOptions({
NODE_ENV: 'production',
SENTRY_DSN: ' https://key@errors.example/1 ',
SENTRY_ENVIRONMENT: 'staging',
SENTRY_RELEASE: 'v1.2.3',
});
expect(options.dsn).toBe('https://key@errors.example/1');
expect(options.environment).toBe('staging');
expect(options.release).toBe('v1.2.3');
});
});
});

View File

@@ -0,0 +1,169 @@
import type { Breadcrumb, ErrorEvent, Event, EventHint } from '@sentry/core';
import type { NodeOptions } from '@sentry/nestjs';
type Env = Record<string, string | undefined>;
/** Path prefixes whose next segment is a secret token (lab case share links). */
const TOKEN_PATH_PREFIXES = ['/api/lab-cases/access/'];
const TOKEN_PATH_PATTERNS = TOKEN_PATH_PREFIXES.map(
(prefix) =>
new RegExp(
`(${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})[^/?#]+`,
'g',
),
);
const EMAIL_PATTERN = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
const MOBILE_PATTERN = /(?<![\d+])(?:\+98|0098)?0?9\d{9}(?!\d)/g;
const SENSITIVE_HEADERS = [
'cookie',
'Cookie',
'authorization',
'Authorization',
];
export function scrubUrl(url: string): string {
const [path] = url.split(/[?#]/);
return TOKEN_PATH_PATTERNS.reduce(
(value, pattern) => value.replace(pattern, '$1[token]'),
path,
);
}
// Exception messages can quote user input.
export function redactSensitiveText(text: string): string {
return text
.replace(EMAIL_PATTERN, '[email]')
.replace(MOBILE_PATTERN, '[mobile]');
}
function scrubRequest(event: Event): void {
const request = event.request as
| (Record<string, unknown> & {
url?: unknown;
headers?: Record<string, string>;
})
| undefined;
if (!request) return;
if (typeof request.url === 'string') {
request.url = scrubUrl(request.url);
}
// SDK 10 puts cookies, the body, and the query string on server events although sendDefaultPii is false.
delete request.query_string;
delete request.data;
delete request.cookies;
for (const header of SENSITIVE_HEADERS) {
delete request.headers?.[header];
}
}
function scrubUser(event: Event): void {
if (!event.user) return;
delete event.user.email;
delete event.user.username;
delete event.user.ip_address;
}
function redactExceptions(event: Event): void {
for (const exception of event.exception?.values ?? []) {
if (exception.value) {
exception.value = redactSensitiveText(exception.value);
}
}
if (event.message) {
event.message = redactSensitiveText(event.message);
}
}
// Duck-typed: instrument.ts must not load Nest before Sentry.init.
function httpStatusOf(value: unknown): number | undefined {
if (typeof value !== 'object' || value === null) return undefined;
const getStatus = (value as { getStatus?: unknown }).getStatus;
return typeof getStatus === 'function'
? Number(getStatus.call(value))
: undefined;
}
function appErrorCodeOf(value: unknown): string | undefined {
if (typeof value !== 'object' || value === null) return undefined;
const getResponse = (value as { getResponse?: unknown }).getResponse;
if (typeof getResponse !== 'function') return undefined;
const response = getResponse.call(value) as { code?: unknown } | undefined;
return typeof response?.code === 'string' ? response.code : undefined;
}
export function beforeSend(
event: ErrorEvent,
hint: EventHint,
): ErrorEvent | null {
scrubRequest(event);
scrubUser(event);
redactExceptions(event);
// Can be the raw path, which carries the share-link token.
if (typeof event.transaction === 'string') {
event.transaction = scrubUrl(event.transaction);
}
const exception = hint?.originalException;
const status = httpStatusOf(exception);
if (status !== undefined) {
event.tags = { ...event.tags, http_status: String(status) };
const code = appErrorCodeOf(exception);
if (code) {
event.tags.error_code = code;
// An AppException message is only its class name.
const values = event.exception?.values;
const thrown = values?.[values.length - 1];
if (thrown) {
thrown.value = code;
}
}
}
return event;
}
// In production, console output of level log and info is dropped.
export function filterBreadcrumb(
breadcrumb: Breadcrumb,
isProduction: boolean,
): Breadcrumb | null {
const data = breadcrumb.data as { url?: unknown } | undefined;
if (data && typeof data.url === 'string') {
data.url = scrubUrl(data.url);
}
if (
isProduction &&
breadcrumb.category === 'console' &&
(breadcrumb.level === 'log' || breadcrumb.level === 'info')
) {
return null;
}
return breadcrumb;
}
// No tracesSampleRate: without it no tracing code loads, and errors still share a trace id.
export function buildSentryOptions(env: Env = process.env): NodeOptions {
const dsn = env.SENTRY_DSN?.trim();
const isProduction = env.NODE_ENV === 'production';
return {
dsn: dsn || undefined,
environment:
env.SENTRY_ENVIRONMENT?.trim() || env.NODE_ENV || 'development',
release: env.SENTRY_RELEASE?.trim() || undefined,
sendDefaultPii: false,
beforeSend,
beforeBreadcrumb: (breadcrumb: Breadcrumb) =>
filterBreadcrumb(breadcrumb, isProduction),
};
}

View File

@@ -1,36 +1,11 @@
import { config } from 'dotenv';
import * as Sentry from '@sentry/nestjs';
import { buildSentryOptions } from './common/observability/sentry-options';
config();
const dsn = process.env.SENTRY_DSN?.trim();
const options = buildSentryOptions();
if (dsn) {
Sentry.init({
dsn,
environment:
process.env.SENTRY_ENVIRONMENT?.trim() ||
process.env.NODE_ENV ||
'development',
release: process.env.SENTRY_RELEASE?.trim() || undefined,
sendDefaultPii: false,
tracesSampleRate: 0,
beforeSend(event) {
if (event.request) {
delete event.request.cookies;
delete event.request.data;
if (event.request.headers) {
delete event.request.headers.cookie;
delete event.request.headers.authorization;
delete event.request.headers.Authorization;
}
}
if (event.user) {
delete event.user.email;
delete event.user.ip_address;
delete event.user.username;
}
return event;
},
});
if (options.dsn) {
Sentry.init(options);
}

View File

@@ -1,5 +1,6 @@
// backend/src/main.ts
import './instrument';
import * as Sentry from '@sentry/nestjs';
import { NestFactory } from '@nestjs/core';
import { urlencoded } from 'express';
import { AppModule } from './app.module';
@@ -30,6 +31,9 @@ async function bootstrap() {
// Nest's built-in one would otherwise reject a voice recording at 100 kb.
const app = await NestFactory.create(AppModule, { bodyParser: false });
// SIGTERM: run onModuleDestroy (Prisma, timers), then drain the Sentry queue (SentryLifecycle).
app.enableShutdownHooks();
// Nginx terminates TLS; AdminJS sessions and Secure cookies need the real proto/host.
app.getHttpAdapter().getInstance().set('trust proxy', 1);
@@ -97,4 +101,9 @@ async function bootstrap() {
console.log(`📚 AdminJS Panel: http://localhost:${port}/admin`);
}
bootstrap();
bootstrap().catch((error: unknown) => {
// Exit so the container restarts; the SDK alone would keep the process alive with no port.
console.error('Backend failed to start', error);
Sentry.captureException(error, { tags: { startup: 'true' } });
void Sentry.close(2000).finally(() => process.exit(1));
});

View File

@@ -73,8 +73,6 @@ export class AuthController {
@Req() req,
@Res({ passthrough: true }) res: Response
) {
console.log('Login endpoint hit');
const result = await this.authService.login(loginDto, req.user);
const rememberMe = Boolean(loginDto.rememberMe);

View File

@@ -3,7 +3,8 @@ import {
Injectable,
HttpStatus,
HttpException,
InternalServerErrorException
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import type { JwtSignOptions } from '@nestjs/jwt';
@@ -147,6 +148,8 @@ const READ_ONLY_PERMISSIONS = [
@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
@@ -157,6 +160,16 @@ export class AuthService {
private subscription: SubscriptionService,
) { }
/** A malformed, expired, or not-yet-valid token is a client condition. Each other error is a server failure. */
private isTokenError(error: unknown): boolean {
return (
error instanceof Error &&
(error.name === 'JsonWebTokenError' ||
error.name === 'TokenExpiredError' ||
error.name === 'NotBeforeError')
);
}
private accessJwtSignOptions(): JwtSignOptions {
return {
secret: this.configService.get<string>('jwt.secret')!,
@@ -219,7 +232,12 @@ export class AuthService {
const { passwordHash, ...result } = user;
return result;
} catch (error) {
throw new InternalServerErrorException('Error validating user');
if (error instanceof HttpException) {
throw error;
}
throw new InternalServerErrorException('Error validating user', {
cause: error,
});
}
}
@@ -280,8 +298,13 @@ export class AuthService {
},
};
} catch (error) {
//throw new InternalServerErrorException('Login failed');
console.error('🔥 LOGIN ERROR FULL:', error);
// Expected 4xx (unverified email) must not log as an error; the filter reports the rest.
if (!(error instanceof HttpException)) {
this.logger.error(
'Login failed',
error instanceof Error ? error.stack : undefined,
);
}
throw error;
}
}
@@ -518,7 +541,12 @@ export class AuthService {
},
};
} catch (error) {
throw new InternalServerErrorException('Failed to get profile');
if (error instanceof HttpException) {
throw error;
}
throw new InternalServerErrorException('Failed to get profile', {
cause: error,
});
}
}
@@ -538,7 +566,9 @@ export class AuthService {
message: 'Logged out successfully',
};
} catch (error) {
throw new InternalServerErrorException('Logout failed');
throw new InternalServerErrorException('Logout failed', {
cause: error,
});
}
}
@@ -622,10 +652,11 @@ export class AuthService {
if (error instanceof HttpException) {
throw error;
}
if (error instanceof Error && (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError')) {
if (this.isTokenError(error)) {
throw new AppException(ErrorCode.AUTH_REFRESH_TOKEN_INVALID, HttpStatus.UNAUTHORIZED);
}
throw new AppException(ErrorCode.AUTH_REFRESH_TOKEN_INVALID, HttpStatus.UNAUTHORIZED);
// A database failure is a server error. The filter reports it.
throw error;
}
}
@@ -687,7 +718,9 @@ export class AuthService {
if (error instanceof HttpException) {
throw error;
}
throw new InternalServerErrorException('Failed to change password');
throw new InternalServerErrorException('Failed to change password', {
cause: error,
});
}
}
@@ -926,7 +959,9 @@ export class AuthService {
data: sessions,
};
} catch (error) {
throw new InternalServerErrorException('Failed to get sessions');
throw new InternalServerErrorException('Failed to get sessions', {
cause: error,
});
}
}
@@ -950,7 +985,9 @@ export class AuthService {
message: 'Session revoked successfully',
};
} catch (error) {
throw new InternalServerErrorException('Failed to revoke session');
throw new InternalServerErrorException('Failed to revoke session', {
cause: error,
});
}
}
@@ -974,7 +1011,9 @@ export class AuthService {
message: 'All other sessions revoked successfully',
};
} catch (error) {
throw new InternalServerErrorException('Failed to revoke sessions');
throw new InternalServerErrorException('Failed to revoke sessions', {
cause: error,
});
}
}
@@ -1023,7 +1062,16 @@ export class AuthService {
},
};
} catch (error) {
throw new AppException(ErrorCode.AUTH_SESSION_EXPIRED, HttpStatus.UNAUTHORIZED);
if (error instanceof HttpException) {
throw error;
}
if (this.isTokenError(error)) {
throw new AppException(
ErrorCode.AUTH_SESSION_EXPIRED,
HttpStatus.UNAUTHORIZED,
);
}
throw error;
}
}

View File

@@ -4,6 +4,7 @@ import {
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { reportBackgroundFailure } from '../../common/observability/report-failure';
import {
BillingCatalogKind,
BillingCashEventType,
@@ -158,11 +159,12 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
}
onModuleInit() {
void this.runScheduledStaffRollupIfDue().catch(() => undefined);
this.staffRollupTimer = setInterval(
() => void this.runScheduledStaffRollupIfDue().catch(() => undefined),
60 * 60 * 1000,
);
const runRollup = () =>
void this.runScheduledStaffRollupIfDue().catch((error: unknown) => {
reportBackgroundFailure('staff-billing-rollup', error);
});
runRollup();
this.staffRollupTimer = setInterval(runRollup, 60 * 60 * 1000);
this.staffRollupTimer.unref?.();
}

View File

@@ -1,5 +1,6 @@
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
import { AppException, ErrorCode } from '../../common/errors';
import { reportHandledFailure } from '../../common/observability/report-failure';
import { createReadStream, existsSync, unlinkSync } from 'fs';
import { join, resolve, sep } from 'path';
import {
@@ -647,8 +648,11 @@ export class CasesService {
});
try {
await this.notifyPartnerCaseCreated(labCaseId, actorUserId);
} catch {
} catch (error) {
// Start already committed. A notice failure must not turn that into a 500.
reportHandledFailure('partner-case-created-notice', error, this.logger, {
lab_case_id: labCaseId,
});
}
return { success: true, data: await this.mapLabCaseDetail(refreshed, localeInput, labOrganizationId) };
}
@@ -943,7 +947,7 @@ export class CasesService {
return child.id;
});
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: dto.destinationOrganizationId,
type: UserNotificationType.CASE_SENT,
href: `/cases?caseId=${encodeURIComponent(childCaseId)}`,
@@ -1128,15 +1132,14 @@ export class CasesService {
payload: { attachmentId },
});
} catch (error) {
this.logger.error(
`Failed to record ATTACHMENT_ADDED for case ${labCaseId}`,
error instanceof Error ? error.stack : undefined,
);
reportHandledFailure('attachment-activity-row', error, this.logger, {
lab_case_id: labCaseId,
});
}
}
} finally {
if (created.length > 0) {
void this.userNotifications.emitCaseSectionChanged({
this.userNotifications.emitCaseSectionChangedInBackground({
organizationId: labOrganizationId,
actorUserId,
labCaseId,
@@ -1404,7 +1407,7 @@ export class CasesService {
type: LabCaseActivityType.CASE_IMPORTANT,
actorUserId,
});
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrganizationId,
type: UserNotificationType.CASE_IMPORTANT,
href: `/cases?caseId=${encodeURIComponent(labCaseId)}`,
@@ -1599,7 +1602,7 @@ export class CasesService {
payload: { taskId, assigneeUserId },
});
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrganizationId,
type: UserNotificationType.TASK_ASSIGNED,
href: `/tasks?taskId=${encodeURIComponent(taskId)}&labCaseId=${encodeURIComponent(labCaseId)}`,
@@ -2308,7 +2311,7 @@ export class CasesService {
const token = await this.labCaseAccess.ensureAccessToken(labCase.id);
if (!token) return;
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labCase.partnerClinicOrganizationId,
type: UserNotificationType.PARTNER_CASE_CREATED,
href: `/lab-case/${token}`,

View File

@@ -65,7 +65,7 @@ export class LabCaseCommentsService {
},
});
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrganizationId,
type: UserNotificationType.LAB_COMMENT,
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
@@ -146,7 +146,7 @@ export class LabCaseCommentsService {
});
const labOrgId = await this.labOrgIdForCase(caseId);
if (labOrgId) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrgId,
type: UserNotificationType.CLINIC_COMMENT,
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
@@ -199,7 +199,7 @@ export class LabCaseCommentsService {
});
const labOrgId = await this.labOrgIdForCase(caseId);
if (labOrgId) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrgId,
type: UserNotificationType.CLINIC_COMMENT,
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
@@ -254,7 +254,7 @@ export class LabCaseCommentsService {
const labOrgId = await this.labOrgIdForCase(caseId);
if (labOrgId && labOrgId !== partnerOrganizationId) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrgId,
type:
authorSide === LabCaseCommentSide.CLINIC
@@ -524,7 +524,7 @@ export class LabCaseCommentsService {
if (!partnerId || labCase.partnerClinic?.type.name !== 'CLINIC') return;
const href = await this.partnerShareHref(caseId);
if (!href) return;
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: partnerId,
type: UserNotificationType.LAB_COMMENT_CLINIC,
href,
@@ -538,7 +538,7 @@ export class LabCaseCommentsService {
if (labCase.origin === LabCaseOrigin.LAB_OUTSOURCE) {
const parentLabId = labCase.parentLabCase?.destinationOrganizationId;
if (!parentLabId || !labCase.parentLabCaseId) return;
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: parentLabId,
type: UserNotificationType.LAB_COMMENT,
href: `/cases?caseId=${encodeURIComponent(labCase.parentLabCaseId)}`,
@@ -552,7 +552,7 @@ export class LabCaseCommentsService {
const clinicOrgId =
labCase.treatment?.organizationId ?? labCase.partnerClinicOrganizationId ?? null;
if (!clinicOrgId) return;
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: clinicOrgId,
type: UserNotificationType.LAB_COMMENT_CLINIC,
href: `/treatment?labCaseId=${encodeURIComponent(caseId)}`,

View File

@@ -179,7 +179,12 @@ export class MailService {
});
} catch (error) {
this.logger.error(message.failureLog, error);
throw new AppException(ErrorCode.AUTH_EMAIL_SEND_FAILED, HttpStatus.BAD_GATEWAY);
throw new AppException(
ErrorCode.AUTH_EMAIL_SEND_FAILED,
HttpStatus.BAD_GATEWAY,
undefined,
error,
);
}
}
}

View File

@@ -1,7 +1,8 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { Prisma, UserNotificationType } from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';
import { hasEffectivePermission } from '../../common/membership-permissions';
import { reportBackgroundFailure } from '../../common/observability/report-failure';
import { isActorTreatmentProvider } from '../../common/treatment-provider-scope';
import { RealtimeEmitter } from '../../realtime/realtime.emitter';
@@ -39,13 +40,40 @@ type FanoutInput = RecipientQuery & {
recipientUserIds?: string[];
};
type CaseSectionChangedInput = {
organizationId: string;
actorUserId: string;
labCaseId: string;
requiredPermissions: string[];
};
@Injectable()
export class UserNotificationService {
private readonly logger = new Logger(UserNotificationService.name);
constructor(
private readonly prisma: PrismaService,
private readonly realtime: RealtimeEmitter,
) {}
/** `notify()` for callers that do not await it: reports the failure instead of an unhandled rejection. */
notifyInBackground(input: FanoutInput): void {
this.runInBackground('user-notification.notify', this.notify(input));
}
emitCaseSectionChangedInBackground(input: CaseSectionChangedInput): void {
this.runInBackground(
'case-section-changed',
this.emitCaseSectionChanged(input),
);
}
private runInBackground(task: string, work: Promise<unknown>): void {
void work.catch((error: unknown) => {
reportBackgroundFailure(task, error, this.logger);
});
}
/**
* Lean lab-case snapshot for inbox cards. Used only inside `notify()` so
* inbox list/read never joins patients/orgs/tasks.
@@ -199,12 +227,7 @@ export class UserNotificationService {
* Tell other lab members a case section changed, without writing an inbox row.
* The client treats `case-section.changed` like a tab-badge refresh.
*/
async emitCaseSectionChanged(input: {
organizationId: string;
actorUserId: string;
labCaseId: string;
requiredPermissions: string[];
}): Promise<void> {
async emitCaseSectionChanged(input: CaseSectionChangedInput): Promise<void> {
const recipientIds = await this.resolveRecipients({
organizationId: input.organizationId,
actorUserId: input.actorUserId,

View File

@@ -1,5 +1,6 @@
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
import { AppException, ErrorCode } from '../../common/errors';
import { reportHandledFailure } from '../../common/observability/report-failure';
import { LinkStatus, UserNotificationType } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { createHash, randomBytes } from 'crypto';
@@ -317,7 +318,7 @@ export class OrganizationService {
},
});
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: dto.targetOrganizationId,
type: UserNotificationType.CONNECTION_REQUEST,
href: '/organizations',
@@ -1017,7 +1018,8 @@ export class OrganizationService {
locale: normalizeEmailLocale(inviter?.language),
});
} catch (error) {
this.logger.error(`Failed to email invitation link to ${params.email}`, error);
// The invite exists and the inviter sees success. The failure must still be visible.
reportHandledFailure('invitation-email', error, this.logger);
}
}

View File

@@ -1,4 +1,8 @@
import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import {
Injectable,
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
interface SmsIrVerifyResponse {
@@ -21,7 +25,15 @@ export class SmsService {
const templateId = this.configService.get<number>('sms.templateId');
if (!apiKey) {
this.logger.warn(`SMS_IR_API_KEY not set — verification code for ${mobile}: ${code}`);
if (this.configService.get<string>('NODE_ENV') === 'development') {
this.logger.warn(
`[dev] SMS_IR_API_KEY not set — verification code for ${mobile}: ${code}`,
);
} else {
this.logger.warn(
'SMS_IR_API_KEY not set: the verification SMS was not sent',
);
}
return;
}
@@ -40,24 +52,35 @@ export class SmsService {
parameters: [{ name: 'Code', value: code }],
}),
});
console.log('request', templateId , apiKey,mobile, code);
console.log('response', response);
} catch (error) {
this.logger.error('sms.ir request failed', error);
throw new InternalServerErrorException('Failed to send verification code');
throw new InternalServerErrorException(
'Failed to send verification code',
{ cause: error },
);
}
let payload: SmsIrVerifyResponse;
try {
payload = (await response.json()) as SmsIrVerifyResponse;
} catch {
throw new InternalServerErrorException('Invalid response from SMS provider');
} catch (error) {
throw new InternalServerErrorException(
'Invalid response from SMS provider',
{ cause: error },
);
}
if (!response.ok || payload.status !== 1) {
this.logger.error(`sms.ir error: ${payload.message}`);
throw new InternalServerErrorException('Failed to send verification code');
const providerError = new Error(
`sms.ir status ${payload.status}: ${payload.message}`,
);
throw new InternalServerErrorException(
'SMS provider rejected the verification code',
{
cause: providerError,
},
);
}
}
}

View File

@@ -4,6 +4,7 @@ import {
Logger,
} from '@nestjs/common';
import { AppException, ErrorCode } from '../../common/errors';
import { reportHandledFailure } from '../../common/observability/report-failure';
import * as bcrypt from 'bcrypt';
import { createHash, randomBytes } from 'crypto';
import { UserNotificationType } from '@prisma/client';
@@ -232,7 +233,7 @@ export class StaffService {
});
}
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId,
type: UserNotificationType.STAFF_INVITE,
href: '/staff',
@@ -720,7 +721,8 @@ export class StaffService {
locale: normalizeEmailLocale(inviter?.language),
});
} catch (error) {
this.logger.error(`Failed to email invitation link to ${params.email}`, error);
// The invite exists and the inviter sees success. The failure must still be visible.
reportHandledFailure('invitation-email', error, this.logger);
}
}

View File

@@ -6,6 +6,7 @@ import {
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { AppException, ErrorCode } from '../../common/errors';
import { reportBackgroundFailure } from '../../common/observability/report-failure';
import { HttpStatus } from '@nestjs/common';
import { isSubscriptionWriteAllowed } from './subscription-write.rules';
import { SubscriptionService } from './subscription.service';
@@ -24,7 +25,11 @@ export class SubscriptionWriteInterceptor implements NestInterceptor {
const method = (request.method ?? 'GET').toUpperCase();
const user = request.user;
if (user?.id && user.organizationId) {
void this.subscriptions.ensureExpiryNotices(user.organizationId).catch(() => undefined);
void this.subscriptions
.ensureExpiryNotices(user.organizationId)
.catch((error: unknown) => {
reportBackgroundFailure('seat-expiry-notices', error);
});
}
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
return next.handle();

View File

@@ -1,8 +1,13 @@
import {
HttpStatus,
Injectable,
Logger,
} from '@nestjs/common';
import { AppException, ErrorCode } from '../../common/errors';
import {
reportBackgroundFailure,
reportHandledFailure,
} from '../../common/observability/report-failure';
import { CatalogEntityKind, LabCaseActivityType, LabCaseOrigin, LabTaskStatus, Prisma, UserNotificationType } from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';
import { normalizeMobile } from '../../common/phone';
@@ -63,6 +68,8 @@ const CASE_SCOPED_SCAN_STEP_CODE = 'intraoral_scan';
@Injectable()
export class TasksService {
private readonly logger = new Logger(TasksService.name);
constructor(
private readonly prisma: PrismaService,
private readonly catalogLabels: CatalogLabelService,
@@ -422,11 +429,13 @@ export class TasksService {
});
for (const notice of updated.debtNotices) {
void this.billing.notifyCaseFee(notice).catch(() => undefined);
void this.billing.notifyCaseFee(notice).catch((error: unknown) => {
reportBackgroundFailure('case-fee-notice', error);
});
}
if (updated.caseCompleted) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labOrganizationId,
type: UserNotificationType.CASE_COMPLETED,
href: `/cases?caseId=${encodeURIComponent(task.labCaseId)}`,
@@ -437,7 +446,7 @@ export class TasksService {
const clinicOrgId = task.labCase?.treatment?.organization?.id;
if (clinicOrgId && task.labCase.origin !== LabCaseOrigin.LAB_OUTSOURCE) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: clinicOrgId,
type: UserNotificationType.CASE_COMPLETED,
href: `/treatment?labCaseId=${encodeURIComponent(task.labCaseId)}`,
@@ -450,13 +459,19 @@ export class TasksService {
try {
await this.notifyPartnerCaseCompleted(task.labCase, actorUserId);
} catch {
} catch (error) {
// The step is already completed. A notice failure must not turn that into a 500.
reportHandledFailure(
'partner-case-completed-notice',
error,
this.logger,
{ lab_case_id: task.labCaseId },
);
}
}
for (const notice of updated.ancestorCompletions) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: notice.organizationId,
type: UserNotificationType.CASE_COMPLETED,
href: `/cases?caseId=${encodeURIComponent(notice.labCaseId)}`,
@@ -465,7 +480,7 @@ export class TasksService {
requiredPermission: 'TAB_TASKS_READ',
});
if (notice.clinicOrganizationId) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: notice.clinicOrganizationId,
type: UserNotificationType.CASE_COMPLETED,
href: `/treatment?labCaseId=${encodeURIComponent(notice.labCaseId)}`,
@@ -486,8 +501,14 @@ export class TasksService {
},
null,
);
} catch {
} catch (error) {
// The parent step is already completed.
reportHandledFailure(
'parent-case-completed-notice',
error,
this.logger,
{ lab_case_id: notice.labCaseId },
);
}
}
}
@@ -1033,7 +1054,7 @@ export class TasksService {
if (!requiredPermission) return;
const href = await this.partnerShareHref(labCase.id);
if (!href) return;
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labCase.partnerClinicOrganizationId,
type: UserNotificationType.CASE_COMPLETED,
href,

View File

@@ -1232,7 +1232,7 @@ export class TreatmentsService {
});
if (isFirstSend && labCase.destinationOrganizationId) {
void this.userNotifications.notify({
this.userNotifications.notifyInBackground({
organizationId: labCase.destinationOrganizationId,
type: UserNotificationType.CASE_SENT,
href: `/cases?caseId=${encodeURIComponent(labCaseId)}`,

View File

@@ -360,7 +360,8 @@ export class VoiceService {
: ErrorCode.VOICE_EXTRACT_FAILED;
// No details: the transcript used to ride along here for a salvage dialog that was never
// built, so it was serialized onto the wire and dropped. It stays on the server now.
return new AppException(code, HttpStatus.BAD_GATEWAY);
// The cause rides to the error tracker only.
return new AppException(code, HttpStatus.BAD_GATEWAY, undefined, error);
}
/** Structured and patient-free: never the transcript, never audio, never a patient id. */

View File

@@ -5,6 +5,7 @@ import {
WebSocketServer,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { reportHandledFailure } from '../common/observability/report-failure';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Server, Socket } from 'socket.io';
@@ -62,6 +63,15 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection {
client.data.organizationId = payload.organizationId;
} catch (error) {
this.logger.debug(`Realtime auth failed: ${String(error)}`);
// An expired or malformed token is expected. Anything else (for example a database failure) is not.
const isTokenError =
error instanceof Error &&
(error.name === 'JsonWebTokenError' ||
error.name === 'TokenExpiredError' ||
error.name === 'NotBeforeError');
if (!isTokenError) {
reportHandledFailure('realtime-connection', error, this.logger);
}
client.disconnect(true);
}
}

View File

@@ -33,6 +33,11 @@ ARG NEXT_PUBLIC_APP_URL
ARG NEXT_PUBLIC_APP_NAME
ARG NEXT_PUBLIC_SENTRY_DSN
ARG NEXT_PUBLIC_SENTRY_ENVIRONMENT
# Source maps and release name, used at build time only (upload to GlitchTip). See next.config.ts.
ARG SENTRY_AUTH_TOKEN
ARG SENTRY_ORG
ARG SENTRY_PROJECT
ARG SENTRY_RELEASE
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production

View File

@@ -45,6 +45,11 @@ const nextConfig: NextConfig = {
export default withSentryConfig(withNextIntl(nextConfig), {
silent: true,
sourcemaps: { disable: true },
disableLogger: true,
// GlitchTip. The upload needs SENTRY_AUTH_TOKEN, SENTRY_ORG and SENTRY_PROJECT.
sentryUrl: process.env.SENTRY_URL || 'https://errors.wixur.ir',
telemetry: false,
errorHandler: (error) => {
// A failed upload must not stop a deploy.
console.warn(`[@sentry/nextjs] ${error.message}`);
},
});

View File

@@ -15,7 +15,10 @@ export default function LocaleError({
const t = useTranslations('common');
useEffect(() => {
Sentry.captureException(error);
// An error with a digest was already sent by the server (onRequestError).
if (!error.digest) {
Sentry.captureException(error);
}
}, [error]);
return (

View File

@@ -11,7 +11,10 @@ export default function GlobalError({
reset: () => void;
}) {
useEffect(() => {
Sentry.captureException(error);
// An error with a digest was already sent by the server (onRequestError).
if (!error.digest) {
Sentry.captureException(error);
}
}, [error]);
return (

View File

@@ -0,0 +1,52 @@
import { AxiosError } from 'axios';
import * as Sentry from '@sentry/nextjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getUserFacingError } from './formatApiError';
vi.mock('@sentry/nextjs', () => ({ captureException: vi.fn() }));
const captureException = vi.mocked(Sentry.captureException);
const t = (key: string) => `errors.${key}`;
describe('getUserFacingError', () => {
beforeEach(() => {
captureException.mockClear();
});
it('given a coded API error, when getUserFacingError runs, then the text of the code is returned and nothing is reported', () => {
const message = getUserFacingError({ statusCode: 409, code: 'CONFLICT' }, t, 'Fallback');
expect(message).toBe('errors.CONFLICT');
expect(captureException).not.toHaveBeenCalled();
});
it('given a lost connection, when getUserFacingError runs, then the network text is returned', () => {
expect(getUserFacingError({ statusCode: 0, code: 'NETWORK_ERROR' }, t, 'Fallback')).toBe('errors.NETWORK_ERROR');
expect(getUserFacingError(new Error('Network Error'), t, 'Fallback')).toBe('errors.NETWORK_ERROR');
});
it('given a timeout, when getUserFacingError runs, then the timeout text is returned', () => {
expect(getUserFacingError(new Error('timeout of 10000ms exceeded'), t, 'Fallback')).toBe('errors.TIMEOUT');
});
it('given the same bug twice, when getUserFacingError runs, then the fallback text is returned and the bug is reported once', () => {
const bug = new TypeError("Cannot read properties of undefined (reading 'id')");
expect(getUserFacingError(bug, t, 'cases.errorLoadList')).toBe('cases.errorLoadList');
expect(getUserFacingError(bug, t, 'cases.errorLoadList')).toBe('cases.errorLoadList');
expect(captureException).toHaveBeenCalledTimes(1);
expect(captureException.mock.calls[0]?.[0]).toBe(bug);
});
it('given an axios error, when getUserFacingError runs, then nothing is reported', () => {
getUserFacingError(new AxiosError('Request failed with status code 500'), t, 'Fallback');
expect(captureException).not.toHaveBeenCalled();
});
it('given no error, when getUserFacingError runs, then the generic text is returned', () => {
expect(getUserFacingError(undefined, t)).toBe('errors.GENERIC');
});
});

View File

@@ -1,4 +1,5 @@
import { asApiError, isApiError, type ApiError, type ApiErrorDetail } from '@/types/api';
import { reportUnexpectedError } from '@/lib/error-tracking/reportUnexpectedError';
type TranslateFn = (key: string) => string;
@@ -76,6 +77,10 @@ export function getUserFacingError(
): string {
const apiError = asApiError(err) ?? normalizeLegacyError(err);
// Not an API failure: a bug. Report it before the caller drops it.
if (!apiError) {
reportUnexpectedError(err);
}
if (apiError?.code === 'VALIDATION_FAILED' && apiError.details?.length) {
const validationMessage = formatValidationDetails(apiError.details, t);
if (validationMessage) {

View File

@@ -9,6 +9,8 @@ import {
ResponsiveDialogPanel,
} from '@/components/ui/shared/ResponsiveDialog';
import { Button } from '@/components/ui/shared/Button';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useToast } from '@/lib/hooks/useToast';
import type { LabCaseAttachmentMeta } from '@/types/cases';
interface LabCaseAttachmentsDialogProps {
@@ -136,6 +138,8 @@ export function LabCaseAttachmentsDialog({
loadBlob,
}: LabCaseAttachmentsDialogProps) {
const t = useTranslations('cases');
const tErrors = useTranslations('errors');
const toast = useToast();
const sortedAttachments = [...attachments].sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
@@ -155,10 +159,13 @@ export function LabCaseAttachmentsDialog({
const blob = await loadBlob(caseId, attachment.id);
downloadBlob(blob, attachment.fileName);
}
} catch (error) {
// "Download all" must not fail silently.
toast.showError(getUserFacingError(error, tErrors));
} finally {
setDownloadingAll(false);
}
}, [caseId, loadBlob, sortedAttachments]);
}, [caseId, loadBlob, sortedAttachments, tErrors, toast]);
if (!open) return null;

View File

@@ -148,7 +148,10 @@ export function OrganizationSelectorContent() {
{organizations.map((org) => (
<button
key={org.id}
onClick={() => selectOrganization(org.id)}
// apiError is set and rendered above.
onClick={() => {
void selectOrganization(org.id).catch(() => undefined);
}}
className="surface-card p-4 sm:p-6 transition-all text-left flex items-center gap-3 sm:gap-4 hover:border-primary/60 w-full min-w-0"
>
<div className="p-2.5 sm:p-3 bg-primary-soft rounded-[var(--radius-sm)] text-primary shrink-0">

View File

@@ -1,4 +1,5 @@
import React, { useRef, useState } from 'react';
import { reportUnexpectedError } from '@/lib/error-tracking/reportUnexpectedError';
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'danger' | 'ghost';
type ButtonSize = 'sm' | 'md' | 'lg';
@@ -77,10 +78,15 @@ export const Button: React.FC<ButtonProps> = ({
if (result != null && typeof (result as Promise<void>).then === 'function') {
autoPendingRef.current = true;
setAutoPending(true);
void Promise.resolve(result).finally(() => {
autoPendingRef.current = false;
setAutoPending(false);
});
void Promise.resolve(result)
// A rejected handler would be an unhandled rejection.
.catch((error: unknown) => {
reportUnexpectedError(error);
})
.finally(() => {
autoPendingRef.current = false;
setAutoPending(false);
});
}
};

View File

@@ -29,10 +29,13 @@ export function DetailLabCaseCommentsSection({
}: DetailLabCaseCommentsSectionProps) {
useEffect(() => {
if (!labCaseId) return;
void notificationsApi.markCaseRead(labCaseId).then(() => {
notifyTabBadgesChanged();
onMarkRead?.(labCaseId);
});
void notificationsApi.markCaseRead(labCaseId)
.then(() => {
notifyTabBadgesChanged();
onMarkRead?.(labCaseId);
})
// Best effort: not an unhandled rejection.
.catch(() => undefined);
}, [labCaseId, onMarkRead]);
return (

View File

@@ -28,11 +28,14 @@ export function LabCaseTrackerCard({
useEffect(() => {
if (!expanded || !summary.hasUnread) return;
void notificationsApi.markCaseRead(summary.labCaseId).then(() => {
notifyTabBadgesChanged();
onSummaryChange?.({ ...summary, hasUnread: false });
onMarkedRead?.(summary.labCaseId);
});
void notificationsApi.markCaseRead(summary.labCaseId)
.then(() => {
notifyTabBadgesChanged();
onSummaryChange?.({ ...summary, hasUnread: false });
onMarkedRead?.(summary.labCaseId);
})
// Best effort: not an unhandled rejection.
.catch(() => undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps -- mark read once per expand
}, [expanded, summary.labCaseId, summary.hasUnread, onSummaryChange, onMarkedRead]);

View File

@@ -1802,7 +1802,8 @@ export function TreatmentWorkspace({
isDetailsDirty(detailsRef.current, savedSnapshotRef.current) ||
isLabCasesDirty(labCaseDraftsRef.current, savedLabCasesSnapshotRef.current)
) {
void runDraftSave();
// runDraftSave already shows the toast.
void runDraftSave().catch(() => undefined);
}
}
}
@@ -1855,7 +1856,8 @@ export function TreatmentWorkspace({
if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current);
autosaveTimerRef.current = setTimeout(() => {
autosaveTimerRef.current = null;
void runDraftSave();
// runDraftSave already shows the toast.
void runDraftSave().catch(() => undefined);
}, AUTOSAVE_DEBOUNCE_MS);
return () => {

View File

@@ -99,6 +99,16 @@ apiClient.interceptors.response.use(
| { message?: string | string[] }
| undefined;
// No response: the server was not reached. Say so, instead of "something went wrong on our end".
if (!error.response) {
const timedOut = error.code === AxiosError.ETIMEDOUT || error.code === AxiosError.ECONNABORTED;
const networkError: ApiError = {
statusCode: 0,
code: timedOut ? 'TIMEOUT' : 'NETWORK_ERROR',
};
return Promise.reject(networkError);
}
if (responseData && 'error' in responseData && responseData.error?.code) {
const apiError: ApiError = {
statusCode: responseData.error.statusCode ?? error.response?.status ?? 500,

View File

@@ -0,0 +1,70 @@
import { AxiosError, CanceledError, type InternalAxiosRequestConfig } from 'axios';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import * as Sentry from '@sentry/nextjs';
import { reportUnexpectedApiFailure } from './reportUnexpectedApiFailure';
vi.mock('@sentry/nextjs', () => ({ captureException: vi.fn() }));
const captureException = vi.mocked(Sentry.captureException);
const config = (method: string, url: string) => ({ method, url }) as InternalAxiosRequestConfig;
function axiosError(status: number | undefined, data?: unknown, code = AxiosError.ERR_BAD_RESPONSE) {
return new AxiosError('Request failed', code, config('get', '/cases'), undefined, data === undefined && status === undefined ? undefined : ({ status, data } as never));
}
function backendError(status: number) {
return axiosError(status, { success: false, error: { code: 'INTERNAL_ERROR', statusCode: status } });
}
describe('reportUnexpectedApiFailure', () => {
beforeEach(() => {
captureException.mockClear();
});
it('given a 5xx that the backend filter produced, when the failure is reported, then no event is sent', () => {
reportUnexpectedApiFailure(backendError(500));
expect(captureException).not.toHaveBeenCalled();
});
it('given a 4xx, when the failure is reported, then no event is sent', () => {
reportUnexpectedApiFailure(backendError(409));
expect(captureException).not.toHaveBeenCalled();
});
it('given a canceled request, when the failure is reported, then no event is sent', () => {
reportUnexpectedApiFailure(new CanceledError('canceled'));
expect(captureException).not.toHaveBeenCalled();
});
it('given a request with no response, when the failure is reported, then one event names the endpoint as unreachable', () => {
const error = new AxiosError('Network Error', AxiosError.ERR_NETWORK, config('post', '/cases'), undefined, undefined);
reportUnexpectedApiFailure(error);
const [reported, context] = captureException.mock.calls[0] as [Error, { tags: Record<string, string> }];
expect(reported.message).toBe('API unreachable (network): POST /cases');
expect(reported.cause).toBe(error);
expect(context.tags).toEqual({ failure_kind: 'network', api_status: 'network', api_endpoint: 'POST /cases' });
});
it('given a request that timed out, when the failure is reported, then the event says timeout', () => {
const error = new AxiosError('timeout of 10000ms exceeded', AxiosError.ECONNABORTED, config('get', '/patients'), undefined, undefined);
reportUnexpectedApiFailure(error);
const [reported] = captureException.mock.calls[0] as [Error];
expect(reported.message).toBe('API unreachable (timeout): GET /patients');
});
it('given a 5xx without a backend error body, when the failure is reported, then one event names the status and the endpoint', () => {
reportUnexpectedApiFailure(axiosError(502, '<html>502 Bad Gateway</html>'));
const [reported, context] = captureException.mock.calls[0] as [Error, { tags: Record<string, string> }];
expect(reported.message).toBe('API answered 502 without a backend error: GET /cases');
expect(context.tags.api_status).toBe('502');
});
});

View File

@@ -1,20 +1,43 @@
import * as Sentry from '@sentry/nextjs';
import type { AxiosError } from 'axios';
import axios, { AxiosError } from 'axios';
/** Report network failures and HTTP 5xx only — not coded 4xx AppExceptions. */
/** The backend filter answers each failure with `{ success: false, error: { code } }`. */
function isBackendErrorResponse(data: unknown): boolean {
return (
typeof data === 'object' &&
data !== null &&
typeof (data as { error?: { code?: unknown } }).error?.code === 'string'
);
}
function isTimeout(error: AxiosError): boolean {
return error.code === AxiosError.ETIMEDOUT || error.code === AxiosError.ECONNABORTED;
}
/**
* Reports only the API failures that no backend event covers: no response (network, timeout),
* or a 5xx without a backend error body. The backend filter owns each 5xx that it produced.
*/
export function reportUnexpectedApiFailure(error: AxiosError): void {
const status = error.response?.status;
if (status !== undefined && status < 500) {
if (axios.isCancel(error)) {
return;
}
Sentry.captureException(error, {
tags: {
api_status: status ? String(status) : 'network',
},
extra: {
url: error.config?.url,
method: error.config?.method,
},
const endpoint = `${(error.config?.method ?? 'get').toUpperCase()} ${error.config?.url ?? '(unknown url)'}`;
const status = error.response?.status;
if (status !== undefined) {
if (status < 500 || isBackendErrorResponse(error.response?.data)) {
return;
}
Sentry.captureException(new Error(`API answered ${status} without a backend error: ${endpoint}`, { cause: error }), {
tags: { failure_kind: 'no-backend-error', api_status: String(status), api_endpoint: endpoint },
});
return;
}
const kind = isTimeout(error) ? 'timeout' : 'network';
Sentry.captureException(new Error(`API unreachable (${kind}): ${endpoint}`, { cause: error }), {
tags: { failure_kind: kind, api_status: kind, api_endpoint: endpoint },
});
}

View File

@@ -0,0 +1,16 @@
import * as Sentry from '@sentry/nextjs';
const reportedErrors = new WeakSet<object>();
/** Reports a bug (an error that is not an API failure) once per error object. */
export function reportUnexpectedError(err: unknown): void {
if (!(err instanceof Error) || reportedErrors.has(err)) {
return;
}
// API failures belong to the interceptor and to the backend.
if ((err as { isAxiosError?: boolean }).isAxiosError) {
return;
}
reportedErrors.add(err);
Sentry.captureException(err, { tags: { handled: 'frontend-catch' } });
}

View File

@@ -0,0 +1,76 @@
import type { Breadcrumb, ErrorEvent } from '@sentry/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { scrubUrl, sentrySharedOptions } from './sentrySharedOptions';
describe('sentrySharedOptions', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
describe('scrubUrl', () => {
it('given a page URL with a query string and a hash, when scrubUrl runs, then only the path stays', () => {
expect(scrubUrl('https://app/billing?partyName=John&partyId=1#top')).toBe('https://app/billing');
});
it('given the URL of the lab case share page, when scrubUrl runs, then the token is masked', () => {
expect(scrubUrl('https://app/en/lab-case/abc123')).toBe('https://app/en/lab-case/[token]');
});
});
describe('beforeSend', () => {
const makeEvent = () =>
({
transaction: '/lab-case/abc123',
request: {
url: 'https://app/billing?partyName=John',
cookies: { accessToken: 'JWT' },
data: '{"password":"x"}',
headers: { cookie: 'a=b', authorization: 'Bearer x', accept: 'text/html' },
},
user: { id: 'u1', email: 'a@b.co', ip_address: '203.0.113.9', username: 'amin' },
}) as unknown as ErrorEvent;
it('given an event with cookies, body, query string, and user contact data, when beforeSend runs, then that data is gone', () => {
const result = sentrySharedOptions().beforeSend(makeEvent());
expect(result?.request).toEqual({ url: 'https://app/billing', headers: { accept: 'text/html' } });
expect(result?.user).toEqual({ id: 'u1' });
});
it('given a route name with a share-link token, when beforeSend runs, then the token is masked', () => {
const result = sentrySharedOptions().beforeSend(makeEvent());
expect(result?.transaction).toBe('/lab-case/[token]');
});
});
describe('beforeBreadcrumb', () => {
it('given a request breadcrumb with a query string in its URL, when it is filtered, then the query string is gone', () => {
const breadcrumb = { category: 'xhr', level: 'info', data: { url: '/api/patients?q=john' } } as Breadcrumb;
sentrySharedOptions().beforeBreadcrumb(breadcrumb);
expect(breadcrumb.data).toEqual({ url: '/api/patients' });
});
it('given console output of level log in production, when it is filtered, then it is dropped', () => {
vi.stubEnv('NODE_ENV', 'production');
expect(sentrySharedOptions().beforeBreadcrumb({ category: 'console', level: 'log', message: 'x' })).toBeNull();
});
it('given console output of level log outside production, when it is filtered, then it stays', () => {
vi.stubEnv('NODE_ENV', 'development');
expect(sentrySharedOptions().beforeBreadcrumb({ category: 'console', level: 'log', message: 'x' })).not.toBeNull();
});
});
it('given the shared options, when they are built, then no tracing option and no session replay is set', () => {
const options = sentrySharedOptions();
expect(options).not.toHaveProperty('tracesSampleRate');
expect(options.sendDefaultPii).toBe(false);
expect(options.replaysOnErrorSampleRate).toBe(0);
});
});

View File

@@ -1,22 +1,42 @@
import type { ErrorEvent } from '@sentry/core';
import type { Breadcrumb, ErrorEvent } from '@sentry/core';
/** Path prefixes whose next segment is a secret token (the lab case share page). */
const TOKEN_PATH_PREFIXES = ['/lab-case/'];
const TOKEN_PATH_PATTERNS = TOKEN_PATH_PREFIXES.map(
(prefix) => new RegExp(`(${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})[^/?#]+`, 'g'),
);
export function scrubUrl(url: string): string {
const [path] = url.split(/[?#]/);
return TOKEN_PATH_PATTERNS.reduce((value, pattern) => value.replace(pattern, '$1[token]'), path);
}
/** Shared Sentry/GlitchTip options — no session replay, no PII in payloads. */
export function sentrySharedOptions() {
return {
sendDefaultPii: false as const,
tracesSampleRate: 0,
replaysSessionSampleRate: 0,
replaysOnErrorSampleRate: 0,
// No tracesSampleRate here: without it no tracing code loads, and errors still share a trace id.
beforeSend(event: ErrorEvent): ErrorEvent {
if (event.request) {
// Page URLs can carry names and ids in the query string; the share page carries a token.
if (typeof event.request.url === 'string') {
event.request.url = scrubUrl(event.request.url);
}
delete event.request.cookies;
delete event.request.data;
if (event.request.headers) {
delete event.request.headers.cookie;
delete event.request.headers.Cookie;
delete event.request.headers.authorization;
delete event.request.headers.Authorization;
}
}
if (typeof event.transaction === 'string') {
event.transaction = scrubUrl(event.transaction);
}
if (event.user) {
delete event.user.email;
delete event.user.ip_address;
@@ -24,5 +44,21 @@ export function sentrySharedOptions() {
}
return event;
},
// Request breadcrumbs carry the API URL with its query string (search text, tokens).
// In production, console output of level log and info is dropped.
beforeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {
const data = breadcrumb.data as { url?: unknown } | undefined;
if (data && typeof data.url === 'string') {
data.url = scrubUrl(data.url);
}
if (
process.env.NODE_ENV === 'production' &&
breadcrumb.category === 'console' &&
(breadcrumb.level === 'log' || breadcrumb.level === 'info')
) {
return null;
}
return breadcrumb;
},
};
}

View File

@@ -2,7 +2,10 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { useRouter, usePathname } from '@/i18n/navigation';
import * as Sentry from '@sentry/nextjs';
import { reportUnexpectedError } from '@/lib/error-tracking/reportUnexpectedError';
import { scrubUrl } from '@/lib/error-tracking/sentrySharedOptions';
import { authApi } from '@/lib/api/auth';
import {
clearRememberedEmail,
@@ -90,6 +93,19 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const [apiError, setApiError] = useState<ApiError | null>(null);
const router = useRouter();
const pathname = usePathname();
// Error tracking: who is affected, and on which page. Only ids go out, never email or name.
useEffect(() => {
if (!isAuthReady) return;
Sentry.setUser(user ? { id: user.id } : null);
Sentry.setTag('organization_id', currentOrganization?.id ?? '');
Sentry.setTag('organization_type', currentOrganization?.type ?? '');
}, [isAuthReady, user, currentOrganization]);
useEffect(() => {
Sentry.setTag('route', scrubUrl(pathname));
}, [pathname]);
const normalizeProfilePayload = useCallback((payload: any): { user: User | null; organizations: Organization[] } => {
const organizations = payload?.organizations || [];
@@ -199,6 +215,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
// 401 on profile is expected when there is no session — not an application error.
if (status !== 401) {
console.error('Auth check failed:', err);
reportUnexpectedError(err);
}
// Only clear state — DO NOT redirect here
@@ -267,6 +284,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
} catch (err: any) {
setApiError(toApiError(err));
reportUnexpectedError(err);
throw err;
} finally {
setIsLoading(false);
@@ -310,6 +328,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
return { organizations: orgs };
} catch (err: any) {
setApiError(toApiError(err));
reportUnexpectedError(err);
throw err;
} finally {
setIsLoading(false);
@@ -323,6 +342,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
await authApi.logout();
} catch (err) {
console.error('Logout API failed:', err);
reportUnexpectedError(err);
} finally {
const rememberedEmail = getRememberedEmail();
localStorage.clear();
@@ -356,6 +376,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
} catch (err: any) {
setApiError(toApiError(err));
reportUnexpectedError(err);
throw err;
} finally {
setIsLoading(false);
@@ -385,6 +406,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
return createResponse.data.organization.id as string;
} catch (err: any) {
setApiError(toApiError(err));
reportUnexpectedError(err);
throw err;
} finally {
setIsLoading(false);

View File

@@ -53,8 +53,11 @@ export function useMarkTabReadOnVisit() {
// Cases and Treatment tab badges clear per opened case (mark-case-read), not on tab visit.
if (!tab || tab === 'CASES' || tab === 'TREATMENT' || !currentOrganization?.id) return;
void notificationsApi.markTabRead(tab).then(() => {
window.dispatchEvent(new Event(tabBadgesChangedEventName()));
});
void notificationsApi.markTabRead(tab)
.then(() => {
window.dispatchEvent(new Event(tabBadgesChangedEventName()));
})
// Best effort: not an unhandled rejection.
.catch(() => undefined);
}, [pathname, currentOrganization?.id]);
}

View File

@@ -1,6 +1,7 @@
import createMiddleware from 'next-intl/middleware';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import * as Sentry from '@sentry/nextjs';
import {
getLocaleFromPathname,
routing,
@@ -27,6 +28,16 @@ function isRedirectResponse(response: Response): boolean {
}
export function proxy(request: NextRequest) {
try {
return handleProxy(request);
} catch (error) {
// onRequestError does not reach the proxy on the Node.js runtime (Next.js 16).
Sentry.captureException(error);
throw error;
}
}
function handleProxy(request: NextRequest) {
const intlResponse = handleI18nRouting(request);
if (isRedirectResponse(intlResponse)) {

View File

@@ -45,6 +45,7 @@ services:
PORT: "3000"
ADMIN_JS_TMP_DIR: /app/adminjs-tmp
SENTRY_ENVIRONMENT: staging
SENTRY_RELEASE: ${TAG:-staging}
expose:
- "3000"
networks: