Skip to content

feat(webapp): management API for orgs, projects, members, and settings#4146

Open
nicktrn wants to merge 13 commits into
mainfrom
feat/local-management-api-tri-11579
Open

feat(webapp): management API for orgs, projects, members, and settings#4146
nicktrn wants to merge 13 commits into
mainfrom
feat/local-management-api-tri-11579

Conversation

@nicktrn

@nicktrn nicktrn commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Draft for review/discussion. Opening early to get feedback on scope, shape, and the auth model before polishing.

Summary

Adds a set of PAT-authenticated management API endpoints so orgs, projects, members/invites, environment variables, and a few project/environment settings can be managed programmatically (scripting, automation) rather than only through the dashboard. Each route is a thin wrapper over the existing service the dashboard already uses, with the same authorization applied at the route layer - no new business logic.

Endpoints

Organizations

  • POST /api/v1/orgs - create an org (createOrganization)
  • PATCH /api/v1/orgs/:orgParam - rename (title)
  • DELETE /api/v1/orgs/:orgParam - soft-delete (DeleteOrganizationService; keeps the active-subscription guard)

Members & invites

  • GET /api/v1/orgs/:orgParam/members - list members + pending invites
  • DELETE /api/v1/orgs/:orgParam/members/:memberId - remove a member (last-member guarded)
  • POST /api/v1/orgs/:orgParam/invites - invite by email (inviteMembers, sends the invite email)
  • DELETE /api/v1/orgs/:orgParam/invites/:inviteId - revoke an invite

Projects

  • PATCH /api/v1/projects/:projectRef - rename (ProjectSettingsService)
  • DELETE /api/v1/projects/:projectRef - soft-delete (DeleteProjectService)
  • PUT /api/v1/projects/:projectRef/default-region - set the default region by worker-group name (SetDefaultRegionService)
  • project GET/list now return defaultRegion (worker-group name, or null when unset)

Environments

  • POST /api/v1/projects/:projectRef/:env/pause and /resume (PauseEnvironmentService)
  • POST /api/v1/projects/:projectRef/:env/regenerate-api-key - rotate the env secret key (regenerateApiKey, RBAC write:apiKeys)
  • env var create now accepts an optional isSecret flag

Auth & authorization

  • All routes authenticate with a Personal Access Token (Authorization: Bearer tr_pat_...), following the existing api.v1.orgs.ts pattern.
  • Org-scoped routes re-apply the dashboard's RBAC gates via a small shared helper (organizationApiAccess.server.ts): membership resolution as the floor, plus read:members / manage:members ability checks. Env-tier routes reuse the existing authorizePatEnvironmentAccess.

Notes for reviewers

  • Everything wraps an existing service; the intent is API parity for things that are currently dashboard-only, not new behaviour.
  • @trigger.dev/core gets one additive field (defaultRegion on the project response) - changeset included, patch.
  • Open questions I'd like input on: is PAT the right auth for all of these (vs OAT for automation)? Should any of these be gated behind a flag or scope? Naming/shape of the routes.

@changeset-bot

changeset-bot Bot commented Jul 3, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 72e4443

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 28 packages
Name Type
@trigger.dev/core Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/plugins Patch
@trigger.dev/python Patch
@trigger.dev/redis-worker Patch
@trigger.dev/schema-to-json Patch
@trigger.dev/sdk Patch
@internal/cache Patch
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@trigger.dev/rbac Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@trigger.dev/sso Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/tsql Patch
@internal/zod-worker Patch
@internal/dashboard-agent Patch
@internal/sdk-compat-tests Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@nicktrn nicktrn changed the title feat(webapp): PAT-authenticated management API for orgs, projects, members, and settings feat(webapp): management API for orgs, projects, members, and settings Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This pull request adds organization API routes for create, list, update, delete, members, and invites, plus shared organization API access helpers. It also updates project and environment routes to expose and manage defaultRegion, adds pause/resume and API key regeneration actions, persists environment variable isSecret, updates core API schemas, and records the defaultRegion response change in a changeset.

Estimated code review effort: 4 (High)
Related issues: None specified.
Related PRs: None specified.
Suggested labels: api, webapp, core
Suggested reviewers: matt-aitken, ericallam

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is informative, but it does not follow the required template sections like Closes #issue, checklist, testing, changelog, or screenshots. Add the missing template sections: Closes #issue, checklist items, testing steps, changelog, and screenshots placeholders.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: a new management API for orgs, projects, members, and settings.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/local-management-api-tri-11579

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[bot]

This comment was marked as resolved.

@nicktrn

nicktrn commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Addressed the two actionable items: malformed/empty JSON now returns 400 (not 500) across all five new handlers (9573c59).

On the nitpick to extract a shared resolveEnvironmentForWriteAction helper across the pause/resume/regenerate-api-key routes: deferring for now. These three routes' auth is about to change - we're adding role-based (Owner) gating to the management API in a follow-up - so consolidating the auth flow now would just churn. I'll extract the shared helper as part of that RBAC pass, when the final auth shape is settled.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/webapp/app/routes/api.v1.orgs.$orgParam.ts (2)

17-19: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Reject whitespace-only organization titles.

Line 18 accepts " " because .min(1) runs before any normalization, allowing a visually blank title to be persisted.

Proposed fix
 const RenameOrgRequestBody = z.object({
-  title: z.string().min(1),
+  title: z.string().trim().min(1),
 });

23-24: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return an Allow header with 405 responses.

Clients receiving 405 Method Not Allowed should also get the supported methods for this route.

Proposed fix
   if (method !== "DELETE" && method !== "PATCH") {
-    return json({ error: "Method Not Allowed" }, { status: 405 });
+    return json(
+      { error: "Method Not Allowed" },
+      { status: 405, headers: { Allow: "DELETE, PATCH" } }
+    );
   }
🧹 Nitpick comments (1)
apps/webapp/app/services/organizationApiAccess.server.ts (1)

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

Document why this lookup must stay on primary Prisma.

The code already uses prisma; add the replica-lag rationale inline so this RBAC-scope lookup is not later moved to $replica.

Based on learnings, slug→org lookups for RBAC scope should use primary prisma and include an inline comment documenting replica-lag risk.

Proposed comment
 export async function resolveOrganizationForApiUser({
   orgParam,
   userId,
 }: {
   orgParam: string;
   userId: string;
 }): Promise<{ id: string; slug: string } | null> {
+  // Use the primary client here: replica lag can make slug→org RBAC scope resolution stale.
   return prisma.organization.findFirst({

Source: Learnings


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ba876ad0-e835-489a-8b2c-7cb22c9b0dc2

📥 Commits

Reviewing files that changed from the base of the PR and between 9573c59 and 0fcced7.

📒 Files selected for processing (4)
  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.default-region.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/webapp/app/routes/api.v1.projects.$projectRef.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.default-region.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (26)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (1, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 10)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (11, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (12, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (4, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 10)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (5, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 10)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (8, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (10, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 10)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 10)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (3, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (9, 12)
  • GitHub Check: internal / 🧪 Unit Tests: Internal (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 10)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 10)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 10)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 10)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 10)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: e2e / 🧪 CLI v3 tests (blacksmith-4vcpu-windows-2025 - npm)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
⚠️ CI failures not shown inline (2)

GitHub Actions: 🛡️ E2E Tests: Webapp Auth (full) / 🛡️ E2E Auth Tests (full): feat(webapp): management API for orgs, projects, members, and settings

Conclusion: failure

View job details

f6-40c8-9b89-bc6db0597577","timestamp":"","message":"Error querying clickhouse","level":"error"}
 {"error":{"name":"QueryError","message":"Unable to query clickhouse: connect ECONNREFUSED 127.0.0.1:19123","stack":"QueryError: Unable to query clickhouse: connect ECONNREFUSED 127.0.0.1:19123\n    at /home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:75637:17\n    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)\n    at async /home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:260:14\n    at async /home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:75588:18\n    at async ClickHouseRunsRepository.listRunRows (/home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:117775:36)\n    at async ClickHouseRunsRepository.listRunIds (/home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:117788:20)\n    at async ClickHouseRunsRepository.listRuns (/home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:117840:38)\n    at async /home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:35453:14\n    at async NextRunListPresenter.call (/home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:157156:39)\n    at async /home/runner/_work/trigger.dev/trigger.dev/apps/webapp/build/index.js:260120:21"},"url":"http://localhost:36693/api/v1/runs","http":{"requestId":"rdR5wdVhqRZ-wwXsNJvID","path":"/api/v1/runs","host":"localhost","method":"GET","abortController":{}},"timestamp":"","name":"webapp","message":"Error in loader","level":"error"}
 GET /api/v1/runs 500 - - 11.650 ms
 GET /api/v1/runs 403 - - 4.768 ms
 GET /api/v1/runs 403 - - 4.530 ms
 [][ERROR][`@clickhouse/client`][Connection] Query: HTTP request error.
 Arguments: {
   query: 'SELECT run_id, toUnixTimestamp64Milli(created_at) AS created_at_ms FROM trigger_dev.task_runs_v2 FINAL WHERE organization_id = {organizationId: String} AND project_id = {projectId: String} AND environmen...

GitHub Actions: 🛡️ E2E Tests: Webapp Auth (full) / 0_🛡️ E2E Auth Tests (full).txt: feat(webapp): management API for orgs, projects, members, and settings

Conclusion: failure

View job details

     'FORMAT JSONEachRow',
   search_params: 'query_id=c3d35a82-c585-4c78-9b0c-84001a5e4613&param_organizationId=cmr92h04j007bqnc06eawh7sy&param_projectId=cmr92h04k007dqnc0lt6v1a70&param_environmentId=cmr92h04k007fqnc0y97xkt3i&param_tasks=%5B%27task_a%27%2C%27task_b%27%5D&param_period=1782728281324&output_format_json_quote_64bit_integers=0&output_format_json_quote_64bit_floats=0&cancel_http_readonly_queries_on_client_close=1',
   with_abort_signal: false,
   session_id: undefined,
   query_id: 'c3d35a82-c585-4c78-9b0c-84001a5e4613',
   decompress_response: false,
   clickhouse_settings: {
     output_format_json_quote_64bit_integers: 0,
     output_format_json_quote_64bit_floats: 0,
     cancel_http_readonly_queries_on_client_close: 1
   }
 }
 Caused by: Error: connect ECONNREFUSED 127.0.0.1:19123
     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1638:16)
     at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
   errno: -111,
   code: 'ECONNREFUSED',
   syscall: 'connect',
   address: '127.0.0.1',
   port: 19123
 }
 {"name":"ClickHouse","error":{"message":"connect ECONNREFUSED 127.0.0.1:19123","stack":"Error: connect ECONNREFUSED 127.0.0.1:19123\n    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1638:16)\n    at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17)","name":"Error"},"query":"SELECT run_id, toUnixTimestamp64Milli(created_at) AS created_at_ms FROM trigger_dev.task_runs_v2 FINAL WHERE organization_id = {organizationId: String} AND project_id = {projectId: String} AND environment_id = {environmentId: String} AND task_identifier IN {tasks: Array(String)} AND created_at >= fromUnixTimestamp64Milli({period: Int64}) ORDER BY created_at DESC, run_id DESC LIMIT 26","params":{"organizationId":"cmr92h04j007bqnc06eawh7sy","projectId":"cmr92h04k007dqnc0lt6v1a70","environmentId":"cmr92h04k007fqnc0y97xkt3i","tasks":["task_a","task_b"],"period":1782728281324},"queryId":"c3d35a82-c585-4c78-9b0c-84001a5e46...
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

Files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use zod for validation in packages/core and apps/webapp

Files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

**/*.{ts,tsx,js,jsx}: Prefer static imports over dynamic import(); only use dynamic imports when resolving circular dependencies, enabling real code splitting, or conditionally loading a module at runtime.
Always import from @trigger.dev/sdk; never import from @trigger.dev/sdk/v3 or use deprecated client.defineJob.
In code that imports @trigger.dev/core, use subpath imports only and never import from the package root.

Files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Always use findFirst instead of findUnique for Prisma queries.

Files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
apps/webapp/app/routes/**/*.ts

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

Use Remix flat-file route naming with dot-separated segments in app/routes/ (for example, api.v1.tasks.$taskId.trigger.ts maps to /api/v1/tasks/:taskId/trigger).

Files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
🧠 Learnings (14)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.

Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.

Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.

Applied to files:

  • apps/webapp/app/routes/api.v1.orgs.$orgParam.ts
  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-03-26T09:02:07.973Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 3274
File: apps/webapp/app/services/runsReplicationService.server.ts:922-924
Timestamp: 2026-03-26T09:02:07.973Z
Learning: When parsing Trigger.dev task run annotations in server-side services, keep `TaskRun.annotations` strictly conforming to the `RunAnnotations` schema from `trigger.dev/core/v3`. If the code already uses `RunAnnotations.safeParse` (e.g., in a `#parseAnnotations` helper), treat that as intentional/necessary for atomic, schema-accurate annotation handling. Do not recommend relaxing the annotation payload schema or using a permissive “passthrough” parse path, since the annotations are expected to be written atomically in one operation and should not contain partial/legacy payloads that would require a looser parser.

Applied to files:

  • apps/webapp/app/services/organizationApiAccess.server.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.

Applied to files:

  • apps/webapp/app/services/organizationApiAccess.server.ts
🔇 Additional comments (3)
apps/webapp/app/services/organizationApiAccess.server.ts (2)

6-11: LGTM!


46-80: LGTM!

apps/webapp/app/routes/api.v1.orgs.$orgParam.ts (1)

27-59: LGTM!

@nicktrn nicktrn force-pushed the feat/local-management-api-tri-11579 branch from 96bc958 to 52e2b5b Compare July 6, 2026 10:49
@pkg-pr-new

pkg-pr-new Bot commented Jul 6, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@d621708

trigger.dev

npm i https://pkg.pr.new/trigger.dev@d621708

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@d621708

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@d621708

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@d621708

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@d621708

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@d621708

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@d621708

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@d621708

commit: d621708

@nicktrn nicktrn force-pushed the feat/local-management-api-tri-11579 branch from 52e2b5b to 11e40dd Compare July 6, 2026 10:57
coderabbitai[bot]

This comment was marked as resolved.

@nicktrn nicktrn marked this pull request as ready for review July 6, 2026 11:47
devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@nicktrn nicktrn force-pushed the feat/local-management-api-tri-11579 branch from 72e4443 to 018d6b7 Compare July 6, 2026 14:11

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 2 new potential issues.

View 1 additional finding in Devin Review.

Open in Devin Review

Comment on lines +57 to +62
const memberCount = await prisma.orgMember.count({
where: { organizationId: organization.id },
});
if (memberCount <= 1) {
return json({ error: "Cannot remove the last member of an organization" }, { status: 400 });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Concurrent member-removal requests can leave an organization with zero members

The last-member guard counts members and then removes one in separate steps (prisma.orgMember.count at api.v1.orgs.$orgParam.members.$memberId.ts:57-61, then removeTeamMember at line 64-68), so two simultaneous DELETE requests can both pass the count check and both proceed to remove their target.

Impact: An organization can end up with no members at all, making it permanently inaccessible.

TOCTOU race between count check and removal

The code at api.v1.orgs.$orgParam.members.$memberId.ts:57-68 first counts members:

const memberCount = await prisma.orgMember.count({
  where: { organizationId: organization.id },
});
if (memberCount <= 1) {
  return json({ error: "Cannot remove the last member..." }, { status: 400 });
}

Then removes the member in a separate call:

const removed = await removeTeamMember({ ... });

If two requests arrive concurrently (e.g. removing two different members from a 2-member org), both see memberCount === 2, both pass the guard, and both removals succeed — leaving zero members. The comment on line 55-56 explicitly notes that removeTeamMember does not enforce this invariant itself. A serializable transaction or an atomic conditional delete is needed to close the race window.

Prompt for agents
In api.v1.orgs.$orgParam.members.$memberId.ts, the member-count check (lines 57-62) and the removeTeamMember call (lines 64-68) are not atomic. Two concurrent DELETE requests can both pass the count guard and both remove their target, leaving the org with zero members.

To fix this, wrap the count check and the removal in a serializable transaction, or use an atomic approach such as: (1) attempt the delete inside a transaction that re-checks the count with a SELECT ... FOR UPDATE, or (2) use a Prisma interactive transaction that locks the orgMember rows for the organization before counting and deleting. The key requirement is that the count and the delete must be serialized so concurrent requests cannot both see the pre-deletion count.
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +155 to 158
context: async (params) => {
const orgId = await resolveOrgIdFromSlug(params.organizationSlug);
return orgId ? { organizationId: orgId } : {};
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 resolveOrgIdFromSlug returning empty context may weaken RBAC checks

In all three dashboard action refactors, the context callback calls resolveOrgIdFromSlug and returns {} when the org is not found (e.g. _app.orgs.$organizationSlug.settings._index/route.tsx:157). This means dashboardAction proceeds without an organizationId in its RBAC context. The RBAC ability object is then constructed without org scoping. Whether this is safe depends on how the RBAC fallback handles missing organizationId — in OSS mode it grants permissive access regardless, so the subsequent ability.can(...) checks would pass even without org context. The action body still validates membership via Prisma queries, so this is not exploitable, but it's worth understanding the interaction.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@nicktrn nicktrn force-pushed the feat/local-management-api-tri-11579 branch from 018d6b7 to d621708 Compare July 6, 2026 16:43
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