Skip to content

Close the six remaining security findings, plus the analytics view leak they exposed - #115

Merged
imshashank merged 10 commits into
mainfrom
fix/security-review-followups
Aug 6, 2026
Merged

imshashank merged 10 commits into
mainfrom
fix/security-review-followups

Conversation

@imshashank

Copy link
Copy Markdown
Contributor

Closes the six lower-severity findings left open after #114, plus one more the verification pass turned up.

Every fix here was proven by mutation: the test was watched failing first, and after the fix the production code was deliberately re-broken to confirm the test goes red. An independent verifier re-ran all of it in its own worktree and reproduced every mutation with the same red counts, then ran 17 more the author had not listed.

The six

  1. Team-restricted projects and milestones were broadcast workspace-wide. projectScopes and milestoneScopes attached an org scope, so a project an HTTP reader gets a 404 for was pushed to every member. The org scope could not simply be dropped, or project list updates would stop arriving for everyone, so the reach is now computed from project_team: team scopes when the project has teams, the org scope only when it has none, which matches visibleProjectFilter, assertProjectVisible and the hub's projectScopeAllowed exactly. deleteProject computes the reach before the row cascades away.

  2. Unshared saved views were broadcast org-wide. A private view now carries its owner alone, and unsharing publishes a delete on the org scope so it leaves everyone else's sidebar rather than going stale there.

  3. Signing out did not close the socket. Sign-out now publishes a revocation, and a periodic sweep closes sockets whose session has expired. Fails closed.

  4. The orbit.read MCP scope was never enforced. An openid-only token read the entire workspace. readOnly is now a required field on ToolConfig, all 74 tools are classified (27 read, 47 write), reads require orbit.read and writes require a write scope. A scripted scan confirmed no read-flagged tool calls a mutation.

  5. Presigned uploads had no server-enforced size limit. The upload is now bound to the byte length it declares, so S3 itself rejects an oversized object. Covered by a live MinIO round trip.

  6. The analytics CSV export did not escape formula-leading characters. A crafted issue title became a live formula in Excel. Values leading with =, +, -, @, tab or carriage return are now defused and quoted correctly.

The one the verification found

The verifier noticed finding 2 was only half closed: the identical viewScopes shape was still live in packages/core/src/analytics/saved-view.ts, which the branch had not touched, and reproduced it against the real database. A private analytics dashboard was owner-only over REST and broadcast to the whole workspace over the socket, name and config included.

Fixed here with the same rule and seven tests; five of the seven fail if the fix is reverted. Also removes the org scope from the starter project, which is created bound to a team and was the last project insert still announcing itself workspace-wide.

bun run verify exits 0: lint, comment policy, byte policy, typecheck and 1916 tests.

A team restricted project and its milestones were published on the organization scope, so every member of the workspace received rows an HTTP reader gets a 404 for. Both now emit the scopes of the teams that own the project and keep the organization scope only while the project belongs to no team, which is the same rule the realtime server authorizes a project scope with.
Every saved view was announced on the organization scope, so an unshared view and its filter reached the whole workspace. A view now carries the organization scope only while it is shared, and turning a shared view private tells the workspace the view is gone without carrying its contents.
Nothing rechecked a session once a socket was authenticated, so a deleted or expired session kept its socket. The hub now asks Postgres for the sessions behind its open connections on an interval and closes any connection whose session has gone, in one query per sweep.
apps/web owns orbit_test_web but never pointed at it, so any query in a web test would have reached the development database and three suites stubbed the drizzle client instead. A module mock reaches every file in the run, so a single stubbed client made a real query impossible anywhere in the suite. The preload now resolves the lane database like every other package and the three suites use it.
Signing out deleted the session row and cleared the cookie but told nothing else, so the websocket that session opened stayed subscribed. The auth route now reads the session before better-auth deletes it and publishes the revocation once the sign out succeeds, which is what the hub already listens for.
Only write tools were gated, so a token that never asked for orbit.read still read the whole workspace through get_me, search_issues and every other read tool. Registration now needs the matching scope on both sides, the default is deny, and a token holding neither orbit scope is refused with a 403 before any tool exists.
A presigned PUT carried no size, so the holder of one url could store an object of any size and nothing ever removed it. The signature now covers content-length, so the object store itself rejects a body that does not match, and the driver refuses to sign a length past the upload cap.
A crafted issue, project or label name starting with an equals sign, a plus, a minus, an at sign, a tab or a carriage return became a live formula when the export opened in a spreadsheet. Those cells are now prefixed and quoted, while a number stays a number.
The verification pass on the security follow ups found the same leak the
branch had just closed in work/view-service.ts still live in the
analytics saved view service, which the branch never touched. viewScopes
there returned the organization scope unconditionally, so a dashboard
created with shared defaulting to false was owner only over REST and
broadcast to every connected member of the workspace, name and config
included. It was reproduced against the real database before this fix.

The rule is now the one the sibling file uses: a private view carries its
owner alone, and unsharing publishes a delete on the organization scope
so a view that was shared leaves everybody else's sidebar rather than
going stale there.

Also drops the organization scope from the starter project, which is
created bound to a team and was the one remaining project insert still
announcing itself workspace wide.
@vercel

vercel Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
orbit Ready Ready Preview Aug 6, 2026 1:38pm

Request Review

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imshashank has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This pull request aligns synchronization scopes with access rules, adds realtime session sweeping and sign-out revocation, enforces upload sizes, separates MCP read/write authorization, hardens CSV export, and converts selected web tests to database-backed fixtures.

Changes

Synchronization visibility

Layer / File(s) Summary
Project and milestone scope resolution
packages/core/src/work/project-service.ts, packages/core/src/work/milestone-service.ts, packages/core/src/org/starter-content.ts, packages/core/src/test-support.ts, packages/core/tests/work/*, CLAUDE.md
Project and milestone actions now use team and project scopes for restricted work, with organization fallback when no team exists.
Saved-view sharing and withdrawal
packages/core/src/work/view-service.ts, packages/core/src/analytics/saved-view.ts, packages/core/tests/analytics/saved-view-scopes.test.ts, packages/core/tests/work/view-service.test.ts
Private views remain owner-scoped. Shared views use organization scope. Unsharing emits a deletion action for organization subscribers.

Realtime session invalidation

Layer / File(s) Summary
Session lookup and periodic sweeping
packages/realtime-server/src/auth.ts, packages/realtime-server/src/hub.ts, apps/realtime/tests/session-revocation.test.ts
The realtime hub closes sockets for deleted or expired sessions and preserves sockets with live sessions.
Sign-out revocation wiring
apps/web/src/lib/auth/sign-out.ts, apps/web/src/app/api/auth/[...all]/route.ts, apps/web/tests/lib/auth/sign-out.test.ts
Successful sign-out requests publish session-revocation events and close the matching realtime socket.

Upload size enforcement

Layer / File(s) Summary
Content-length contract and validation
packages/services/src/storage/types.ts, packages/services/src/storage/s3.ts, packages/services/tests/storage/*
Upload targets require a positive safe-integer size, enforce the maximum, sign content-length, and return the requested limit.
Presign endpoint integration
apps/web/src/app/api/account/avatar/presign/route.ts, apps/web/src/app/api/attachments/presign/route.ts
Avatar and attachment endpoints pass validated upload sizes to storage target creation.

MCP scope authorization

Layer / File(s) Summary
Read and write tool permissions
packages/mcp-server/src/server.ts, packages/mcp-server/src/tools/support.ts, packages/mcp-server/tests/auth.test.ts, CLAUDE.md
MCP authorization separates orbit.read and orbit.write. Requests without either scope return 403, and tool registration exposes only permitted tools.

CSV output safety

Layer / File(s) Summary
Formula-safe CSV serialization
apps/web/src/features/analytics/csv.ts, apps/web/tests/features/analytics/csv.test.ts
CSV serialization preserves numeric values, escapes quotes, quotes delimiter-containing fields, and neutralizes formula-like strings.

Database-backed test infrastructure

Layer / File(s) Summary
Persisted web test fixtures
apps/web/tests-preload.ts, apps/web/tests/app/api/standup-board.test.ts, apps/web/tests/lib/auth/server-session-domain.test.ts
Selected tests now initialize a lane database and use persisted users, organizations, teams, issues, labels, and relationships.
Bootstrap test simplification
apps/web/tests/lib/api/bootstrap.test.ts
The bootstrap test removes database mocking and uses direct imports.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • Noveum/orbit#4: Both changes modify project, milestone, and view synchronization scopes.
  • Noveum/orbit#89: Both changes modify MCP authorization and tool registration.
  • Noveum/orbit#31: Both changes modify session revocation and realtime socket invalidation.

Suggested reviewers: pulkitxm

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the security fixes and the additional analytics view leak addressed by the changeset.
Description check ✅ Passed The description directly explains the security findings, implemented fixes, verification approach, and related test coverage.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/security-review-followups

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (4)
apps/web/tests/lib/auth/sign-out.test.ts (2)

7-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the @/ alias instead of deep relative imports.

Lines 7 and 8 reach into src with ../../../src/.... Inside apps/web, imports must use the @/ alias. The alias also keeps the paths stable when the test file moves.

♻️ Proposed change
-import { POST as authPost } from '../../../src/app/api/auth/[...all]/route.ts';
-import { auth } from '../../../src/lib/auth/server.ts';
+import { POST as authPost } from '`@/app/api/auth/`[...all]/route.ts';
+import { auth } from '`@/lib/auth/server.ts`';

As per coding guidelines: "Use @orbit/db and @orbit/shared workspace aliases; inside apps/web, use @/ imports."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/lib/auth/sign-out.test.ts` around lines 7 - 8, Replace the
deep relative imports for authPost and auth in sign-out.test.ts with the
apps/web `@/` alias, preserving the existing module targets and test behavior.

Source: Coding guidelines


123-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the implicit any from the ready-message assertion.

JSON.parse(raw) returns any, so JSON.parse(raw).type is an unchecked any access. The guidelines forbid any in TypeScript. Parse the frame with a Zod schema, or narrow the parsed value before reading type.

♻️ Proposed change
+const readyFrameSchema = z.object({ type: z.string() });
+
 async function openSocket(member: SignedIn): Promise<FakeSocket> {
@@
   await settle(() => socket.sent.length > 0);
-  expect(socket.sent.map((raw) => JSON.parse(raw).type)).toContain('ready');
+  const types = socket.sent.map((raw) => readyFrameSchema.parse(JSON.parse(raw) as unknown).type);
+  expect(types).toContain('ready');
   return socket;
 }

As per coding guidelines: "Use strict TypeScript: do not use any or non-null assertions" and "Validate every external input with Zod."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/lib/auth/sign-out.test.ts` around lines 123 - 125, Update the
ready-message assertion in the socket helper to validate each parsed frame with
the existing Zod validation approach before accessing its type. Replace the
direct JSON.parse(raw).type access with a narrowed, typed result so no implicit
any remains, while preserving the existing ready-message containment check.

Source: Coding guidelines

apps/realtime/tests/session-revocation.test.ts (1)

60-62: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the local server binding to avoid shadowing.

Line 21 declares a module-level server. Each new test declares a local const server, which shadows it. A distinct name, for example sweeping, makes the scope explicit and avoids accidental use of the shared server.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/realtime/tests/session-revocation.test.ts` around lines 60 - 62, Rename
the local server binding returned by the sweepingServer test setup and update
its references to avoid shadowing the module-level server declaration; use a
distinct name such as sweeping while preserving the existing server behavior.
packages/realtime-server/src/hub.ts (1)

532-537: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Consider a re-entrancy guard for the session sweep.

setInterval starts a new sweep even when the previous sweep has not finished. If a database query is slow, concurrent sweeps issue duplicate IN queries for the same session IDs. A boolean guard keeps one sweep in flight at a time.

♻️ Proposed guard
+  let sweeping = false;
   const sessionSweeper = setInterval(() => {
+    if (sweeping) return;
+    sweeping = true;
     sweepSessions().catch((error: unknown) => {
       logger.error('session sweep failed', errorFields(error));
-    });
+    }).finally(() => {
+      sweeping = false;
+    });
   }, sessionSweepIntervalMs);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/realtime-server/src/hub.ts` around lines 532 - 537, Update the
interval callback around sessionSweeper to track whether sweepSessions is
already in flight, skip starting another sweep while that guard is set, and
clear the guard after the promise settles, including failures. Preserve the
existing error logging and interval behavior for subsequent sweeps.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/src/lib/auth/sign-out.ts`:
- Around line 21-26: Update the sign-out flow around auth.api.getSession and
publishSessionRevoked so failures are caught and logged without replacing the
completed sign-out response with a 500. Preserve the existing response return
behavior, while ensuring session lookup failures are handled before proceeding
and Redis revocation remains best effort; use the project’s typed domain-error
and route-mapping conventions where applicable, and log each failure rather than
silently swallowing it.

In `@apps/web/tests/app/api/standup-board.test.ts`:
- Around line 150-169: Replace the manual beforeAll/afterAll fixture setup and
cleanup in apps/web/tests/app/api/standup-board.test.ts:150-169 with the
project’s rollback transaction fixture, ensuring seed setup and test mutations
run against the real test database and always roll back. In
apps/web/tests/lib/auth/server-session-domain.test.ts:16-21, insert users
through the same rollback transaction fixture; update both sites to use the
established fixture rather than manual persistence cleanup.

In `@apps/web/tests/lib/api/bootstrap.test.ts`:
- Line 3: Update the bootstrapVersion import in the test to use the configured
`@/` alias instead of a relative path, preserving the same web source module.

In `@packages/core/src/work/project-service.ts`:
- Line 267: Update updateProject() to capture the project’s existing reach
scopes before replaceProjectTeams() removes old projectTeam rows, then publish
withdrawal/delete notifications for revoked teams before publishing updates for
the new scopes from projectScopes(). Add coverage in the project-service tests
for team reassignment and verify both removed-team notifications and new-scope
updates.

In `@packages/core/src/work/view-service.ts`:
- Around line 223-236: The withdrawal actions in unshareActions and the
corresponding analytics-view withdrawal logic must exclude the view owner.
Update packages/core/src/work/view-service.ts:223-236 and
packages/core/src/analytics/saved-view.ts:61-80 to use a recipient-aware
withdrawal mechanism that delivers the organization-scoped deletion only to
colleagues, while preserving the owner’s private view; add regression tests
confirming colleagues remove the view and the owner retains it.

In `@packages/mcp-server/src/server.ts`:
- Around line 31-32: Add a regression test covering comma-separated scopes by
configuring the client with “openid,orbit.read” and asserting it can
successfully invoke a read tool. Place it alongside the existing scope
authorization tests and ensure the assertion would fail if granted stopped
splitting on commas.

In `@packages/mcp-server/tests/auth.test.ts`:
- Around line 159-204: Replace the readOnlyNames-derived expectations in the
read- and write-scoped access tests with independently defined expected read and
write tool-name inventories. Assert exact advertised tool sets for both scoped
clients, while retaining the denied-call checks, so misclassified tools cause
the tests to fail.

In `@packages/services/tests/storage/round-trip.test.ts`:
- Around line 177-199: The upload-length test should also cover bodies smaller
than the declared size. Extend the test around createUploadTarget and the
existing oversized request with a smaller-body request using the same target,
then assert a failure status and that storage().stat(key) remains null before
retaining the valid exact-size upload assertions.

---

Nitpick comments:
In `@apps/realtime/tests/session-revocation.test.ts`:
- Around line 60-62: Rename the local server binding returned by the
sweepingServer test setup and update its references to avoid shadowing the
module-level server declaration; use a distinct name such as sweeping while
preserving the existing server behavior.

In `@apps/web/tests/lib/auth/sign-out.test.ts`:
- Around line 7-8: Replace the deep relative imports for authPost and auth in
sign-out.test.ts with the apps/web `@/` alias, preserving the existing module
targets and test behavior.
- Around line 123-125: Update the ready-message assertion in the socket helper
to validate each parsed frame with the existing Zod validation approach before
accessing its type. Replace the direct JSON.parse(raw).type access with a
narrowed, typed result so no implicit any remains, while preserving the existing
ready-message containment check.

In `@packages/realtime-server/src/hub.ts`:
- Around line 532-537: Update the interval callback around sessionSweeper to
track whether sweepSessions is already in flight, skip starting another sweep
while that guard is set, and clear the guard after the promise settles,
including failures. Preserve the existing error logging and interval behavior
for subsequent sweeps.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d19d5045-6adf-43aa-b015-1ffb4a595bb0

📥 Commits

Reviewing files that changed from the base of the PR and between 807487f and 9a3b0fe.

📒 Files selected for processing (32)
  • CLAUDE.md
  • apps/realtime/tests/session-revocation.test.ts
  • apps/web/src/app/api/account/avatar/presign/route.ts
  • apps/web/src/app/api/attachments/presign/route.ts
  • apps/web/src/app/api/auth/[...all]/route.ts
  • apps/web/src/features/analytics/csv.ts
  • apps/web/src/lib/auth/sign-out.ts
  • apps/web/tests-preload.ts
  • apps/web/tests/app/api/standup-board.test.ts
  • apps/web/tests/features/analytics/csv.test.ts
  • apps/web/tests/lib/api/bootstrap.test.ts
  • apps/web/tests/lib/auth/server-session-domain.test.ts
  • apps/web/tests/lib/auth/sign-out.test.ts
  • packages/core/src/analytics/saved-view.ts
  • packages/core/src/org/starter-content.ts
  • packages/core/src/test-support.ts
  • packages/core/src/work/milestone-service.ts
  • packages/core/src/work/project-service.ts
  • packages/core/src/work/view-service.ts
  • packages/core/tests/analytics/saved-view-scopes.test.ts
  • packages/core/tests/work/milestone-service.test.ts
  • packages/core/tests/work/project-service.test.ts
  • packages/core/tests/work/view-service.test.ts
  • packages/mcp-server/src/server.ts
  • packages/mcp-server/src/tools/support.ts
  • packages/mcp-server/tests/auth.test.ts
  • packages/realtime-server/src/auth.ts
  • packages/realtime-server/src/hub.ts
  • packages/services/src/storage/s3.ts
  • packages/services/src/storage/types.ts
  • packages/services/tests/storage/round-trip.test.ts
  • packages/services/tests/storage/storage.test.ts

Comment on lines +21 to +26
const session = await auth.api.getSession({ headers: request.headers });
const response = await handle(request);
const userId = session?.user.id;
if (userId === undefined || !response.ok) return response;
await publishSessionRevoked(userId);
return response;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not let a Redis publish failure fail a completed sign-out.

Line 25 awaits publishSessionRevoked without error handling. publishSessionRevoked publishes to Redis and can reject, for example when the Redis connection is down. The sign-out already completed at that point, and Better Auth already deleted the session row and cleared the cookie. The rejection propagates out of the route handler, so the client receives a 500 for a sign-out that succeeded, and a client that retries or reports an error sees inconsistent state.

Revocation is best effort here. The hub sweep in packages/realtime-server/src/hub.ts closes the socket on the next pass. Catch and log the failure instead of returning it.

Line 21 also calls auth.api.getSession without error handling. If that call rejects, the sign-out request never reaches handlers.POST.

🛡️ Proposed fix
-  const session = await auth.api.getSession({ headers: request.headers });
+  const session = await auth.api.getSession({ headers: request.headers }).catch(() => null);
   const response = await handle(request);
   const userId = session?.user.id;
   if (userId === undefined || !response.ok) return response;
-  await publishSessionRevoked(userId);
+  try {
+    await publishSessionRevoked(userId);
+  } catch (error: unknown) {
+    console.error('[orbit] session revocation publish failed', error);
+  }
   return response;

As per coding guidelines: "Throw typed domain errors from @orbit/shared/errors; route handlers must map them to responses and never silently swallow errors." Log the failure so it is not swallowed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/lib/auth/sign-out.ts` around lines 21 - 26, Update the sign-out
flow around auth.api.getSession and publishSessionRevoked so failures are caught
and logged without replacing the completed sign-out response with a 500.
Preserve the existing response return behavior, while ensuring session lookup
failures are handled before proceeding and Redis revocation remains best effort;
use the project’s typed domain-error and route-mapping conventions where
applicable, and log each failure rather than silently swallowing it.

Source: Coding guidelines

Comment on lines +150 to +169
beforeAll(async () => {
await seedIssuesWithLabels();
});

beforeEach(async () => {
sessionHolder.value = session;
board.since = SINCE;
board.issues = [
{ id: 'issue_1', title: 'Ship the importer', assigneeId: 'user_2' },
{ id: 'issue_2', title: 'Fix the socket', assigneeId: 'user_2' },
{ id: seeded.labelledIssueId, title: 'Ship the importer', assigneeId: 'user_2' },
{ id: seeded.plainIssueId, title: 'Fix the socket', assigneeId: 'user_2' },
];
board.workload = [{ userId: 'user_2', open: 2, inProgress: 1, completedSince: 3 }];
labelLinks.length = 0;
await db.delete(schema.issueLabel).where(eq(schema.issueLabel.issueId, seeded.labelledIssueId));
received.length = 0;
});

afterAll(() => {
mock.module('@orbit/db', () => dbModule);
afterAll(async () => {
mock.module('@orbit/core', () => coreModule);
await db.delete(schema.organization).where(eq(schema.organization.id, seeded.organizationId));
await db.delete(schema.user).where(eq(schema.user.id, seeded.userId));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Use rollback transactions for persisted test fixtures.

Manual cleanup does not protect the database if setup or a test fails. Run fixture setup and mutations in a test transaction that always rolls back.

  • apps/web/tests/app/api/standup-board.test.ts#L150-L169: Replace the beforeAll and afterAll cleanup lifecycle with a rollback transaction fixture.
  • apps/web/tests/lib/auth/server-session-domain.test.ts#L16-L21: Insert users through the same rollback transaction fixture.

As per coding guidelines, database tests must use the real test database in a rollback transaction.

📍 Affects 2 files
  • apps/web/tests/app/api/standup-board.test.ts#L150-L169 (this comment)
  • apps/web/tests/lib/auth/server-session-domain.test.ts#L16-L21
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/app/api/standup-board.test.ts` around lines 150 - 169, Replace
the manual beforeAll/afterAll fixture setup and cleanup in
apps/web/tests/app/api/standup-board.test.ts:150-169 with the project’s rollback
transaction fixture, ensuring seed setup and test mutations run against the real
test database and always roll back. In
apps/web/tests/lib/auth/server-session-domain.test.ts:16-21, insert users
through the same rollback transaction fixture; update both sites to use the
established fixture rather than manual persistence cleanup.

Source: Coding guidelines

}));

const { bootstrapVersion } = await import('../../../src/lib/api/bootstrap.ts');
import { bootstrapVersion } from '../../../src/lib/api/bootstrap.ts';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the @/ alias for the web source import.

Line 3 uses a relative import inside apps/web. Replace it with the configured @/ alias to follow the repository convention and avoid brittle path depth.

Proposed fix
-import { bootstrapVersion } from '../../../src/lib/api/bootstrap.ts';
+import { bootstrapVersion } from '`@/lib/api/bootstrap`';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { bootstrapVersion } from '../../../src/lib/api/bootstrap.ts';
import { bootstrapVersion } from '`@/lib/api/bootstrap`';
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/lib/api/bootstrap.test.ts` at line 3, Update the
bootstrapVersion import in the test to use the configured `@/` alias instead of a
relative path, preserving the same web source module.

Source: Coding guidelines

syncId,
organizationId: principal.organizationId,
scopes: projectScopes(project),
scopes: await projectScopes(tx, project),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate SyncAction consumers and project delete handling.
fd -t f -e ts . packages apps | xargs rg -n -C 4 \
  'SyncAction|model:\s*["'\'']project["'\'']|action:\s*["'\'']delete["'\'']|case\s+["'\'']delete["'\'']'

# Inspect the reassignment coverage.
rg -n -C 8 'follows the project when its teams change|teamIds: \[\.\.\.stranger\.teamIds\]' \
  packages/core/tests/work/project-service.test.ts

Repository: Noveum/orbit

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate project-service and tests:"
fd -t f -e ts project-service packages/core src apps | sed 's#^\./##'

echo
echo "Relevant project-service sections:"
wc -l packages/core/src/work/project-service.ts
sed -n '220,290p' packages/core/src/work/project-service.ts
sed -n '320,370p' packages/core/src/work/project-service.ts
sed -n '480,530p' packages/core/src/work/project-service.ts

echo
echo "Search projectScopes/projectReachScopes/updateProject functions:"
rg -n -C 6 'function (projectScopes|projectReachScopes|replaceProjectTeams|updateProject)|export async function (projectScopes|projectReachScopes|replaceProjectTeams|updateProject)' packages/core/src/work/project-service.ts

echo
echo "Project sync tests around team reassignment:"
rg -n -C 10 'teamIds: \\[\\.\\.\\.stranger\\.teamIds\\]|follows the project when its teams change|updateProject|replaceProjectTeams|projectScopes' packages/core/tests/work/project-service.test.ts

Repository: Noveum/orbit

Length of output: 11862


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Project-service implementation details:"
sed -n '28,170p' packages/core/src/work/project-service.ts

echo
echo "Milestone-service team-scoped delete implementation:"
sed -n '140,165p' packages/core/src/work/milestone-service.ts

echo
echo "Sync shared model schema:"
sed -n '1,60p' packages/shared/src/events/sync.ts

echo
echo "Web sync tests around project deletion:"
rg -n -C 8 'project|milestone|delete.*project|model:\s*["'\'']project["'\'']|action:\s*["'\'']delete["'\'']' apps/web/tests/lib/query/sync.test.ts

echo
echo "Search for project/milestone delete redactions in apps:"
rg -n -C 4 'model:\s*["'\'']project["'\''].*(action:\s*["'\'']delete["'\''].*)|action:\s*["'\'']delete["'\''].*(model:\s*["'\'']project["'\'']|model:\s*["'\'']milestone["'\''])|model:\s*["'\'']milestone["'\''].*action:\s*["'\'']delete["'\'']' apps packages/realtime-client src 2>/dev/null || true

Repository: Noveum/orbit

Length of output: 10103


Notify removed project teams during reassignment.

replaceProjectTeams() deletes the old projectTeam rows before projectScopes() runs, so updateProject() only publishes the project: update action to members who remain on the project. Capture the old reach scopes before updating, publish a withdrawal/delete for revoked teams, then publish updates for the new reach scopes. Also cover this case in packages/core/tests/work/project-service.test.ts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/work/project-service.ts` at line 267, Update
updateProject() to capture the project’s existing reach scopes before
replaceProjectTeams() removes old projectTeam rows, then publish
withdrawal/delete notifications for revoked teams before publishing updates for
the new scopes from projectScopes(). Add coverage in the project-service tests
for team reassignment and verify both removed-team notifications and new-scope
updates.

Comment on lines +223 to +236
function unshareActions(input: UnshareInput): SyncAction[] {
if (!isShared(input.before) || isShared(input.after)) return [];
return [
buildSyncAction({
syncId: input.syncId,
organizationId: input.after.organizationId,
scopes: [scopes.organization(input.after.organizationId)],
action: 'delete',
model: 'view',
modelId: input.after.id,
data: { id: input.after.id },
actor: input.actor,
}),
];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not deliver the withdrawal action to the owner.

An organization-scoped withdrawal also reaches the owner. Both functions return an owner-scoped private update followed by an organization-scoped delete for the same view. A client that applies both actions removes the owner's private view.

Use a recipient-aware withdrawal mechanism that excludes the owner, or make the client ignore a withdrawal addressed to that view owner. Add regression tests that confirm colleagues remove the view and the owner retains it.

  • packages/core/src/work/view-service.ts#L223-L236: exclude the owner from the shared-view withdrawal.
  • packages/core/src/analytics/saved-view.ts#L61-L80: exclude the owner from the analytics-view withdrawal.

As per coding guidelines, private saved-view scopes contain only the owner.

📍 Affects 2 files
  • packages/core/src/work/view-service.ts#L223-L236 (this comment)
  • packages/core/src/analytics/saved-view.ts#L61-L80
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/work/view-service.ts` around lines 223 - 236, The
withdrawal actions in unshareActions and the corresponding analytics-view
withdrawal logic must exclude the view owner. Update
packages/core/src/work/view-service.ts:223-236 and
packages/core/src/analytics/saved-view.ts:61-80 to use a recipient-aware
withdrawal mechanism that delivers the organization-scoped deletion only to
colleagues, while preserving the owner’s private view; add regression tests
confirming colleagues remove the view and the owner retains it.

Source: Coding guidelines

Comment on lines +31 to +32
function granted(scopes: string): Set<string> {
return new Set(scopes.split(/[\s,]+/).filter(Boolean));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Add a comma-separated scope regression test.

granted accepts comma-separated scopes. The supplied tests use only whitespace-separated scopes. If this parser changes to split only on whitespace, comma-scoped clients will be rejected and the test suite will still pass.

Add a test with openid,orbit.read and verify that the client can use a read tool. As per coding guidelines, “A feature is not complete until it has tests that would fail if the feature broke.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mcp-server/src/server.ts` around lines 31 - 32, Add a regression
test covering comma-separated scopes by configuring the client with
“openid,orbit.read” and asserting it can successfully invoke a read tool. Place
it alongside the existing scope authorization tests and ensure the assertion
would fail if granted stopped splitting on commas.

Source: Coding guidelines

Comment on lines +159 to +204
it('offers a read scoped token exactly the read tools and refuses a write call', async () => {
const full = await clientWith('openid orbit.read orbit.write');
const reader = await clientWith('openid orbit.read');
try {
const everything = await toolNames(full);
const reads = await readOnlyNames(full);
const writes = everything.filter((name) => !reads.includes(name));
expect(reads.length).toBeGreaterThan(0);
expect(writes.length).toBeGreaterThan(0);

const offered = await toolNames(reader);
expect([...offered].sort()).toEqual([...reads].sort());
for (const name of writes) {
expect(offered).not.toContain(name);
}

expect((await reader.result('get_me'))['role']).toBe('admin');
const denied = await reader.call('create_team', { name: 'Smuggled', key: 'SMUG' });
expect(denied.isError).toBe(true);
const teams = (await full.result('list_teams'))['teams'] as { name: string }[];
expect(teams.map((team) => team.name)).not.toContain('Smuggled');
} finally {
await full.close();
await reader.close();
}
});

it('offers a write scoped token no read tool and refuses a read call', async () => {
const full = await clientWith('openid orbit.read orbit.write');
const writer = await clientWith('openid orbit.write');
try {
const reads = await readOnlyNames(full);
const offered = await toolNames(writer);

expect(offered.length).toBeGreaterThan(0);
expect(reads.length).toBeGreaterThan(0);
for (const name of reads) {
expect(offered).not.toContain(name);
}
expect((await writer.call('get_me')).isError).toBe(true);
expect((await writer.call('search_issues', { query: 'anything' })).isError).toBe(true);
} finally {
await full.close();
await writer.close();
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Assert tool access against an independent inventory.

The test derives reads from readOnlyHint. packages/mcp-server/src/tools/support.ts also uses the same readOnly value to grant access. If a mutating tool is misclassified as read-only, a read-scoped client receives it and this test passes.

Define the expected read and write tool names independently. Assert the exact advertised sets for read-scoped and write-scoped clients. As per coding guidelines, “A feature is not complete until it has tests that would fail if the feature broke.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mcp-server/tests/auth.test.ts` around lines 159 - 204, Replace the
readOnlyNames-derived expectations in the read- and write-scoped access tests
with independently defined expected read and write tool-name inventories. Assert
exact advertised tool sets for both scoped clients, while retaining the
denied-call checks, so misclassified tools cause the tests to fail.

Source: Coding guidelines

Comment on lines +177 to +199
it('refuses an upload larger than the presigned length and stores nothing', async () => {
const key = `org_round_trip/2026/07/${Bun.randomUUIDv7()}-oversized.txt`;
const declared = new Blob(['ten bytes!']);
const target = await storage().createUploadTarget(key, 'text/plain', declared.size);

const oversized = await fetch(target.url, {
method: target.method,
headers: { ...target.headers, origin: PRODUCTION_ORIGIN },
body: new Blob([`${'x'.repeat(declared.size * 100)}`]),
});

expect(oversized.status).toBeGreaterThanOrEqual(400);
expect(await storage().stat(key)).toBeNull();

const honest = await fetch(target.url, {
method: target.method,
headers: { ...target.headers, origin: PRODUCTION_ORIGIN },
body: declared,
});
written.push(key);
expect(honest.status).toBe(200);
expect((await storage().stat(key))?.size).toBe(declared.size);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Test a body smaller than the declared length.

The test verifies an oversized body, but it does not verify the lower boundary. Add a request with a body smaller than declared.size. Assert a failure status and assert that storage().stat(key) is null.

This verifies that the presigned target enforces the exact declared length. As per coding guidelines, "A feature is not complete until it has tests that would fail if the feature broke."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/services/tests/storage/round-trip.test.ts` around lines 177 - 199,
The upload-length test should also cover bodies smaller than the declared size.
Extend the test around createUploadTarget and the existing oversized request
with a smaller-body request using the same target, then assert a failure status
and that storage().stat(key) remains null before retaining the valid exact-size
upload assertions.

Source: Coding guidelines

@imshashank
imshashank merged commit f020c86 into main Aug 6, 2026
7 checks passed
imshashank added a commit that referenced this pull request Aug 7, 2026
… for them (#121)

The two discovery documents disagreed. The authorization server offered
orbit.read and orbit.write, but the protected resource document, which is
the one an MCP client reads to learn what to request, listed only openid,
profile, email and offline_access, because it was delegating wholesale to
better-auth's default.

So a client asked for a token without orbit.read, and every tool call was
then refused by the scope enforcement added in #115. Production had one
live token and it carried exactly those four scopes. Re-authorising would
have minted another broken one, which is why this looked unfixable from
the client side.

The protected resource document now advertises MCP_SCOPES, the same list
the authorization server issues from, and a test pins the two together so
adding a scope to one without the other fails the build.
@imshashank
imshashank deleted the fix/security-review-followups branch August 7, 2026 18:53

This branch was successfully deployed

1 active deployment
Preview — 9a3b0fee Deployed Aug 6, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant