mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-05 21:02:34 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server has about 1,100 test and helper files in `server/src/__tests__` > - `server/tsconfig.json` excludes that directory, Vitest does not check types, and no script runs the tsconfig in that directory > - So a test can call a function with the wrong arguments and still pass, and no tool reports it > - This gap hid 2,168 real type errors, and some of them hid tests that did not test what they claim > - This pull request fixes all of these errors and adds the directory to the server layers from paperclipai/paperclip#18737 > - The benefit is that a type error in a server test now fails the typecheck, with no baseline and no backlog ## Linked Issues or Issue Description Refs paperclipai/paperclip#18737, which is merged and added the server layers. Refs paperclipai/paperclip#18738, which is merged and checks the test projects outside `pnpm -r`, so it is not a duplicate. Refs paperclipai/paperclip#18137, which records that this directory has no check. **What happened?** No tool checked the types of 1,074 of the 1,101 files in `server/src/__tests__`. I searched `package.json`, the workflows, and all tsconfig files. 27 files are in the program of another tsconfig, and these 27 have 0 errors. 11 of the 27 are in `helpers/maintenance/tsconfig.json`. No script ran that project when I measured this. paperclipai/paperclip#18738 now runs it. **Expected behavior** The server typecheck checks these files, and a type error fails the check. **Steps to reproduce** 1. On the base commit, run `tsc -p server/src/__tests__/tsconfig.json --noEmit`. It reports 6,536 errors and needs 12.3 GiB. 2. Add a type error to any file in `server/src/__tests__`. 3. Run `pnpm --filter @paperclipai/server typecheck`. It passes. **Paperclip version or commit** I measured the error breakdown below on commit `8dfd632452`, with TypeScript 7.0.2. The branch now includes master up to paperclipai/paperclip#18865. **Deployment mode** Not applicable. This issue applies to development and CI. No production source file in the server changes. ### Error breakdown Each row adds one change to the row above. | Step | Total errors | Change | Cause | | --- | --- | --- | --- | | Config as committed | 6,536 | | | | Add `src/types/*.d.ts` | 4,447 | -2,089 | Config. The Express request types were missing. | | Set `rootDir` to the repository root | 2,436 | -2,011 | Config. | | Set `allowImportingTsExtensions` | 2,181 | -255 | Config. Vitest accepts `.ts` imports. | | Add `ES2024.Promise` to `lib` | 2,138 | -43 | Config. Node 24 has `Promise.withResolvers`. | | Set `allowJs` for `.mjs` imports | 2,148 | +10 | Config. It removes 8 `TS7016` errors and shows new real errors. | | Set `declaration` to false | 2,142 | -6 | Config. Tests emit nothing. | | Count only files in `server/src` | 2,058 | -84 | Other packages: 53 Daytona, 29 Runner test, 2 UI. | So 4,478 of the 6,536 errors (69%) came from config or scope, and 2,058 are real type errors in 314 files. The 29 Runner test errors are also real, which gives 2,087 errors. Tests that master added after this measurement had 81 more errors, so this pull request fixes 2,168 errors. This table classifies the first 2,058 errors. | Kind of real error | Errors | | --- | --- | | Wrong argument or assignment type | 1,023 | | Stale or partial fixture objects | 525 | | Property that the type does not have | 317 | | Missing narrowing of null or unknown | 101 | | Implicit any | 60 | | Missing name or module | 16 | | Other | 16 | ### What the type errors hid Most errors were stale fixtures and loose mocks. These errors hid real test problems, and this pull request fixes them: - **A test that never ran.** `instrumentation.test.ts` required `sdk-trace-base`, which is not installed. So 3 span tests were skipped. They now run and pass. - **Assertions that could not fail.** - `issue-thread-interactions-service` used a company ID as an issue ID. - `status-card-evaluation-work` compared `[]` with `[]` in a rollback check. - `slack-conversation-lifecycle` read `item.issueId`, which does not exist. - `email-channels` used a permission key that does not exist. - `heartbeat-project-env` imported `LOW_TRUST_REVIEW_PRESET`, which is not exported. The value was undefined. - **Postgres processes that did not stop.** 11 test files called `stop` on the test database helper. That method does not exist, and the helper method is `cleanup`. - **Arguments that the service ignored.** - `methodKey` is now `connectionMethodKey` in the Daytona, Unikraft, 1Password, and Railway tests. - 108 calls passed `"owner-user"` to a parameter that expects an options object. - 9 chat wizard fixtures passed `managementContext` as `source`, so they ran `existing_app` and not `manifest`. - 2 tests passed a `{ userId }` actor that the function ignores. - Inserts into `environments` passed a `companyId` column that the table does not have. - **Problems in tests that master added during this work.** - `sandbox-creation-operations` read `database.connectionString` when an external test database was set. In that mode `database` is undefined, so the fixture would stop with a TypeError. It now uses the external URL. - `idle-completed-history` set a Dot operation to `dispatched`. That is a Muse status, and the Dot type does not have it. The fixture now uses `admitted`, which is a real in-flight Dot status. ### Possible product problems, not changed These may be real problems in production code or types. I did not change them, because this pull request does not change production behavior: - `decisions-service` `service.create` does not validate the lenient `cancel_issue_tree` input. - `createConnection` ignores `input.connectionPurpose`. - The `createConnection` route schema default stores `{}` for `transportConfig`. - `prepareManagedAiRuntime` accepted the invalid value `mode: "connection"`. - `createBinding` accepts invalid `projectionClass` strings outside class 3. - `ensureManagedProjectWorkspace` forwards an untyped `repoRef` by spread. - `routineVariableSchema.label` is optional, but `RoutineVariable.label` is required. - `ToolRunContext.projectId` may be too strict. - `withdrawInteraction` reads `issue.status`, which its type omits. - `issueService.list` and `reconcileNativeFinalizations` omit fields that they return at runtime. - `createGitHubExternalObjectProvider` handles `tokenProvider: null`, but its type forbids this value. ## What Changed - Fixed the 2,168 type errors. The diff changes 322 test and helper files. - Corrected `server/src/__tests__/tsconfig.json`. Editors and the typecheck now read the same options and report the same errors. - Added three `test-tree` layers to `server/scripts/typecheck-layers.mjs`. They read the server layers as declarations, and any error fails them. A hash of the path selects the shard, so a new file does not move other files. - Added `server/scripts/typecheck-stubs/daytona-sdk.d.ts`. Server tests reach Daytona plugin source, and the root install does not have `@daytonaio/sdk`. - Changed two imports in `ui/src/lib/issue-execution-policy.ts` to use `.js` extensions, because server tests import this file. - Made `declarationsConfig` and `--declarations-only` skip the `test-tree` layers, because these layers emit nothing. Other projects read only the source layers. Added a test for this. - Updated `doc/DEVELOPING.md`. ## Verification Run these commands: ```sh pnpm --filter @paperclipai/server typecheck pnpm exec vitest run server/scripts/typecheck-layers.test.mjs ``` Results on macOS (arm64), Node 24, 16 cores. Each check ran after the merge of paperclipai/paperclip#18738 unless the row says otherwise: | Check | Commit | Result | | --- | --- | --- | | Server typecheck, `PAPERCLIP_TYPECHECK_LOW_MEMORY=1`, all 7 layers | `6e45a08573` | Exit 0, 0 errors, 62 seconds, peak 3.52 GiB | | `node scripts/typecheck-test-projects.mjs --low-memory` | `a3306bd13e` | Exit 0, 0 errors, 42 seconds, peak 3.25 GiB | | The same script with `--reuse-declarations` | `1b878aabc0` | Exit 0, 0 errors | | `typecheck-layers.test.mjs` and `live-recovery-work.test.ts` | `01db5634e4` | 90 passed. These include real compiler runs for a pass, a type error, and an invalid tsconfig. | | `tsconfig.declarations.json` after a full server typecheck | `0fb1e4fb0a` | It references only `below`, `cycle`, and `above`. No generated config names a `tsconfig.layers.json` file. | | Owned runtime test in `idle-completed-history` | `e8f2f448ac` | Passed, with the fix that master later replaced | | `idle-incoming-wake`, `plugin-idle-manager`, and the changed `chat-channels` test | `6e45a08573` | 30 passed | | Runner `native-execution.test.ts` | `eab4dcc1f4` | 114 passed | | The 19 server test files that changed since `eab4dcc1f4`, and `typecheck-layers.test.mjs` | `259737b700` | 4,275 of 4,277 passed. The 2 failures are in `chat-channels` and are in the list of 7 below. | The peak is the largest single process, from `/usr/bin/time -l`. Peaks for the server typecheck were between 3.42 GiB and 3.56 GiB across 8 runs. Peaks for the test projects were 3.25 GiB and 3.37 GiB across 2 runs. I did not measure a cgroup. **Runtime check of the fixes.** Types do not prove that a test still works. So I ran all 309 changed server test files, 11,929 tests, before the rebase onto paperclipai/paperclip#18737: | Result | Tests | Detail | | --- | --- | --- | | Passed | 11,913 | Includes the 2 tests and the 54 `dot-runner` tests that passed in a later run, as described below. | | Failed | 7 | The same 7 tests also fail on the commit before the fixes. | | Skipped | 9 | These tests have their own skip conditions: `sentry` 5, and 1 each in `bundled-plugin-registration`, `customer-success-cloud`, `onepassword-connection`, and `workspace-runtime-https-live-exercise`. | The 7 tests that fail with and without this change, on my machine: - 3 tests in `chat-channels` and `email-channels` stop with `ENOENT` on a `SKILL.md` file. The path is in the parent checkout, above the git worktree that I used, so I expect that the worktree is the cause. I did not prove this. - `workspace-instance-cleanup` compares `/private/var/...` with `/var/...`. This is a macOS symlink difference. - 2 tests in `git-reproducible-managed-checkouts` get `unknown_base_git_files` and expect `unpushed_managed_checkout`. I did not find the cause. - 1 more test in `chat-channels`, `materializes direct external-chat finals once`, gets `undefined`. I did not find the cause. CI is the check for these 7 tests. `ci / verify` passed on `eab4dcc1f4`. Failures during this work: - My fix to `agent-runtime-connector-access` changed an invalid permission key in the setup, but not in the assertion. The runtime check found this. I corrected the assertion, and the file passes. - `heartbeat-plugin-environment` failed one wait in the full run. It passed three times alone, so I think that load caused the failure. It can fail again under load. - `dot-runner` skipped all 54 tests in the full run because `cargo` was not on my `PATH`. It then passed 54 of 54 with the toolchain on the `PATH`. - My first `lib` value removed the default DOM types, and the error count went up by 375. I added the DOM libraries. - My Daytona stub with bare `any` left 48 errors, because generic helpers then inferred `unknown`. I added shapes that return promises. - One fix to `agent-secrets-routes` used `class_3_static_lease`, and the test failed. That class allows only specific paths. I reverted to `unclassified`. - `ci / General tests (server (8/12))` failed on `259737b700` because of the flaky port in `idle-completed-history`. paperclipai/paperclip#18853 fixed this test on master, so this pull request keeps that fix. **Audit of the diff.** I counted these patterns in added and removed lines, to find fixes that only hide an error: | Pattern | Added | Removed | | --- | --- | --- | | `@ts-ignore` | 0 | 0 | | `@ts-expect-error` | 0 | 1 | | `.skip` | 0 | 0 | | `as any` | 9 | 9 | | `: any` | 11 | 2 | | `as never` | 8 | 2 | | `as unknown as` | 35 | 4 | | `Promise<unknown>` | 16 | 5 | | `expect(` | 128 | 113 | No hunk removes more `expect(` calls than it adds. Three removals of test content were intentional, and I checked each one: - `muse-control` removed `signalToken`. Line 1012 already asserts that it is absent. - `merged-pr-confirmation-sweep` removed legacy aliases. Other tests cover them. - `heartbeat-workspace-branch-containment` removed a `finalize` branch that no test row can reach. Some partial fixtures stay unchecked through `as unknown as` and `Promise<unknown>`, mostly in `issue-agent-mutation-ownership-routes` and `issue-comment-reopen-routes`. **Accuracy of the check.** One program over the tree and the three shards reported the same errors at the same positions. Memory, as the peak of the largest process on one thread, was 3.93 GiB for one program and 2.43 GiB for the largest shard. I measured these two values before the fixes. Not run or not proven: - I did not run the full `pnpm test:run`, or a root `pnpm build`. I expect CI to run the full suites. - I did not run the 4 GiB container check, or the full `scripts/typecheck-low-memory.mjs`. The peaks above come from macOS, so they are not a Linux cgroup measurement. - I did not run the UI typecheck after the merges. - `workspace-runtime-https-live-exercise` is skipped, so its `cleanup` fix did not run. ## Risks - **A large diff in test files.** 328 files change. A pull request that edits the same tests can get merge conflicts. New tests on master can also add type errors before this merges. Any such error fails this check and needs a fix here. - **A higher cost for changes to source types.** A change to a type can add errors in test files that the author did not touch. The author must then fix them. This is the purpose of the check, but it is new work. - **Changed test behavior.** Some tests now run paths that they did not run before, such as the 9 chat wizard fixtures and the 3 span tests. They pass here, but they can be more sensitive to timing or to the environment. - **The Daytona stub can go stale.** The stub is written by hand. If the plugin uses a new SDK member, the typecheck reports an error until someone updates the stub. - **The release path.** `release-verify.yml` and `scripts/release.sh` run `pnpm -r typecheck`, so they now run this check. - **The tsconfig change.** The test transform reads `server/src/__tests__/tsconfig.json`. The options that I changed are for type checks, and the runs above passed. - **A gap that remains.** Tsconfigs in `packages/paperclip-runner` and in most sandbox provider plugins exclude `*.test.ts`. This check does not read most of those test files, so they can still drift. That work is separate from this pull request. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used Anthropic Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with reasoning, tool use, code execution, and subagents. The runtime does not show the context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass (7 tests fail locally, with and without this change. See Verification.) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
904 lines
35 KiB
TypeScript
904 lines
35 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { createRequire } from "node:module";
|
|
import os from "node:os";
|
|
import http from "node:http";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import type { NextFunction, Request, Response } from "express";
|
|
import { HttpError } from "../errors.js";
|
|
import { errorHandler } from "../middleware/error-handler.js";
|
|
import { finalizeServerShutdown } from "../shutdown.js";
|
|
import { authRoutes } from "../routes/auth.js";
|
|
import * as sentryModule from "../sentry.js";
|
|
|
|
/**
|
|
* Tests for the opt-in Sentry error-monitoring gate. `@sentry/node` is an
|
|
* optional runtime dependency and is NOT installed in CI, which is itself
|
|
* part of the contract under test: with `SENTRY_DSN` set and the package
|
|
* absent, the module must warn and settle instead of crashing the server.
|
|
*
|
|
* The module reads `SENTRY_DSN` at import time, so each test resets the
|
|
* module registry and imports a fresh copy.
|
|
*/
|
|
|
|
const DSN_ENV = "SENTRY_DSN";
|
|
const FRONTEND_DSN_ENV = "SENTRY_DSN_FRONTEND";
|
|
const BACKEND_DSN_ENV = "SENTRY_DSN_BACKEND";
|
|
const originalDsn = process.env[DSN_ENV];
|
|
const originalFrontendDsn = process.env[FRONTEND_DSN_ENV];
|
|
const originalBackendDsn = process.env[BACKEND_DSN_ENV];
|
|
|
|
async function importFreshSentry() {
|
|
vi.resetModules();
|
|
return await import("../sentry.js");
|
|
}
|
|
|
|
/**
|
|
* Register a fake `@sentry/node` module for the next dynamic import. Each
|
|
* mock function is returned so a test can assert on the call it received.
|
|
* The mock stays in place until `vi.doUnmock` runs, so `afterEach` clears it.
|
|
*
|
|
* `@sentry/node` is not installed on disk in this test environment, so the
|
|
* exact-version gate would report it missing before the dynamic import ever
|
|
* runs. This helper also mocks the gate module itself to report success, so
|
|
* a test can exercise the "package present and at the right version" path
|
|
* without installing the real package.
|
|
*/
|
|
function mockSentryPackage() {
|
|
const init = vi.fn();
|
|
const captureException = vi.fn((_error: unknown, _hint?: unknown) => "event-id");
|
|
const close = vi.fn(async () => true);
|
|
const httpIntegration = vi.fn((options: unknown) => ({ name: "Http", ...(options as object) }));
|
|
const onUnhandledRejectionIntegration = vi.fn((options: unknown) => ({
|
|
name: "OnUnhandledRejection",
|
|
...(options as object),
|
|
}));
|
|
|
|
vi.doMock("@sentry/node", () => ({
|
|
getClient: () => ({ on: vi.fn() }),
|
|
init,
|
|
captureException,
|
|
close,
|
|
httpIntegration,
|
|
onUnhandledRejectionIntegration,
|
|
}));
|
|
vi.doMock("../peer-version-check.js", () => ({
|
|
checkExactPeerVersions: () => ({ ok: true }),
|
|
}));
|
|
|
|
return { init, captureException, close, httpIntegration, onUnhandledRejectionIntegration };
|
|
}
|
|
|
|
// A representative default-integration list, shaped like the array
|
|
// `@sentry/node@10.71.0`'s `getDefaultIntegrations()` returns for a Node
|
|
// server. Recorded against the published package with:
|
|
// node -e "const S=require('@sentry/node'); \
|
|
// console.log(S.getDefaultIntegrations({}).map(i=>i.name))"
|
|
const DEFAULT_INTEGRATION_NAMES = [
|
|
"InboundFilters",
|
|
"FunctionToString",
|
|
"LinkedErrors",
|
|
"RequestData",
|
|
"NodeSystemError",
|
|
"ConversationId",
|
|
"Console",
|
|
"OnUncaughtException",
|
|
"OnUnhandledRejection",
|
|
"ContextLines",
|
|
"LocalVariablesAsync",
|
|
"Context",
|
|
"ChildProcess",
|
|
"ProcessSession",
|
|
"Modules",
|
|
"Http",
|
|
"NodeFetch",
|
|
];
|
|
|
|
beforeEach(() => {
|
|
delete process.env[DSN_ENV];
|
|
delete process.env[FRONTEND_DSN_ENV];
|
|
delete process.env[BACKEND_DSN_ENV];
|
|
});
|
|
|
|
afterEach(() => {
|
|
if (originalDsn === undefined) delete process.env[DSN_ENV];
|
|
else process.env[DSN_ENV] = originalDsn;
|
|
if (originalFrontendDsn === undefined) delete process.env[FRONTEND_DSN_ENV];
|
|
else process.env[FRONTEND_DSN_ENV] = originalFrontendDsn;
|
|
if (originalBackendDsn === undefined) delete process.env[BACKEND_DSN_ENV];
|
|
else process.env[BACKEND_DSN_ENV] = originalBackendDsn;
|
|
vi.restoreAllMocks();
|
|
vi.doUnmock("@sentry/node");
|
|
vi.doUnmock("../peer-version-check.js");
|
|
});
|
|
|
|
describe("sentryReady", () => {
|
|
it("resolves and imports no SDK when SENTRY_DSN is unset", async () => {
|
|
// A spy that fails the test if the module attempts a dynamic import of
|
|
// an SDK it should never touch on the closed-gate path. `@sentry/node`
|
|
// is not installed, so an attempted import would settle this promise
|
|
// with a warning instead of resolving clean.
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
|
|
await expect(sentryReady).resolves.toBeUndefined();
|
|
expect(warn).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe("captureException", () => {
|
|
it("sends only private normalized portfolio diagnostics on the matching event", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://fixture@example.com/1";
|
|
const sdk = mockSentryPackage();
|
|
const { captureException, sentryReady } = await importFreshSentry();
|
|
const { CloudPortfolioError } = await import("../services/cloud-portfolio-error.js");
|
|
await sentryReady;
|
|
const error = new CloudPortfolioError("upstream", { phase: "fetch", elapsedMs: 270, upstreamStatus: null }, { code: "ECONNRESET" });
|
|
Object.assign(error, { cause: new Error("private cause"), headers: { authorization: "private token" } });
|
|
Object.defineProperty(error, "diagnostics", { value: { token: "private replacement" } });
|
|
captureException(error);
|
|
const unrelated = new Error("unrelated");
|
|
captureException(unrelated);
|
|
expect(sdk.captureException.mock.calls[0]).toEqual([
|
|
expect.objectContaining({ message: error.message, stack: error.stack }),
|
|
{ tags: { error_code: "cloud_portfolio_failure" }, fingerprint: ["{{ default }}"], contexts: {
|
|
cloud_portfolio: { phase: "fetch", elapsedMs: 270, upstreamStatus: null, networkCode: "ECONNRESET" },
|
|
} },
|
|
]);
|
|
expect(JSON.stringify(sdk.captureException.mock.calls[0])).not.toContain("private");
|
|
expect(sdk.captureException.mock.calls[0]![0]).not.toHaveProperty("cause");
|
|
expect(sdk.captureException.mock.calls[1]).toEqual([unrelated]);
|
|
});
|
|
|
|
it("adds the normalized storage failure to the original error's event only", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://fixture@example.com/1";
|
|
const sdk = mockSentryPackage();
|
|
const { captureException, sentryReady } = await importFreshSentry();
|
|
const { recordS3Failure } = await import("../storage/s3-failure.js");
|
|
await sentryReady;
|
|
const error = Object.assign(new Error("The request signature we calculated does not match"), {
|
|
name: "SignatureDoesNotMatch",
|
|
$metadata: { httpStatusCode: 403, requestId: "req-4G-1", attempts: 1, extendedRequestId: "private host id" },
|
|
StringToSign: "private string to sign",
|
|
});
|
|
recordS3Failure(error, "get_object");
|
|
captureException(error);
|
|
const unrelated = new Error("unrelated");
|
|
captureException(unrelated);
|
|
expect(sdk.captureException.mock.calls[0]).toEqual([
|
|
error,
|
|
{ tags: { storage_operation: "get_object", storage_error_code: "SignatureDoesNotMatch" }, fingerprint: ["{{ default }}"], contexts: {
|
|
storage_failure: { provider: "s3", operation: "get_object", errorCode: "SignatureDoesNotMatch", httpStatus: 403, requestId: "req-4G-1", attempts: 1 },
|
|
} },
|
|
]);
|
|
expect(JSON.stringify(sdk.captureException.mock.calls[0]![1])).not.toContain("private");
|
|
expect(sdk.captureException.mock.calls[1]).toEqual([unrelated]);
|
|
});
|
|
|
|
it("adds bounded Stop timeout context only to that event", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://fixture@example.com/1";
|
|
const sdk = mockSentryPackage();
|
|
const { captureException, sentryReady } = await importFreshSentry();
|
|
const { AdapterStopTimeoutError } = await import("../services/adapter-stop-timeout.js");
|
|
await sentryReady;
|
|
const error = new AdapterStopTimeoutError(60_000, {
|
|
runId: "11111111-1111-4111-8111-111111111111",
|
|
adapterType: "cursor", runtimeMode: "legacy", abortRequested: true,
|
|
phase: "instruction_collection", phaseElapsedMs: 60_321,
|
|
});
|
|
Object.assign(error, { providerResponse: "private fixture payload" });
|
|
captureException(error);
|
|
const unrelated = new Error("unrelated");
|
|
captureException(unrelated);
|
|
expect(sdk.captureException.mock.calls[0]).toEqual([
|
|
expect.objectContaining({ message: error.message, stack: error.stack }),
|
|
{ tags: { error_code: "adapter_stop_unconfirmed" }, fingerprint: ["{{ default }}"], contexts: {
|
|
adapter_stop: { runId: "11111111-1111-4111-8111-111111111111", adapterType: "cursor", runtimeMode: "legacy", abortRequested: true, timeoutMs: 60_000,
|
|
phase: "instruction_collection", phaseElapsedMs: 60_321 },
|
|
} },
|
|
]);
|
|
expect(JSON.stringify(sdk.captureException.mock.calls[0])).not.toContain("private fixture payload");
|
|
expect(sdk.captureException.mock.calls[1]).toEqual([unrelated]);
|
|
});
|
|
|
|
it("does not send arbitrary Stop diagnostic values", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://fixture@example.com/1";
|
|
const sdk = mockSentryPackage();
|
|
const { captureException, sentryReady } = await importFreshSentry();
|
|
const { AdapterStopTimeoutError } = await import("../services/adapter-stop-timeout.js");
|
|
await sentryReady;
|
|
captureException(new AdapterStopTimeoutError(NaN, {
|
|
runId: "private fixture payload", adapterType: "private fixture payload", runtimeMode: "private fixture payload",
|
|
phase: "private fixture payload", phaseElapsedMs: Infinity,
|
|
}));
|
|
expect(JSON.stringify(sdk.captureException.mock.calls)).not.toContain("private fixture payload");
|
|
expect(sdk.captureException.mock.calls[0]).toEqual([expect.any(Error), expect.objectContaining({ contexts: {
|
|
adapter_stop: { runId: null, adapterType: "unknown", runtimeMode: "unknown", abortRequested: null, timeoutMs: null,
|
|
phase: "unknown", phaseElapsedMs: null },
|
|
} })]);
|
|
});
|
|
|
|
it("is a no-op and does not throw when the gate is closed", async () => {
|
|
const { captureException, sentryReady } = await importFreshSentry();
|
|
await sentryReady;
|
|
|
|
expect(() => captureException(new Error("boom"))).not.toThrow();
|
|
});
|
|
});
|
|
|
|
describe("shutdownSentry", () => {
|
|
it("resolves once for concurrent callers", async () => {
|
|
const { shutdownSentry } = await importFreshSentry();
|
|
|
|
const first = shutdownSentry();
|
|
const second = shutdownSentry();
|
|
|
|
// Memoized: concurrent callers share one shutdown promise.
|
|
expect(first).toBe(second);
|
|
await expect(first).resolves.toBeUndefined();
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Seam tests for the two `errorHandler` call sites that report to Sentry.
|
|
* These tests spy on the exported `captureException` binding rather than
|
|
* import a real client, so they assert the call-site shape (one call, the
|
|
* Error object only) without a live Sentry SDK.
|
|
*/
|
|
describe("errorHandler Sentry capture", () => {
|
|
function makeReq(): Request {
|
|
return {
|
|
method: "GET",
|
|
originalUrl: "/api/test",
|
|
body: { a: 1 },
|
|
params: { id: "123" },
|
|
query: { q: "x" },
|
|
} as unknown as Request;
|
|
}
|
|
|
|
function makeRes(): Response {
|
|
const res = {
|
|
status: vi.fn(),
|
|
json: vi.fn(),
|
|
} as unknown as Response;
|
|
(res.status as unknown as ReturnType<typeof vi.fn>).mockReturnValue(res);
|
|
return res;
|
|
}
|
|
|
|
it("captures one event for a 500-level HttpError", () => {
|
|
const capture = vi.spyOn(sentryModule, "captureException").mockImplementation(() => {});
|
|
const req = makeReq();
|
|
const res = makeRes();
|
|
const next = vi.fn() as unknown as NextFunction;
|
|
const err = new HttpError(500, "db exploded");
|
|
|
|
errorHandler(err, req, res, next);
|
|
|
|
expect(capture).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("captures one event for an unknown error", () => {
|
|
const capture = vi.spyOn(sentryModule, "captureException").mockImplementation(() => {});
|
|
const req = makeReq();
|
|
const res = makeRes();
|
|
const next = vi.fn() as unknown as NextFunction;
|
|
const err = new Error("boom");
|
|
|
|
errorHandler(err, req, res, next);
|
|
|
|
expect(capture).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("captures no event for a Zod validation 400 response", () => {
|
|
const capture = vi.spyOn(sentryModule, "captureException").mockImplementation(() => {});
|
|
const req = makeReq();
|
|
const res = makeRes();
|
|
const next = vi.fn() as unknown as NextFunction;
|
|
const issue = {
|
|
code: "invalid_type",
|
|
expected: "string",
|
|
received: "undefined",
|
|
path: ["provider"],
|
|
message: "Required",
|
|
};
|
|
const err = Object.assign(new Error("Validation failed"), {
|
|
name: "ZodError",
|
|
issues: [issue],
|
|
});
|
|
|
|
errorHandler(err, req, res, next);
|
|
|
|
expect(res.status).toHaveBeenCalledWith(400);
|
|
expect(capture).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("passes the Error object only to captureException, never the request-bearing ErrorContext", () => {
|
|
const capture = vi.spyOn(sentryModule, "captureException").mockImplementation(() => {});
|
|
const req = makeReq();
|
|
const res = makeRes();
|
|
const next = vi.fn() as unknown as NextFunction;
|
|
const err = new Error("boom");
|
|
|
|
errorHandler(err, req, res, next);
|
|
|
|
expect(capture).toHaveBeenCalledWith(err);
|
|
const [received] = capture.mock.calls[0]!;
|
|
expect(received).toBeInstanceOf(Error);
|
|
// The `ErrorContext` shape carries the request body, params, and query.
|
|
// The received value must not carry any of them.
|
|
expect(received).not.toHaveProperty("reqBody");
|
|
expect(received).not.toHaveProperty("reqParams");
|
|
expect(received).not.toHaveProperty("reqQuery");
|
|
});
|
|
});
|
|
|
|
describe("finalizeServerShutdown Sentry teardown", () => {
|
|
it("calls shutdownSentry after shutdownInstrumentation", async () => {
|
|
const order: string[] = [];
|
|
const shutdownInstrumentation = vi.fn(async () => {
|
|
order.push("instrumentation");
|
|
});
|
|
const shutdownSentry = vi.fn(async () => {
|
|
order.push("sentry");
|
|
});
|
|
|
|
await finalizeServerShutdown({
|
|
signal: "SIGTERM",
|
|
shutdownAppServices: undefined,
|
|
stopEmbeddedPostgres: null,
|
|
shutdownInstrumentation,
|
|
shutdownSentry,
|
|
log: { info: vi.fn(), error: vi.fn() },
|
|
});
|
|
|
|
expect(order).toEqual(["instrumentation", "sentry"]);
|
|
});
|
|
});
|
|
|
|
describe("missing @sentry/node package", () => {
|
|
it("logs one warning and resolves", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://public@o0.ingest.sentry.io/1";
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
// Keep this failure-mode test valid when the optional real-SDK tests run.
|
|
vi.doMock("../peer-version-check.js", () => ({
|
|
checkExactPeerVersions: () => ({
|
|
ok: false,
|
|
detail: { missing: ["@sentry/node"], mismatched: [] },
|
|
}),
|
|
}));
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
|
|
// Bootstrap must absorb the failed dynamic import — the server keeps
|
|
// booting without error monitoring rather than crashing on an opt-in
|
|
// feature.
|
|
await expect(sentryReady).resolves.toBeUndefined();
|
|
expect(warn).toHaveBeenCalledTimes(1);
|
|
expect(warn).toHaveBeenCalledWith(
|
|
expect.stringContaining("@sentry/node package is not installed"),
|
|
expect.anything(),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("@sentry/node installed at an unsupported version", () => {
|
|
it("logs one diagnostic and resolves without importing the package", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://public@o0.ingest.sentry.io/1";
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
vi.doMock("../peer-version-check.js", () => ({
|
|
checkExactPeerVersions: () => ({
|
|
ok: false,
|
|
diagnostic: "unused by the Sentry gate; see server/src/sentry.ts",
|
|
detail: {
|
|
missing: [],
|
|
mismatched: [{ name: "@sentry/node", installed: "9.0.0", expected: "10.71.0" }],
|
|
},
|
|
}),
|
|
}));
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
|
|
// Bootstrap must absorb the reported mismatch — the server keeps
|
|
// booting without error monitoring rather than crashing on an opt-in
|
|
// feature.
|
|
await expect(sentryReady).resolves.toBeUndefined();
|
|
expect(warn).toHaveBeenCalledTimes(1);
|
|
expect(warn).toHaveBeenCalledWith(
|
|
expect.stringContaining("@sentry/node package is not installed"),
|
|
expect.anything(),
|
|
);
|
|
|
|
vi.doUnmock("../peer-version-check.js");
|
|
});
|
|
});
|
|
|
|
describe("split DSN gating", () => {
|
|
it("opens the gate and passes the backend DSN to Sentry.init when SENTRY_DSN_BACKEND alone is set", async () => {
|
|
process.env[BACKEND_DSN_ENV] = "https://public-backend@o0.ingest.sentry.io/2";
|
|
const mocks = mockSentryPackage();
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
await sentryReady;
|
|
|
|
expect(mocks.init).toHaveBeenCalledTimes(1);
|
|
const initOptions = mocks.init.mock.calls[0][0] as { dsn: string };
|
|
expect(initOptions.dsn).toBe("https://public-backend@o0.ingest.sentry.io/2");
|
|
});
|
|
|
|
it("leaves the gate closed and loads no SDK when SENTRY_DSN_FRONTEND alone is set", async () => {
|
|
process.env[FRONTEND_DSN_ENV] = "https://public-frontend@o0.ingest.sentry.io/1";
|
|
const mocks = mockSentryPackage();
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
await sentryReady;
|
|
|
|
expect(mocks.init).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("logs one warning that names the three variables and holds no DSN value when only SENTRY_DSN is set", async () => {
|
|
process.env[DSN_ENV] = "https://public-legacy@o0.ingest.sentry.io/3";
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
mockSentryPackage();
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
await sentryReady;
|
|
|
|
expect(warn).toHaveBeenCalledTimes(1);
|
|
const [message] = warn.mock.calls[0]!;
|
|
expect(message).toEqual(expect.stringContaining("SENTRY_DSN_FRONTEND"));
|
|
expect(message).toEqual(expect.stringContaining("SENTRY_DSN_BACKEND"));
|
|
expect(message).toEqual(expect.stringContaining("SENTRY_DSN"));
|
|
for (const call of warn.mock.calls) {
|
|
for (const arg of call) {
|
|
expect(String(arg)).not.toContain("https://public-legacy@o0.ingest.sentry.io/3");
|
|
}
|
|
}
|
|
});
|
|
|
|
it("logs no warning when both specific variables are set", async () => {
|
|
process.env[FRONTEND_DSN_ENV] = "https://public-frontend@o0.ingest.sentry.io/1";
|
|
process.env[BACKEND_DSN_ENV] = "https://public-backend@o0.ingest.sentry.io/2";
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
mockSentryPackage();
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
await sentryReady;
|
|
|
|
expect(warn).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe("buildSentryInitOptions", () => {
|
|
it("sets sendDefaultPii false, tracesSampleRate 0, and skipOpenTelemetrySetup true", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
|
|
expect(options.sendDefaultPii).toBe(false);
|
|
expect(options.tracesSampleRate).toBe(0);
|
|
expect(options.skipOpenTelemetrySetup).toBe(true);
|
|
});
|
|
|
|
it("passes onUnhandledRejection with mode strict", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
const onUnhandledRejectionIntegration = vi.fn((options: unknown) => ({
|
|
name: "OnUnhandledRejection",
|
|
...(options as object),
|
|
}));
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration,
|
|
});
|
|
const resolved = options.integrations(DEFAULT_INTEGRATION_NAMES.map((name) => ({ name })));
|
|
|
|
expect(onUnhandledRejectionIntegration).toHaveBeenCalledWith({ mode: "strict" });
|
|
const rejectionIntegration = resolved.find((i) => i.name === "OnUnhandledRejection");
|
|
expect(rejectionIntegration).toMatchObject({ mode: "strict" });
|
|
// The default OnUnhandledRejection entry must not survive alongside it.
|
|
expect(resolved.filter((i) => i.name === "OnUnhandledRejection")).toHaveLength(1);
|
|
});
|
|
|
|
it("the resolved server integration list holds no Console integration and no ContextLines integration", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
const resolved = options.integrations(DEFAULT_INTEGRATION_NAMES.map((name) => ({ name })));
|
|
const names = resolved.map((i) => i.name);
|
|
|
|
expect(names).not.toContain("Console");
|
|
expect(names).not.toContain("ContextLines");
|
|
});
|
|
|
|
it("the resolved server integration list keeps OnUncaughtException, OnUnhandledRejection, LinkedErrors, and RequestData", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
const resolved = options.integrations(DEFAULT_INTEGRATION_NAMES.map((name) => ({ name })));
|
|
const names = resolved.map((i) => i.name);
|
|
|
|
// The full error-capture set the plan requires, not just the four named
|
|
// in this test's title.
|
|
expect(names).toEqual(
|
|
expect.arrayContaining([
|
|
"OnUncaughtException",
|
|
"OnUnhandledRejection",
|
|
"ChildProcess",
|
|
"LinkedErrors",
|
|
"RequestData",
|
|
"Modules",
|
|
"Context",
|
|
"ProcessSession",
|
|
]),
|
|
);
|
|
});
|
|
|
|
it("turns the outbound HTTP breadcrumb off and keeps the rest of the Http integration", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
const httpIntegration = vi.fn((options: unknown) => ({ name: "Http", ...(options as object) }));
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration,
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
const resolved = options.integrations(DEFAULT_INTEGRATION_NAMES.map((name) => ({ name })));
|
|
|
|
expect(httpIntegration).toHaveBeenCalledWith({ breadcrumbs: false });
|
|
expect(resolved.filter((i) => i.name === "Http")).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
describe("buildSentryInitOptions serverName", () => {
|
|
it("sets serverName to the host name", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
|
|
expect(options.serverName).toBe(os.hostname());
|
|
});
|
|
|
|
it("reads the host name from node:os at call time, not at module load time", async () => {
|
|
vi.doMock("node:os", () => ({
|
|
default: { hostname: () => "fixed-test-host" },
|
|
hostname: () => "fixed-test-host",
|
|
}));
|
|
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
|
|
expect(options.serverName).toBe("fixed-test-host");
|
|
|
|
vi.doUnmock("node:os");
|
|
});
|
|
|
|
const SENTRY_NAME_ENV = "SENTRY_NAME";
|
|
let originalSentryName: string | undefined;
|
|
|
|
beforeEach(() => {
|
|
originalSentryName = process.env[SENTRY_NAME_ENV];
|
|
});
|
|
|
|
afterEach(() => {
|
|
if (originalSentryName === undefined) delete process.env[SENTRY_NAME_ENV];
|
|
else process.env[SENTRY_NAME_ENV] = originalSentryName;
|
|
});
|
|
|
|
it("uses SENTRY_NAME as serverName when the variable holds a non-empty string", async () => {
|
|
process.env[SENTRY_NAME_ENV] = "opaque-operator-id";
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
|
|
expect(options.serverName).toBe("opaque-operator-id");
|
|
});
|
|
|
|
it("uses the host name as serverName when SENTRY_NAME is absent", async () => {
|
|
delete process.env[SENTRY_NAME_ENV];
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
|
|
expect(options.serverName).toBe(os.hostname());
|
|
});
|
|
|
|
it("uses the host name as serverName when SENTRY_NAME is an empty string", async () => {
|
|
process.env[SENTRY_NAME_ENV] = "";
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
|
|
const options = buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
});
|
|
|
|
expect(options.serverName).toBe(os.hostname());
|
|
});
|
|
});
|
|
|
|
describe("buildSentryInitOptions release", () => {
|
|
const commit = "0123456789abcdef0123456789abcdef01234567";
|
|
const readBuildCommit = vi.fn<() => string | null>();
|
|
const integrations = {
|
|
httpIntegration: () => ({ name: "Http" }),
|
|
onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
|
|
};
|
|
|
|
beforeEach(() => {
|
|
vi.stubEnv("SENTRY_RELEASE", "");
|
|
readBuildCommit.mockReturnValue(commit);
|
|
vi.doMock("../build-commit.js", () => ({ readBuildCommit }));
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllEnvs();
|
|
vi.doUnmock("../build-commit.js");
|
|
readBuildCommit.mockReset();
|
|
});
|
|
|
|
it("uses the server build commit", async () => {
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
expect(buildSentryInitOptions("test-dsn", integrations).release).toBe(commit);
|
|
});
|
|
|
|
it("preserves an operator's explicit release", async () => {
|
|
vi.stubEnv("SENTRY_RELEASE", " custom-release ");
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
expect(buildSentryInitOptions("test-dsn", integrations).release).toBe("custom-release");
|
|
});
|
|
|
|
it("leaves an unknown build unattributed", async () => {
|
|
// Keep one module factory and change its return value explicitly for this
|
|
// case, rather than depending on a second factory replacing the first.
|
|
readBuildCommit.mockReturnValue(null);
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
expect(buildSentryInitOptions("test-dsn", integrations).release).toBeUndefined();
|
|
expect(readBuildCommit).toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe("with @sentry/node mocked", () => {
|
|
it("initializes the client and shares captureException / shutdownSentry with it", async () => {
|
|
process.env[DSN_ENV] = "https://public@o0.ingest.sentry.io/1";
|
|
const mocks = mockSentryPackage();
|
|
|
|
const { sentryReady, captureException, shutdownSentry } = await importFreshSentry();
|
|
await sentryReady;
|
|
|
|
expect(mocks.init).toHaveBeenCalledTimes(1);
|
|
const initOptions = mocks.init.mock.calls[0][0] as { dsn: string };
|
|
expect(initOptions.dsn).toBe("https://public@o0.ingest.sentry.io/1");
|
|
|
|
captureException(new Error("boom"));
|
|
expect(mocks.captureException).toHaveBeenCalledWith(expect.any(Error));
|
|
|
|
await shutdownSentry();
|
|
expect(mocks.close).toHaveBeenCalledWith(5_000);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Proves the one-project result: the server and the browser both resolve
|
|
* their Sentry client from the same `SENTRY_DSN` value, so both send events
|
|
* to the same Sentry project. The browser reads its DSN from the
|
|
* `GET /api/auth/get-session` response body (see `ui/src/lib/sentry.ts` and
|
|
* `ui/src/components/SentryGate.tsx`), never from a `<meta>` tag.
|
|
*/
|
|
describe("one-project resolution", () => {
|
|
function makeSessionApp() {
|
|
const app = express();
|
|
app.use((req, _res, next) => {
|
|
req.actor = { type: "board", userId: "user-1", source: "session" };
|
|
next();
|
|
});
|
|
const db = {
|
|
select: () => ({
|
|
from: () => ({
|
|
where: () =>
|
|
Promise.resolve([
|
|
{ id: "user-1", name: "Jane Example", email: "jane@example.com", image: null },
|
|
]),
|
|
}),
|
|
}),
|
|
};
|
|
app.use("/api/auth", authRoutes(db as unknown as Parameters<typeof authRoutes>[0]));
|
|
app.use(errorHandler);
|
|
return app;
|
|
}
|
|
|
|
it("the server initializer and GET /api/auth/get-session resolve the same Sentry project", async () => {
|
|
process.env[DSN_ENV] = "https://public@o0.ingest.sentry.io/1";
|
|
const mocks = mockSentryPackage();
|
|
|
|
const { sentryReady } = await importFreshSentry();
|
|
await sentryReady;
|
|
const initOptions = mocks.init.mock.calls[0]![0] as { dsn: string };
|
|
|
|
const app = makeSessionApp();
|
|
const res = await request(app).get("/api/auth/get-session");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.sentryDsn).toBe(initOptions.dsn);
|
|
});
|
|
});
|
|
|
|
// `@sentry/node` is an optional runtime dependency (see the module comment
|
|
// in sentry.ts). When it is absent, the three tests below cannot run against
|
|
// the true SDK, so they are skipped — the same pattern instrumentation.test.ts
|
|
// uses for its OpenTelemetry-SDK-dependent test.
|
|
const sentryPackage = (() => {
|
|
try {
|
|
const require = createRequire(import.meta.url);
|
|
return require("@sentry/node") as {
|
|
init(options: Record<string, unknown>): unknown;
|
|
captureException(error: unknown): string;
|
|
httpIntegration(options: { breadcrumbs: boolean }): { name: string };
|
|
onUnhandledRejectionIntegration(options: { mode: string }): { name: string };
|
|
flush(timeout?: number): Promise<boolean>;
|
|
close(timeout?: number): Promise<boolean>;
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
})();
|
|
|
|
describe.skipIf(!sentryPackage)("captured event shape against the real @sentry/node SDK", () => {
|
|
/**
|
|
* Initialize the real SDK with this module's exact options, plus a
|
|
* transport stub so no event leaves the test process, plus `beforeSend`
|
|
* so the test can inspect the resolved event before it would have been
|
|
* sent. `beforeSend` is test-only introspection — the module under test
|
|
* adds no `beforeSend` of its own (constraint: built-in options only).
|
|
*/
|
|
async function initRealSentryForTest(onEvent: (event: Record<string, unknown>) => void) {
|
|
const Sentry = sentryPackage!;
|
|
const { buildSentryInitOptions } = await importFreshSentry();
|
|
const options = {
|
|
...buildSentryInitOptions("https://public@o0.ingest.sentry.io/1", Sentry),
|
|
transport: () => ({ send: async () => ({}), flush: async () => true }),
|
|
beforeSend: (event: Record<string, unknown>) => {
|
|
onEvent(event);
|
|
return event;
|
|
},
|
|
};
|
|
Sentry.init(options);
|
|
}
|
|
|
|
it("attaches the actual build commit to an emitted event", async () => {
|
|
const commit = "0123456789abcdef0123456789abcdef01234567";
|
|
vi.stubEnv("PAPERCLIP_BUILD_COMMIT", commit);
|
|
vi.stubEnv("SENTRY_RELEASE", "");
|
|
try {
|
|
let captured: Record<string, unknown> | null = null;
|
|
await initRealSentryForTest((event) => { captured = event; });
|
|
sentryPackage!.captureException(new Error("build attribution check"));
|
|
await sentryPackage!.flush(2000);
|
|
expect(captured).toMatchObject({ release: commit });
|
|
expect(captured).not.toHaveProperty("request");
|
|
} finally {
|
|
vi.unstubAllEnvs();
|
|
}
|
|
});
|
|
|
|
it("a server event captured after a console.error call carries no console breadcrumb", async () => {
|
|
const Sentry = sentryPackage!;
|
|
let captured = null as Record<string, unknown> | null;
|
|
await initRealSentryForTest((event) => {
|
|
captured = event;
|
|
});
|
|
|
|
// eslint-disable-next-line no-console
|
|
console.error("child process stderr: simulated failure");
|
|
Sentry.captureException(new Error("after console.error"));
|
|
await Sentry.flush(2000);
|
|
|
|
expect(captured).not.toBeNull();
|
|
expect((captured as Record<string, unknown>).breadcrumbs).toBeUndefined();
|
|
});
|
|
|
|
it("a server event carries no stack-frame source context", async () => {
|
|
const Sentry = sentryPackage!;
|
|
let captured: Record<string, unknown> | null = null;
|
|
await initRealSentryForTest((event) => {
|
|
captured = event;
|
|
});
|
|
|
|
Sentry.captureException(new Error("stack frame check"));
|
|
await Sentry.flush(2000);
|
|
|
|
const event = captured as unknown as {
|
|
exception: { values: Array<{ stacktrace: { frames: Array<Record<string, unknown>> } }> };
|
|
};
|
|
const frames = event.exception.values[0].stacktrace.frames;
|
|
expect(frames.length).toBeGreaterThan(0);
|
|
for (const frame of frames) {
|
|
expect(frame.context_line).toBeUndefined();
|
|
expect(frame.pre_context).toBeUndefined();
|
|
expect(frame.post_context).toBeUndefined();
|
|
}
|
|
});
|
|
|
|
it("a server event carries no outbound HTTP breadcrumb", async () => {
|
|
const Sentry = sentryPackage!;
|
|
let captured: Record<string, unknown> | null = null;
|
|
await initRealSentryForTest((event) => {
|
|
captured = event;
|
|
});
|
|
|
|
const server = http.createServer((_req, res) => res.end("ok"));
|
|
await new Promise<void>((resolve) => server.listen(0, resolve));
|
|
const port = (server.address() as { port: number }).port;
|
|
await new Promise<void>((resolve) => {
|
|
http.get(`http://127.0.0.1:${port}/probe?token=secret`, (res) => {
|
|
res.resume();
|
|
res.on("end", resolve);
|
|
});
|
|
});
|
|
server.close();
|
|
|
|
Sentry.captureException(new Error("after outbound http call"));
|
|
await Sentry.flush(2000);
|
|
|
|
expect((captured as unknown as Record<string, unknown>).breadcrumbs).toBeUndefined();
|
|
});
|
|
|
|
/**
|
|
* `skipOpenTelemetrySetup: true` (set above) keeps this module out of
|
|
* Paperclip's separate, independently opt-in OpenTelemetry feature. It
|
|
* also turns off Sentry's own per-request async-context tracking. The
|
|
* `RequestData` integration reads the inbound URL, method, headers,
|
|
* cookies, and query string from that per-request context. With the
|
|
* context off, a captured event carries no request field — not the
|
|
* SDK's documented default. This test proves the gap, so the operator
|
|
* documentation states the true capture set.
|
|
*/
|
|
it("a server event captured inside a real HTTP request handler carries no request field", async () => {
|
|
const Sentry = sentryPackage!;
|
|
let captured: Record<string, unknown> | null = null;
|
|
await initRealSentryForTest((event) => {
|
|
captured = event;
|
|
});
|
|
|
|
const server = http.createServer((req, res) => {
|
|
req.on("data", () => {});
|
|
req.on("end", () => {
|
|
Sentry.captureException(new Error("boom from a real request handler"));
|
|
res.end("ok");
|
|
});
|
|
});
|
|
await new Promise<void>((resolve) => server.listen(0, resolve));
|
|
const port = (server.address() as { port: number }).port;
|
|
await new Promise<void>((resolve) => {
|
|
http.get(`http://127.0.0.1:${port}/api/test?foo=bar`, (res) => {
|
|
res.resume();
|
|
res.on("end", resolve);
|
|
});
|
|
});
|
|
server.close();
|
|
await Sentry.flush(2000);
|
|
|
|
expect(captured).not.toBeNull();
|
|
expect((captured as unknown as Record<string, unknown>).request).toBeUndefined();
|
|
});
|
|
});
|