Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add scopes for partner program resources (#4652)

Kiran Ka169c096632f
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts
index 58b58ff92a..0326b71a94 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts
@@ -38,7 +38,7 @@ export const POST = withWorkspace(
return NextResponse.json(approvedSubmission);
},
{
+ requiredPermissions: ["bounties.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts
index 073f853a77..1bb4898fe8 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts
@@ -40,7 +40,7 @@ export const POST = withWorkspace(
return NextResponse.json(rejectedSubmission);
},
{
+ requiredPermissions: ["bounties.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
index 95ac706fd5..8c52a2cd1c 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
@@ -85,6 +85,7 @@ export const GET = withWorkspace(
return NextResponse.json(bountySubmissions);
},
{
+ requiredPermissions: ["bounties.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts
index a5dddbdff7..2fe59dba11 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts
@@ -248,6 +248,7 @@ export const POST = withWorkspace(
return NextResponse.json({});
},
{
+ requiredPermissions: ["bounties.write"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
diff --git a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
index 4b7f355117..73967f94b6 100644
--- a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
+++ b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
@@ -13,83 +13,89 @@ import {
import { NextResponse } from "next/server";
// GET /api/commissions/:commissionId - get a single commission by ID
-export const GET = withWorkspace(async ({ workspace, params }) => {
- const programId = getDefaultProgramIdOrThrow(workspace);
+export const GET = withWorkspace(
+ async ({ workspace, params }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
- const { commissionId } = params;
+ const { commissionId } = params;
- const commission = await prisma.commission.findUnique({
- where: {
- id: commissionId,
- programId,
- },
- include: {
- partner: true,
- programEnrollment: {
- select: {
- partnerGroup: {
- select: {
- id: true,
- holdingPeriodDays: true,
+ const commission = await prisma.commission.findUnique({
+ where: {
+ id: commissionId,
+ programId,
+ },
+ include: {
+ partner: true,
+ programEnrollment: {
+ select: {
+ partnerGroup: {
+ select: {
+ id: true,
+ holdingPeriodDays: true,
+ },
},
},
},
- },
- customer: true,
- reward: {
- select: {
- description: true,
- type: true,
- event: true,
- amountInCents: true,
- amountInPercentage: true,
+ customer: true,
+ reward: {
+ select: {
+ description: true,
+ type: true,
+ event: true,
+ amountInCents: true,
+ amountInPercentage: true,
+ },
},
- },
- user: true,
- payout: {
- select: {
- id: true,
- paidAt: true,
- initiatedAt: true,
- user: true,
+ user: true,
+ payout: {
+ select: {
+ id: true,
+ paidAt: true,
+ initiatedAt: true,
+ user: true,
+ },
},
},
- },
- });
-
- if (!commission) {
- throw new DubApiError({
- code: "not_found",
- message: `Commission ${commissionId} not found.`,
});
- }
- const { partner, programEnrollment, customer, reward, ...rest } = commission;
+ if (!commission) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Commission ${commissionId} not found.`,
+ });
+ }
- return NextResponse.json(
- CommissionDetailSchema.parse({
- ...rest,
- paidAt: rest.payout?.paidAt ?? null,
- partner: {
- ...partner,
- groupId: programEnrollment.partnerGroup?.id ?? null,
- },
- customer: transformCustomerForCommission(customer),
- reward: reward
- ? {
- ...reward,
- amountInPercentage: reward.amountInPercentage
- ? Number(reward.amountInPercentage)
- : null,
- }
- : null,
- holdingPeriodDays:
- rest.type === "custom"
- ? 0
- : programEnrollment.partnerGroup?.holdingPeriodDays ?? 0,
- }),
- );
-});
+ const { partner, programEnrollment, customer, reward, ...rest } =
+ commission;
+
+ return NextResponse.json(
+ CommissionDetailSchema.parse({
+ ...rest,
+ paidAt: rest.payout?.paidAt ?? null,
+ partner: {
+ ...partner,
+ groupId: programEnrollment.partnerGroup?.id ?? null,
+ },
+ customer: transformCustomerForCommission(customer),
+ reward: reward
+ ? {
+ ...reward,
+ amountInPercentage: reward.amountInPercentage
+ ? Number(reward.amountInPercentage)
+ : null,
+ }
+ : null,
+ holdingPeriodDays:
+ rest.type === "custom"
+ ? 0
+ : programEnrollment.partnerGroup?.holdingPeriodDays ?? 0,
+ }),
+ );
+ },
+ {
+ requiredPermissions: ["commissions.read"],
+ },
+);
// PATCH /api/commissions/:commissionId - update a commission
export const PATCH = withWorkspace(
@@ -132,6 +138,6 @@ export const PATCH = withWorkspace(
);
},
{
- requiredRoles: ["owner", "member"],
+ requiredPermissions: ["commissions.write"],
},
);
diff --git a/apps/web/app/(ee)/api/commissions/bulk/route.ts b/apps/web/app/(ee)/api/commissions/bulk/route.ts
index f8c68e3c1e..769da49a88 100644
--- a/apps/web/app/(ee)/api/commissions/bulk/route.ts
+++ b/apps/web/app/(ee)/api/commissions/bulk/route.ts
@@ -30,6 +30,6 @@ export const PATCH = withWorkspace(
);
},
{
- requiredRoles: ["owner", "member"],
+ requiredPermissions: ["commissions.write"],
},
);
diff --git a/apps/web/app/(ee)/api/commissions/route.ts b/apps/web/app/(ee)/api/commissions/route.ts
index d23d65fe92..b2539412f0 100644
--- a/apps/web/app/(ee)/api/commissions/route.ts
+++ b/apps/web/app/(ee)/api/commissions/route.ts
@@ -16,59 +16,64 @@ import { NextResponse } from "next/server";
import * as z from "zod/v4";
// GET /api/commissions - get all commissions for a program
-export const GET = withWorkspace(async ({ workspace, searchParams }) => {
- const programId = getDefaultProgramIdOrThrow(workspace);
+export const GET = withWorkspace(
+ async ({ workspace, searchParams }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
- let { partnerId, tenantId, ...filters } = getCommissionsQuerySchema
- .extend({
- fraudEventGroupId: z.string().optional(),
- type: z.string().optional(), // May be comma-separated string, for multi-value handling
- })
- .parse(searchParams);
+ let { partnerId, tenantId, ...filters } = getCommissionsQuerySchema
+ .extend({
+ fraudEventGroupId: z.string().optional(),
+ type: z.string().optional(), // May be comma-separated string, for multi-value handling
+ })
+ .parse(searchParams);
- if (tenantId && !partnerId) {
- const partner = await prisma.programEnrollment.findUnique({
- where: {
- tenantId_programId: {
- tenantId,
- programId,
+ if (tenantId && !partnerId) {
+ const partner = await prisma.programEnrollment.findUnique({
+ where: {
+ tenantId_programId: {
+ tenantId,
+ programId,
+ },
+ },
+ select: {
+ partnerId: true,
},
- },
- select: {
- partnerId: true,
- },
- });
-
- if (!partner) {
- throw new DubApiError({
- code: "not_found",
- message: `Partner with specified tenantId ${tenantId} not found.`,
});
- }
- partnerId = partner.partnerId;
- }
+ if (!partner) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Partner with specified tenantId ${tenantId} not found.`,
+ });
+ }
- const commissions = await getCommissions({
- ...filters,
- partnerId,
- programId,
- });
+ partnerId = partner.partnerId;
+ }
- return NextResponse.json(
- z.array(CommissionEnrichedSchema).parse(
- commissions.map((c) => ({
- ...c,
- paidAt: c.payout?.paidAt ?? null,
- customer: transformCustomerForCommission(c.customer),
- partner: {
- ...c.partner,
- groupId: c.programEnrollment.groupId,
- },
- })),
- ),
- );
-});
+ const commissions = await getCommissions({
+ ...filters,
+ partnerId,
+ programId,
+ });
+
+ return NextResponse.json(
+ z.array(CommissionEnrichedSchema).parse(
+ commissions.map((c) => ({
+ ...c,
+ paidAt: c.payout?.paidAt ?? null,
+ customer: transformCustomerForCommission(c.customer),
+ partner: {
+ ...c.partner,
+ groupId: c.programEnrollment.groupId,
+ },
+ })),
+ ),
+ );
+ },
+ {
+ requiredPermissions: ["commissions.read"],
+ },
+);
// POST /api/commissions - create manual commission
export const POST = withWorkspace(
@@ -104,7 +109,7 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["commissions.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts
index 3f842d24fa..4a8a708852 100644
--- a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts
+++ b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts
@@ -253,7 +253,7 @@ export const POST = withWorkspace(
);
},
{
+ requiredPermissions: ["customers.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/customers/[id]/route.ts b/apps/web/app/(ee)/api/customers/[id]/route.ts
index e0de9bd847..041dbfaaac 100644
--- a/apps/web/app/(ee)/api/customers/[id]/route.ts
+++ b/apps/web/app/(ee)/api/customers/[id]/route.ts
@@ -39,6 +39,7 @@ export const GET = withWorkspace(
return NextResponse.json(responseSchema.parse(transformCustomer(customer)));
},
{
+ requiredPermissions: ["customers.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
@@ -152,8 +153,8 @@ export const PATCH = withWorkspace(
}
},
{
+ requiredPermissions: ["customers.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
@@ -182,7 +183,7 @@ export const DELETE = withWorkspace(
});
},
{
+ requiredPermissions: ["customers.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/customers/route.ts b/apps/web/app/(ee)/api/customers/route.ts
index 588f1317f8..c6f7a4c15e 100644
--- a/apps/web/app/(ee)/api/customers/route.ts
+++ b/apps/web/app/(ee)/api/customers/route.ts
@@ -49,6 +49,7 @@ export const GET = withWorkspace(
return NextResponse.json(response);
},
{
+ requiredPermissions: ["customers.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
@@ -128,7 +129,7 @@ export const POST = withWorkspace(
}
},
{
+ requiredPermissions: ["customers.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/discount-codes/[idOrCode]/route.ts b/apps/web/app/(ee)/api/discount-codes/[idOrCode]/route.ts
index 8a0d07b5b3..5adb293859 100644
--- a/apps/web/app/(ee)/api/discount-codes/[idOrCode]/route.ts
+++ b/apps/web/app/(ee)/api/discount-codes/[idOrCode]/route.ts
@@ -69,7 +69,7 @@ export const DELETE = withWorkspace(
return NextResponse.json({ id: discountCode.id });
},
{
+ requiredPermissions: ["discount_codes.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/discount-codes/route.ts b/apps/web/app/(ee)/api/discount-codes/route.ts
index 69d556b1ff..7d8f5b8d13 100644
--- a/apps/web/app/(ee)/api/discount-codes/route.ts
+++ b/apps/web/app/(ee)/api/discount-codes/route.ts
@@ -64,6 +64,7 @@ export const GET = withWorkspace(
return NextResponse.json(DiscountCodeSchema.array().parse(discountCodes));
},
{
+ requiredPermissions: ["discount_codes.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
@@ -210,7 +211,7 @@ export const POST = withWorkspace(
return NextResponse.json(DiscountCodeSchema.parse(discountCode));
},
{
+ requiredPermissions: ["discount_codes.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/partners/analytics/route.ts b/apps/web/app/(ee)/api/partners/analytics/route.ts
index 236b99d168..b1e6a76c33 100644
--- a/apps/web/app/(ee)/api/partners/analytics/route.ts
+++ b/apps/web/app/(ee)/api/partners/analytics/route.ts
@@ -207,6 +207,7 @@ export const GET = withWorkspace(
return NextResponse.json(topLinksWithEarnings);
},
{
+ requiredPermissions: ["partners.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
diff --git a/apps/web/app/(ee)/api/partners/ban/route.ts b/apps/web/app/(ee)/api/partners/ban/route.ts
index 4005c77750..de9b428a5e 100644
--- a/apps/web/app/(ee)/api/partners/ban/route.ts
+++ b/apps/web/app/(ee)/api/partners/ban/route.ts
@@ -54,7 +54,7 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["partners.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/partners/deactivate/route.ts b/apps/web/app/(ee)/api/partners/deactivate/route.ts
index 67fd509acf..cfd75d4686 100644
--- a/apps/web/app/(ee)/api/partners/deactivate/route.ts
+++ b/apps/web/app/(ee)/api/partners/deactivate/route.ts
@@ -58,7 +58,7 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["partners.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/partners/links/route.ts b/apps/web/app/(ee)/api/partners/links/route.ts
index 4f1c89151e..3283da84f4 100644
--- a/apps/web/app/(ee)/api/partners/links/route.ts
+++ b/apps/web/app/(ee)/api/partners/links/route.ts
@@ -9,6 +9,7 @@ import {
toPartnerLinkRewardIdFields,
} from "@/lib/api/rewards/reward-overrides";
import { throwIfInvalidRewards } from "@/lib/api/rewards/throw-if-invalid-rewards";
+import { PARTNER_SCOPES_ENFORCED_AT } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { applyGroupUtmToLink } from "@/lib/api/utm/apply-group-utm-to-link";
import { withWorkspace } from "@/lib/auth";
@@ -85,8 +86,12 @@ export const GET = withWorkspace(
return NextResponse.json(z.array(responseSchema).parse(links));
},
{
+ requiredPermissions: ["links.read"],
+ // This route only checked roles before, so older keys keep access
+ legacyScopeGrants: [
+ { enforcedAt: PARTNER_SCOPES_ENFORCED_AT, permissions: ["links.read"] },
+ ],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
@@ -263,7 +268,11 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["links.write"],
+ // This route only checked roles before, so older keys keep access
+ legacyScopeGrants: [
+ { enforcedAt: PARTNER_SCOPES_ENFORCED_AT, permissions: ["links.write"] },
+ ],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/partners/route.ts b/apps/web/app/(ee)/api/partners/route.ts
index fb1b6feb32..1b7e643179 100644
--- a/apps/web/app/(ee)/api/partners/route.ts
+++ b/apps/web/app/(ee)/api/partners/route.ts
@@ -108,6 +108,7 @@ export const GET = withWorkspace(
);
},
{
+ requiredPermissions: ["partners.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
@@ -141,7 +142,7 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["partners.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/payouts/route.ts b/apps/web/app/(ee)/api/payouts/route.ts
index 4f598c7b13..85ef35b22a 100644
--- a/apps/web/app/(ee)/api/payouts/route.ts
+++ b/apps/web/app/(ee)/api/payouts/route.ts
@@ -9,18 +9,23 @@ import { NextResponse } from "next/server";
import * as z from "zod/v4";
// GET /api/payouts - get all payouts for a program
-export const GET = withWorkspace(async ({ workspace, searchParams }) => {
- const programId = getDefaultProgramIdOrThrow(workspace);
+export const GET = withWorkspace(
+ async ({ workspace, searchParams }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
- const filters = payoutsQuerySchema.parse(searchParams);
+ const filters = payoutsQuerySchema.parse(searchParams);
- const transformedPayouts = await getPayouts({
- workspaceId: workspace.id,
- programId,
- filters,
- });
+ const transformedPayouts = await getPayouts({
+ workspaceId: workspace.id,
+ programId,
+ filters,
+ });
- return NextResponse.json(
- z.array(PayoutResponseSchema).parse(transformedPayouts),
- );
-});
+ return NextResponse.json(
+ z.array(PayoutResponseSchema).parse(transformedPayouts),
+ );
+ },
+ {
+ requiredPermissions: ["payouts.read"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/program-applications/approve/route.ts b/apps/web/app/(ee)/api/program-applications/approve/route.ts
index ba21d3db27..e036fb0317 100644
--- a/apps/web/app/(ee)/api/program-applications/approve/route.ts
+++ b/apps/web/app/(ee)/api/program-applications/approve/route.ts
@@ -28,7 +28,7 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["program_applications.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/program-applications/reject/route.ts b/apps/web/app/(ee)/api/program-applications/reject/route.ts
index c748d28b65..5e07dc539a 100644
--- a/apps/web/app/(ee)/api/program-applications/reject/route.ts
+++ b/apps/web/app/(ee)/api/program-applications/reject/route.ts
@@ -35,7 +35,7 @@ export const POST = withWorkspace(
});
},
{
+ requiredPermissions: ["program_applications.write"],
requiredPlan: ["business", "advanced", "enterprise"],
- requiredRoles: ["owner", "member"],
},
);
diff --git a/apps/web/app/(ee)/api/program-applications/route.ts b/apps/web/app/(ee)/api/program-applications/route.ts
index c31f67a92b..5d16ebfffa 100644
--- a/apps/web/app/(ee)/api/program-applications/route.ts
+++ b/apps/web/app/(ee)/api/program-applications/route.ts
@@ -32,6 +32,7 @@ export const GET = withWorkspace(
return NextResponse.json(response);
},
{
+ requiredPermissions: ["program_applications.read"],
requiredPlan: ["business", "advanced", "enterprise"],
},
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
index 83e31a1c62..47bf45d1f5 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
@@ -88,6 +88,12 @@ function BountySubmissionDetailsSheetContent({
customPermissionDescription: "review bounty submissions",
}).error;
+ const refreshPermissionsError = clientAccessCheck({
+ action: "bounties.write",
+ role,
+ customPermissionDescription: "refresh bounty stats",
+ }).error;
+
const { setShowRejectModal, RejectBountySubmissionModal } =
useRejectBountySubmissionModal(submission, onNext);
@@ -462,6 +468,7 @@ function BountySubmissionDetailsSheetContent({
text="Refresh"
loading={isRefreshingSocialMetrics}
onClick={refreshSubmissionSocialMetrics}
+ disabledTooltip={refreshPermissionsError}
className="h-8 rounded-lg px-3"
/>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
index 9e6c9077b0..22b315ef86 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -4,6 +4,7 @@ import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
import { BountySubmissionStatusBadges } from "@/lib/bounty/bounty-submission-status-badges";
import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { clientAccessCheck } from "@/lib/client-access-check";
import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useBounty from "@/lib/swr/use-bounty";
@@ -504,7 +505,14 @@ function BountySubmissionFilters({
isRefreshingStats: boolean;
refreshStats: () => void;
}) {
+ const { role } = useWorkspace();
const { queryParams, searchParams } = useRouterStuff();
+
+ const refreshStatsError = clientAccessCheck({
+ action: "bounties.write",
+ role,
+ customPermissionDescription: "refresh bounty stats",
+ }).error;
const {
filters,
activeFilters,
@@ -568,6 +576,7 @@ function BountySubmissionFilters({
text="Refresh stats"
loading={isRefreshingStats}
onClick={refreshStats}
+ disabledTooltip={refreshStatsError}
className="h-8 rounded-lg px-3"
/>
</div>
diff --git a/apps/web/lib/api/oauth/constants.ts b/apps/web/lib/api/oauth/constants.ts
index b971b906aa..1c8120b04a 100644
--- a/apps/web/lib/api/oauth/constants.ts
+++ b/apps/web/lib/api/oauth/constants.ts
@@ -30,6 +30,21 @@ export const OAUTH_SCOPES = [
"webhooks.write",
"folders.read",
"folders.write",
+ "groups.read",
+ "groups.write",
+ "partners.read",
+ "partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
+ "commissions.write",
+ "bounties.read",
+ "bounties.write",
+ "payouts.read",
"user.read", // default scope, no need to request it
];
@@ -47,4 +62,19 @@ export const OAUTH_SCOPE_DESCRIPTIONS = {
"webhooks.write": "Read and Write access to webhooks",
"folders.read": "Read access to folders",
"folders.write": "Read and Write access to folders",
+ "groups.read": "Read access to groups",
+ "groups.write": "Read and Write access to groups",
+ "partners.read": "Read access to partners",
+ "partners.write": "Read and Write access to partners",
+ "program_applications.read": "Read access to program applications",
+ "program_applications.write": "Read and Write access to program applications",
+ "customers.read": "Read access to customers",
+ "customers.write": "Read and Write access to customers",
+ "discount_codes.read": "Read access to discount codes",
+ "discount_codes.write": "Read and Write access to discount codes",
+ "commissions.read": "Read access to commissions",
+ "commissions.write": "Read and Write access to commissions",
+ "bounties.read": "Read access to bounties",
+ "bounties.write": "Read and Write access to bounties",
+ "payouts.read": "Read access to payouts",
};
diff --git a/apps/web/lib/api/rbac/permissions.ts b/apps/web/lib/api/rbac/permissions.ts
index 4718204a59..b783c9520c 100644
--- a/apps/web/lib/api/rbac/permissions.ts
+++ b/apps/web/lib/api/rbac/permissions.ts
@@ -1,6 +1,6 @@
import { WorkspaceRole } from "@prisma/client";
-export const PERMISSION_ACTIONS = [
+const PERMISSION_ACTIONS = [
"workspaces.read",
"workspaces.write",
"links.read",
@@ -22,12 +22,22 @@ export const PERMISSION_ACTIONS = [
"folders.write",
"groups.write",
"groups.read",
+ "partners.read",
"partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
"commissions.write",
+ "bounties.read",
"bounties.write",
"campaigns.write",
"messages.read",
"messages.write",
+ "payouts.read",
"payouts.write",
"billing.write",
] as const;
@@ -134,6 +144,11 @@ export const ROLE_PERMISSIONS: {
description: "manage folders",
roles: ["owner", "member"],
},
+ {
+ action: "payouts.read",
+ description: "access payouts",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
{
action: "payouts.write",
description: "confirm payouts",
@@ -154,16 +169,61 @@ export const ROLE_PERMISSIONS: {
description: "manage groups",
roles: ["owner", "member"],
},
+ {
+ action: "partners.read",
+ description: "access partners",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
{
action: "partners.write",
description: "manage partners",
roles: ["owner", "member"],
},
+ {
+ action: "program_applications.read",
+ description: "access program applications",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
+ {
+ action: "program_applications.write",
+ description: "manage program applications",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "customers.read",
+ description: "access customers",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
+ {
+ action: "customers.write",
+ description: "manage customers",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "discount_codes.read",
+ description: "access discount codes",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
+ {
+ action: "discount_codes.write",
+ description: "manage discount codes",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "commissions.read",
+ description: "access commissions",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
{
action: "commissions.write",
description: "manage commissions",
roles: ["owner", "member"],
},
+ {
+ action: "bounties.read",
+ description: "access bounties",
+ roles: ["owner", "member", "viewer", "billing"],
+ },
{
action: "bounties.write",
description: "manage bounties",
diff --git a/apps/web/lib/api/rbac/resources.ts b/apps/web/lib/api/rbac/resources.ts
index db6531d2a1..c7bc0048f7 100644
--- a/apps/web/lib/api/rbac/resources.ts
+++ b/apps/web/lib/api/rbac/resources.ts
@@ -1,4 +1,4 @@
-export const RESOURCE_KEYS = [
+const RESOURCE_KEYS = [
"links",
"workspaces",
"analytics",
@@ -8,6 +8,13 @@ export const RESOURCE_KEYS = [
"tokens",
"webhooks",
"groups",
+ "partners",
+ "program_applications",
+ "customers",
+ "discount_codes",
+ "commissions",
+ "bounties",
+ "payouts",
] as const;
export type ResourceKey = (typeof RESOURCE_KEYS)[number];
@@ -18,19 +25,49 @@ export const RESOURCES: {
description: string;
}[] = [
{
- name: "Links",
- key: "links",
- description: "Create, read, update, and delete links",
+ name: "Partners",
+ key: "partners",
+ description: "Create, read, update, and delete partners",
},
{
- name: "Analytics",
- key: "analytics",
- description: "Create and read analytics events",
+ name: "Partner Groups",
+ key: "groups",
+ description: "Create, read, update, and delete partner groups",
},
{
- name: "Domains",
- key: "domains",
- description: "Create, read, update, and delete domains",
+ name: "Program Applications",
+ key: "program_applications",
+ description: "List, approve, and reject program applications",
+ },
+ {
+ name: "Customers",
+ key: "customers",
+ description: "Create, read, update, and delete customers",
+ },
+ {
+ name: "Discount Codes",
+ key: "discount_codes",
+ description: "Create, read, and delete discount codes",
+ },
+ {
+ name: "Commissions",
+ key: "commissions",
+ description: "Create, read, and update commissions",
+ },
+ {
+ name: "Bounties",
+ key: "bounties",
+ description: "List, approve, and reject bounty submissions",
+ },
+ {
+ name: "Payouts",
+ key: "payouts",
+ description: "Read payouts",
+ },
+ {
+ name: "Links",
+ key: "links",
+ description: "Create, read, update, and delete links",
},
{
name: "Tags",
@@ -42,4 +79,14 @@ export const RESOURCES: {
key: "folders",
description: "Create, read, update, and delete folders",
},
+ {
+ name: "Domains",
+ key: "domains",
+ description: "Create, read, update, and delete domains",
+ },
+ {
+ name: "Analytics",
+ key: "analytics",
+ description: "Create and read analytics events",
+ },
];
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 517a71addb..f4bd897367 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -18,6 +18,19 @@ export const SCOPES = [
"webhooks.write",
"groups.read",
"groups.write",
+ "partners.read",
+ "partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
+ "commissions.write",
+ "bounties.read",
+ "bounties.write",
+ "payouts.read",
"apis.all", // All API scopes
"apis.read", // All read scopes
] as const;
@@ -25,7 +38,7 @@ export const SCOPES = [
export type Scope = (typeof SCOPES)[number];
// Scopes available for Workspace API keys
-export const RESOURCE_SCOPES: {
+const RESOURCE_SCOPES: {
scope: Scope;
roles: WorkspaceRole[];
permissions: PermissionAction[];
@@ -102,6 +115,97 @@ export const RESOURCE_SCOPES: {
type: "write",
resource: "groups",
},
+ {
+ scope: "partners.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["partners.read"],
+ type: "read",
+ resource: "partners",
+ },
+ {
+ scope: "partners.write",
+ roles: ["owner", "member"],
+ permissions: ["partners.write", "partners.read"],
+ type: "write",
+ resource: "partners",
+ },
+ {
+ scope: "program_applications.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["program_applications.read"],
+ type: "read",
+ resource: "program_applications",
+ },
+ {
+ scope: "program_applications.write",
+ roles: ["owner", "member"],
+ permissions: ["program_applications.write", "program_applications.read"],
+ type: "write",
+ resource: "program_applications",
+ },
+ {
+ scope: "customers.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["customers.read"],
+ type: "read",
+ resource: "customers",
+ },
+ {
+ scope: "customers.write",
+ roles: ["owner", "member"],
+ permissions: ["customers.write", "customers.read"],
+ type: "write",
+ resource: "customers",
+ },
+ {
+ scope: "discount_codes.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["discount_codes.read"],
+ type: "read",
+ resource: "discount_codes",
+ },
+ {
+ scope: "discount_codes.write",
+ roles: ["owner", "member"],
+ permissions: ["discount_codes.write", "discount_codes.read"],
+ type: "write",
+ resource: "discount_codes",
+ },
+ {
+ scope: "commissions.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["commissions.read"],
+ type: "read",
+ resource: "commissions",
+ },
+ {
+ scope: "commissions.write",
+ roles: ["owner", "member"],
+ permissions: ["commissions.write", "commissions.read"],
+ type: "write",
+ resource: "commissions",
+ },
+ {
+ scope: "bounties.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["bounties.read"],
+ type: "read",
+ resource: "bounties",
+ },
+ {
+ scope: "bounties.write",
+ roles: ["owner", "member"],
+ permissions: ["bounties.write", "bounties.read"],
+ type: "write",
+ resource: "bounties",
+ },
+ {
+ scope: "payouts.read",
+ roles: ["owner", "member", "viewer", "billing"],
+ permissions: ["payouts.read"],
+ type: "read",
+ resource: "payouts",
+ },
{
scope: "workspaces.read",
roles: ["owner", "member", "viewer", "billing"],
@@ -148,6 +252,13 @@ export const RESOURCE_SCOPES: {
"workspaces.read",
"analytics.read",
"groups.read",
+ "partners.read",
+ "program_applications.read",
+ "customers.read",
+ "discount_codes.read",
+ "commissions.read",
+ "bounties.read",
+ "payouts.read",
],
},
{
@@ -167,36 +278,65 @@ export const RESOURCE_SCOPES: {
"analytics.read",
"groups.read",
"groups.write",
+ "partners.read",
+ "partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
+ "commissions.write",
+ "bounties.read",
+ "bounties.write",
+ "payouts.read",
],
},
];
-export const SCOPES_BY_RESOURCE = RESOURCE_SCOPES.reduce((acc, scope) => {
- if (!scope.resource || !scope.type) {
- return acc;
- }
-
- if (!acc[scope.resource]) {
- acc[scope.resource] = [];
- }
+export type LegacyScopeGrant = {
+ enforcedAt: Date;
+ permissions: readonly PermissionAction[];
+};
- acc[scope.resource].push({
- scope: scope.scope,
- type: scope.type,
- roles: scope.roles,
- });
+// Keys and OAuth installations created before this date were made before the
+// partner program scopes existed.
+export const PARTNER_SCOPES_ENFORCED_AT = new Date("2026-10-13T18:35:00.000Z");
- return acc;
-}, {});
+// Scopes introduced after API keys already existed. A key or OAuth installation
+// created before `enforcedAt` keeps these permissions without selecting the scope.
+// Keep permissions that share a cutoff in one entry. Add a new entry when a
+// scope needs a different cutoff.
+export const LEGACY_SCOPE_GRANTS: LegacyScopeGrant[] = [
+ {
+ enforcedAt: PARTNER_SCOPES_ENFORCED_AT,
+ permissions: [
+ "partners.read",
+ "partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
+ "commissions.write",
+ "bounties.read",
+ "bounties.write",
+ "payouts.read",
+ ],
+ },
+];
// Scope to permissions mapping
-export const SCOPE_PERMISSIONS_MAP = RESOURCE_SCOPES.reduce((acc, scope) => {
+const SCOPE_PERMISSIONS_MAP = RESOURCE_SCOPES.reduce((acc, scope) => {
acc[scope.scope] = scope.permissions;
return acc;
}, {});
// WorkspaceRole to scopes mapping
-export const ROLE_SCOPES_MAP = RESOURCE_SCOPES.reduce((acc, scope) => {
+const ROLE_SCOPES_MAP = RESOURCE_SCOPES.reduce((acc, scope) => {
scope.roles.forEach((role) => {
if (!acc[role]) {
acc[role] = [];
@@ -221,6 +361,34 @@ export const mapScopesToPermissions = (scopes: Scope[]) => {
return permissions;
};
+// Grants permissions from `grants` when the key or installation predates the
+// grant's cutoff. A missing date is treated as legacy so cached tokens from
+// before this field existed keep working. Routes can pass extra grants that
+// apply only to that route.
+export const grantLegacyScopePermissions = ({
+ permissions,
+ createdAt,
+ grants = LEGACY_SCOPE_GRANTS,
+}: {
+ permissions: PermissionAction[];
+ createdAt?: Date | string | null;
+ grants?: readonly LegacyScopeGrant[];
+}): PermissionAction[] => {
+ const createdAtMs = createdAt == null ? null : new Date(createdAt).getTime();
+
+ const legacyPermissions = grants.flatMap((grant) =>
+ createdAtMs != null && createdAtMs >= grant.enforcedAt.getTime()
+ ? []
+ : grant.permissions,
+ );
+
+ if (legacyPermissions.length === 0) {
+ return permissions;
+ }
+
+ return [...new Set<PermissionAction>([...permissions, ...legacyPermissions])];
+};
+
// Get SCOPES_BY_RESOURCE based on user role in a workspace
export const getScopesByResourceForRole = (role: WorkspaceRole) => {
const groupedByResource = {};
@@ -293,12 +461,12 @@ export const validateScopesForRole = (scopes: Scope[], role: WorkspaceRole) => {
};
// Get the scopes for a role
-export const getScopesForRole = (role: WorkspaceRole) => {
+const getScopesForRole = (role: WorkspaceRole) => {
return ROLE_SCOPES_MAP[role];
};
// Consolidate scopes to avoid duplication and show only the most permissive scope
-export const consolidateScopes = (scopes: string[]) => {
+const consolidateScopes = (scopes: string[]) => {
const consolidated = new Set();
scopes.forEach((scope) => {
diff --git a/apps/web/lib/auth/token-cache.ts b/apps/web/lib/auth/token-cache.ts
index a97159155c..ae2c11cdb6 100644
--- a/apps/web/lib/auth/token-cache.ts
+++ b/apps/web/lib/auth/token-cache.ts
@@ -16,7 +16,13 @@ const tokenCacheItemSchema = z.object({
defaultPartnerId: z.string().nullish(),
}),
scopes: z.string().nullish(),
+ createdAt: z.coerce.date().nullish(),
projectId: z.string().nullish(),
+ installedIntegration: z
+ .object({
+ createdAt: z.coerce.date(),
+ })
+ .nullish(),
project: z
.object({
plan: z.string().nullish(),
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index aac725c11e..d1cfb9600d 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -13,7 +13,13 @@ import {
PermissionAction,
getPermissionsByRole,
} from "../api/rbac/permissions";
-import { Scope, mapScopesToPermissions } from "../api/tokens/scopes";
+import {
+ LEGACY_SCOPE_GRANTS,
+ LegacyScopeGrant,
+ Scope,
+ grantLegacyScopePermissions,
+ mapScopesToPermissions,
+} from "../api/tokens/scopes";
import { throwIfNoAccess } from "../api/tokens/throw-if-no-access";
import { normalizeWorkspaceId } from "../api/workspaces/workspace-id";
import { withAxiomBodyLog } from "../axiom/server";
@@ -63,11 +69,13 @@ export const withWorkspace = (
requiredPlan = ["free", "pro", "business", "advanced", "enterprise"], // if the action needs a specific plan
requiredPermissions = [],
requiredRoles = [],
+ legacyScopeGrants = [], // permissions that older restricted tokens keep on this route only
featureFlag, // if the action needs a specific feature flag
}: {
requiredPlan?: Array<PlanProps>;
requiredPermissions?: PermissionAction[];
requiredRoles?: WorkspaceRole[];
+ legacyScopeGrants?: LegacyScopeGrant[];
featureFlag?: BetaFeatures;
} = {},
) => {
@@ -168,10 +176,22 @@ export const withWorkspace = (
if (apiKey) {
const hashedKey = await hashToken(apiKey);
- const cachedToken = await tokenCache.get({
+ let cachedToken = await tokenCache.get({
hashedKey,
});
+ // Entries cached before scope dates were stored would be treated as
+ // legacy and granted extra permissions, so reload them from the DB.
+ if (isRestrictedToken && cachedToken) {
+ const cachedScopeEffectiveSince = cachedToken.installationId
+ ? cachedToken.installedIntegration?.createdAt
+ : cachedToken.createdAt;
+
+ if (cachedScopeEffectiveSince == null) {
+ cachedToken = null;
+ }
+ }
+
if (!cachedToken) {
const prismaArgs = {
where: {
@@ -182,8 +202,14 @@ export const withWorkspace = (
expires: true,
...(isRestrictedToken && {
scopes: true,
+ createdAt: true,
projectId: true,
installationId: true,
+ installedIntegration: {
+ select: {
+ createdAt: true,
+ },
+ },
project: {
select: {
plan: true,
@@ -404,7 +430,8 @@ export const withWorkspace = (
workspace.users[0].role = "owner";
}
- permissions = getPermissionsByRole(workspace.users[0].role);
+ const rolePermissions = getPermissionsByRole(workspace.users[0].role);
+ permissions = rolePermissions;
// Find the subset of permissions that the user has access to based on the token scopes
// Empty/null scopes must fail closed (no permissions) — never inherit full role perms
@@ -413,8 +440,20 @@ export const withWorkspace = (
[]) as Scope[];
permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
- permissions.includes(p),
+ rolePermissions.includes(p),
);
+
+ // OAuth access tokens are reissued on refresh, so grandfather the
+ // installation date. Workspace API keys use their own createdAt.
+ const scopeEffectiveSince = token?.installationId
+ ? token.installedIntegration?.createdAt
+ : token?.createdAt;
+
+ permissions = grantLegacyScopePermissions({
+ permissions,
+ createdAt: scopeEffectiveSince,
+ grants: [...LEGACY_SCOPE_GRANTS, ...legacyScopeGrants],
+ }).filter((p) => rolePermissions.includes(p));
}
// Check user has permission to make the action
diff --git a/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts b/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
index 5b301f53ed..f00b89ab66 100644
--- a/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
+++ b/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
@@ -4,12 +4,11 @@ import {
getGrantedScopesForRole,
getMissingScopesForRole,
} from "@/lib/api/tokens/scopes";
-import { WorkspaceRole } from "@prisma/client";
import { describe, expect, test } from "vitest";
const ALL_OAUTH_SCOPES = [...OAUTH_SCOPES];
-const OWNER_ONLY_OAUTH_SCOPES = ["domains.write", "webhooks.write"];
+const SCOPES_EXCLUDED_FOR_MEMBER = ["domains.write", "webhooks.write"];
const READ_OAUTH_SCOPES = ALL_OAUTH_SCOPES.filter(
(scope) => scope === "user.read" || scope.endsWith(".read"),
@@ -25,7 +24,7 @@ describe("getGrantedScopesForRole", () => {
).toEqual(ALL_OAUTH_SCOPES);
});
- test("member is granted write scopes except owner-only ones", () => {
+ test("member is granted every scope except domains and webhooks write", () => {
expect(
getGrantedScopesForRole({
scopes: ALL_OAUTH_SCOPES,
@@ -33,22 +32,28 @@ describe("getGrantedScopesForRole", () => {
}),
).toEqual(
ALL_OAUTH_SCOPES.filter(
- (scope) => !OWNER_ONLY_OAUTH_SCOPES.includes(scope),
+ (scope) => !SCOPES_EXCLUDED_FOR_MEMBER.includes(scope),
),
);
});
- test.each(["viewer", "billing"] as const)(
- "%s is only granted read OAuth scopes and user.read",
- (role: WorkspaceRole) => {
- expect(
- getGrantedScopesForRole({
- scopes: ALL_OAUTH_SCOPES,
- role,
- }),
- ).toEqual(READ_OAUTH_SCOPES);
- },
- );
+ test("viewer is only granted read OAuth scopes and user.read", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ALL_OAUTH_SCOPES,
+ role: "viewer",
+ }),
+ ).toEqual(READ_OAUTH_SCOPES);
+ });
+
+ test("billing is only granted read OAuth scopes and user.read", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ALL_OAUTH_SCOPES,
+ role: "billing",
+ }),
+ ).toEqual(READ_OAUTH_SCOPES);
+ });
test("always grants user.read even when other requested scopes are not allowed", () => {
expect(
diff --git a/apps/web/tests/tokens/grant-legacy-scope-permissions.test.ts b/apps/web/tests/tokens/grant-legacy-scope-permissions.test.ts
new file mode 100644
index 0000000000..977f8bac6c
--- /dev/null
+++ b/apps/web/tests/tokens/grant-legacy-scope-permissions.test.ts
@@ -0,0 +1,154 @@
+import {
+ grantLegacyScopePermissions,
+ LEGACY_SCOPE_GRANTS,
+ PARTNER_SCOPES_ENFORCED_AT,
+} from "@/lib/api/tokens/scopes";
+import { describe, expect, test } from "vitest";
+
+const ENFORCED_AT = PARTNER_SCOPES_ENFORCED_AT;
+
+const LEGACY_PERMISSIONS = [
+ "partners.read",
+ "partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
+ "commissions.write",
+ "bounties.read",
+ "bounties.write",
+ "payouts.read",
+] as const;
+
+describe("grantLegacyScopePermissions", () => {
+ test("grants legacy permissions when createdAt is missing", () => {
+ expect(
+ grantLegacyScopePermissions({
+ permissions: ["links.read"],
+ createdAt: null,
+ }),
+ ).toEqual(["links.read", ...LEGACY_PERMISSIONS]);
+
+ expect(
+ grantLegacyScopePermissions({
+ permissions: ["links.read"],
+ }),
+ ).toEqual(["links.read", ...LEGACY_PERMISSIONS]);
+ });
+
+ test("grants legacy permissions when created before the cutoff", () => {
+ const createdAt = new Date(ENFORCED_AT.getTime() - 1);
+
+ expect(
+ grantLegacyScopePermissions({
+ permissions: ["links.read"],
+ createdAt,
+ }),
+ ).toEqual(["links.read", ...LEGACY_PERMISSIONS]);
+
+ expect(
+ grantLegacyScopePermissions({
+ permissions: ["links.read"],
+ createdAt: createdAt.toISOString(),
+ }),
+ ).toEqual(["links.read", ...LEGACY_PERMISSIONS]);
+ });
+
+ test("does not grant legacy permissions at or after the cutoff", () => {
+ const permissions = ["links.read"] as const;
+
+ expect(
+ grantLegacyScopePermissions({
+ permissions: [...permissions],
+ createdAt: ENFORCED_AT,
+ }),
+ ).toEqual([...permissions]);
+
+ expect(
+ grantLegacyScopePermissions({
+ permissions: [...permissions],
+ createdAt: new Date(ENFORCED_AT.getTime() + 1),
+ }),
+ ).toEqual([...permissions]);
+
+ expect(
+ grantLegacyScopePermissions({
+ permissions: [...permissions],
+ createdAt: ENFORCED_AT.toISOString(),
+ }),
+ ).toEqual([...permissions]);
+ });
+
+ test("keeps existing permissions and drops duplicates", () => {
+ expect(
+ grantLegacyScopePermissions({
+ permissions: ["partners.read", "links.write", "partners.read"],
+ createdAt: null,
+ }),
+ ).toEqual([
+ "partners.read",
+ "links.write",
+ "partners.write",
+ "program_applications.read",
+ "program_applications.write",
+ "customers.read",
+ "customers.write",
+ "discount_codes.read",
+ "discount_codes.write",
+ "commissions.read",
+ "commissions.write",
+ "bounties.read",
+ "bounties.write",
+ "payouts.read",
+ ]);
+ });
+
+ describe("route grants", () => {
+ const grants = [
+ ...LEGACY_SCOPE_GRANTS,
+ { enforcedAt: ENFORCED_AT, permissions: ["links.write"] as const },
+ ];
+
+ test("grants route permissions when created before the cutoff", () => {
+ expect(
+ grantLegacyScopePermissions({
+ permissions: [],
+ createdAt: new Date(ENFORCED_AT.getTime() - 1),
+ grants,
+ }),
+ ).toEqual([...LEGACY_PERMISSIONS, "links.write"]);
+ });
+
+ test("grants route permissions when createdAt is missing", () => {
+ expect(
+ grantLegacyScopePermissions({
+ permissions: [],
+ createdAt: null,
+ grants,
+ }),
+ ).toEqual([...LEGACY_PERMISSIONS, "links.write"]);
+ });
+
+ test("does not grant route permissions at or after the cutoff", () => {
+ expect(
+ grantLegacyScopePermissions({
+ permissions: ["links.read"],
+ createdAt: ENFORCED_AT,
+ grants,
+ }),
+ ).toEqual(["links.read"]);
+ });
+
+ test("route permissions do not leak into the default grants", () => {
+ expect(
+ grantLegacyScopePermissions({
+ permissions: [],
+ createdAt: null,
+ }),
+ ).not.toContain("links.write");
+ });
+ });
+});
diff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsx
index 547e3aeff2..8c49b60c80 100644
--- a/apps/web/ui/modals/add-edit-token-modal.tsx
+++ b/apps/web/ui/modals/add-edit-token-modal.tsx
@@ -1,4 +1,4 @@
-import { ResourceKey, RESOURCES } from "@/lib/api/rbac/resources";
+import { RESOURCES } from "@/lib/api/rbac/resources";
import {
getScopesByResourceForRole,
Scope,
@@ -146,7 +146,7 @@ function AddEditTokenModal({
const scopesByResources = transformScopesForUI(
getScopesByResourceForRole(role),
- ).filter(({ name }) => name);
+ );
return (
<>
@@ -273,10 +273,10 @@ function AddEditTokenModal({
</span>
</div>
{preset === "restricted" && (
- <div className="flex flex-col divide-y text-sm">
+ <div className="-mx-1 flex max-h-[max(160px,calc(100dvh-500px))] flex-col divide-y overflow-y-auto px-1 text-sm">
{scopesByResources.map((resource) => (
<div
- className="flex items-center justify-between py-4"
+ className="flex items-center justify-between py-2.5"
key={resource.key}
>
<div className="flex items-center gap-1.5">
@@ -406,10 +406,13 @@ export function useAddEditTokenModal({
}
const transformScopesForUI = (scopedResources) => {
- return Object.keys(scopedResources).map((resourceKey: ResourceKey) => {
- return {
- ...RESOURCES.find((r) => r.key === resourceKey)!,
- scopes: scopedResources[resourceKey],
- };
+ return RESOURCES.flatMap((resource) => {
+ const scopes = scopedResources[resource.key];
+
+ if (!scopes) {
+ return [];
+ }
+
+ return [{ ...resource, scopes }];
});
};