976171ea16
## 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_...`).
- Org/project routes are built on the PAT route builders in
`apiBuilder.server.ts`: `createLoaderPATApiRoute` (already existed) and
**`createActionPATApiRoute`** (added here - the loader builder had no
mutation counterpart). The builder runs auth, resolves the org/project
role-floor via `context`, and enforces a declarative `authorization`
block using the same RBAC actions the dashboard applies
(`manage:organization` / `read:members` / `manage:members` /
`manage:project`). Handlers keep a membership-scoped query as the floor,
so a non-member gets a 404. This also gives these routes `tenantContext`
user attribution (Sentry) and `ServiceValidationError`-to-status mapping
for free.
- **Membership floor (important).** The OSS RBAC fallback grants a
permissive ability, so `ability.can(...)` can't reject a non-member on
self-hosted. Every handler therefore resolves the target scoped to the
caller's membership (`members: { some: { userId } }`) → 404 for
non-members. `authorization` is the *role* gate; this is the *tenant*
gate. `resolveOrganizationForApiUser`
(`organizationApiAccess.server.ts`) is the org-tier version of the
existing `findProjectByRef` - org-addressed PAT routes are new, so no
such helper existed before.
- Env-tier routes reuse the existing `authorizePatEnvironmentAccess`
(`write:apiKeys`).
### What `createActionPATApiRoute` gives you
A route is pure declaration - the builder handles auth, RBAC,
validation, tracing, and error mapping:
```ts
export const action = createActionPATApiRoute(
{
method: "PUT", // one verb, or ["PATCH", "DELETE"] for multi-verb routes
params: ParamsSchema,
body: SetDefaultRegionRequestBody, // zod-validated
context: async ({ projectRef }) => { // resolve the org for the RBAC role-floor
const project = await prisma.project.findFirst({
where: { externalRef: projectRef, deletedAt: null },
select: { organizationId: true },
});
return project ? { organizationId: project.organizationId } : {};
},
authorization: { action: "manage", resource: () => ({ type: "project" }) },
},
async ({ params, body, authentication, ability }) => {
// auth + authz already enforced. Just do the work.
// `throw new ServiceValidationError("Region not found", 400)` → mapped to that status.
return json({ ok: true });
}
);
```
Handled for you, so handlers stay thin:
- **Method allowlist** - `method` accepts a verb or an array; any other
verb → `405` with an `Allow` header, *before* auth runs:
```ts
const allowedMethods = method ? (Array.isArray(method) ? method :
[method]) : undefined;
if (allowedMethods && !(allowedMethods as
string[]).includes(request.method.toUpperCase())) {
return json({ error: "Method not allowed" }, { status: 405, headers: {
Allow: allowedMethods.join(", ") } });
}
```
- **PAT / user-actor auth** in a single roundtrip → `401` on
missing/invalid/revoked token.
- **RBAC** - `context` computes the caller's role-floor for the target
org/project; `authorization` gates it → `403` with a structured error
body.
- **Sentry attribution** - `tenantContext.enrich({ userId })` so events
from the handler carry the acting user.
- **Typed errors** - a thrown `ServiceValidationError` is mapped to its
`.status` (default 400); anything else → `500`, and expected boundary
errors are logged as `warn` (kept out of Sentry).
- **Validation** - params / query / headers / body are all zod-checked →
`400` with details.
## Notes for reviewers
- Everything wraps an existing service; the intent is API parity for
things that are currently dashboard-only, not new behaviour.
- `createActionPATApiRoute` is new shared infra (the PAT + RBAC mutation
builder that didn't exist). It's self-contained - the loader builder and
existing routes are untouched.
- `@trigger.dev/core` gets one additive field (`defaultRegion` on the
project response, optional/nullable for client-server version skew) -
changeset included, patch.
- `removeTeamMember`'s last-member guard is now atomic (Serializable
transaction via the `$transaction` helper, with retry), so the dashboard
and API both get it server-side. Added a `## Transactions` rule to
`apps/webapp/CLAUDE.md` (always use the `$transaction` helper);
migrating the remaining direct usages is tracked in TRI-11698.
## Open questions
- ~~Is PAT the right auth (vs OAT for automation)?~~ **Resolved: PAT.**
Organization Access Tokens are currently internal-only (used by the
image builder) and not user-accessible, so they can't back this yet.
- Should any of these be gated behind a flag or scope?
- Naming/shape of the routes.
172 lines
4.5 KiB
TypeScript
172 lines
4.5 KiB
TypeScript
import type { Prisma, Project } from "@trigger.dev/database";
|
|
import { customAlphabet, nanoid } from "nanoid";
|
|
import slug from "slug";
|
|
import { $replica, prisma } from "~/db.server";
|
|
import { projectCreated } from "~/services/projectCreated.server";
|
|
import { ServiceValidationError } from "~/v3/services/common.server";
|
|
import { type Organization, createEnvironment } from "./organization.server";
|
|
export type { Project } from "@trigger.dev/database";
|
|
|
|
const externalRefGenerator = customAlphabet("abcdefghijklmnopqrstuvwxyz", 20);
|
|
|
|
type Options = {
|
|
organizationSlug: string;
|
|
name: string;
|
|
userId: string;
|
|
version: "v2" | "v3";
|
|
onboardingData?: Prisma.InputJsonValue;
|
|
};
|
|
|
|
export class ExceededProjectLimitError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = "ExceededProjectLimitError";
|
|
}
|
|
}
|
|
|
|
export async function createProject(
|
|
{ organizationSlug, name, userId, version, onboardingData }: Options,
|
|
attemptCount = 0
|
|
): Promise<Project & { organization: Organization }> {
|
|
//check the user has permissions to do this
|
|
const organization = await prisma.organization.findFirst({
|
|
select: {
|
|
id: true,
|
|
slug: true,
|
|
isActivated: true,
|
|
maximumConcurrencyLimit: true,
|
|
maximumProjectCount: true,
|
|
},
|
|
where: {
|
|
slug: organizationSlug,
|
|
members: { some: { userId } },
|
|
},
|
|
});
|
|
|
|
if (!organization) {
|
|
throw new Error(
|
|
`User ${userId} does not have permission to create a project in organization ${organizationSlug}`
|
|
);
|
|
}
|
|
|
|
if (version === "v3") {
|
|
if (!organization.isActivated) {
|
|
throw new ServiceValidationError(
|
|
"You must select a plan for this organization before creating projects.",
|
|
402
|
|
);
|
|
}
|
|
}
|
|
|
|
const projectCount = await prisma.project.count({
|
|
where: {
|
|
organizationId: organization.id,
|
|
deletedAt: null,
|
|
},
|
|
});
|
|
|
|
if (projectCount >= organization.maximumProjectCount) {
|
|
throw new ExceededProjectLimitError(
|
|
`This organization has reached the maximum number of projects (${organization.maximumProjectCount}).`
|
|
);
|
|
}
|
|
|
|
//ensure the slug is globally unique
|
|
const uniqueProjectSlug = `${slug(name)}-${nanoid(4)}`;
|
|
const projectWithSameSlug = await prisma.project.findFirst({
|
|
where: { slug: uniqueProjectSlug },
|
|
});
|
|
|
|
if (attemptCount > 100) {
|
|
throw new Error(`Unable to create project with slug ${uniqueProjectSlug} after 100 attempts`);
|
|
}
|
|
|
|
if (projectWithSameSlug) {
|
|
return createProject(
|
|
{
|
|
organizationSlug,
|
|
name,
|
|
userId,
|
|
version,
|
|
onboardingData,
|
|
},
|
|
attemptCount + 1
|
|
);
|
|
}
|
|
|
|
const project = await prisma.project.create({
|
|
data: {
|
|
name,
|
|
slug: uniqueProjectSlug,
|
|
organization: {
|
|
connect: {
|
|
slug: organizationSlug,
|
|
},
|
|
},
|
|
externalRef: `proj_${externalRefGenerator()}`,
|
|
version: version === "v3" ? "V3" : "V2",
|
|
// New projects run on the v2 engine. The Prisma column still defaults to V1
|
|
// for historical rows; the V1->V2 upgrade guards on worker-register / deploy
|
|
// stay in place to migrate existing legacy projects.
|
|
engine: "V2",
|
|
onboardingData,
|
|
},
|
|
include: {
|
|
organization: {
|
|
include: {
|
|
members: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
// Create the dev and prod environments
|
|
await createEnvironment({
|
|
organization,
|
|
project,
|
|
type: "PRODUCTION",
|
|
isBranchableEnvironment: false,
|
|
});
|
|
|
|
for (const member of project.organization.members) {
|
|
await createEnvironment({
|
|
organization,
|
|
project,
|
|
type: "DEVELOPMENT",
|
|
// We set this true but no backfill (yet!?) so never used
|
|
// for dev environments
|
|
isBranchableEnvironment: true,
|
|
member,
|
|
});
|
|
}
|
|
|
|
await projectCreated(organization, project);
|
|
|
|
return project;
|
|
}
|
|
|
|
export async function findProjectBySlug(orgSlug: string, projectSlug: string, userId: string) {
|
|
// Find the project scoped to the organization, making sure the user belongs to that org
|
|
return await $replica.project.findFirst({
|
|
where: {
|
|
slug: projectSlug,
|
|
organization: {
|
|
slug: orgSlug,
|
|
members: { some: { userId } },
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function findProjectByRef(externalRef: string, userId: string) {
|
|
// Find the project scoped to the organization, making sure the user belongs to that org
|
|
return await $replica.project.findFirst({
|
|
where: {
|
|
externalRef,
|
|
organization: {
|
|
members: { some: { userId } },
|
|
},
|
|
},
|
|
});
|
|
}
|