Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ organization creation provisions the workspace. The next cleanup release
removes the deprecated public project surface, but physical removal of the
internal project table requires a separate approved design.

Authenticated account-session organization members can query
`organizationCheckAllowance` for the creator account's aggregate check usage,
limit, and remaining allowance; the response never exposes creator identity
data.

Never commit credentials, production data, generated keys, or local `.env` files. Keep `.env.example` files limited to safe placeholders. The `docker-compose.infrastructure.yml` file is a generic stateful infrastructure template and must never contain production values, identifiers, hosts, or credentials.

Keep pull requests focused, add tests for behavior changes, and update public documentation when a user-visible workflow, deployment contract, or API changes.
6 changes: 6 additions & 0 deletions api/src/admin-schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,12 @@ type Mutation {
adminUnsuspendUser(id: ID!): AdminUserModel!
}

type OrganizationCheckAllowance {
limit: Int!
remaining: Int!
used: Int!
}

type OrganizationModel {
creatorLabel: String!
creatorUserId: ID!
Expand Down
34 changes: 34 additions & 0 deletions api/src/organizations/organizations.resolver.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { JwtUser } from '../auth/jwt.strategy';
import type { PrismaService } from '../prisma/prisma.service';
import { OrganizationsResolver } from './organizations.resolver';
import type { OrganizationsService } from './organizations.service';

describe('OrganizationsResolver.organizationCheckAllowance', () => {
it('requests the selected organization allowance for the authenticated user', async () => {
const organizationsService = {
organizationCheckAllowance: jest.fn().mockResolvedValue({
used: 3,
limit: 10,
remaining: 7,
}),
};
const resolver = new OrganizationsResolver(
{} as PrismaService,
organizationsService as unknown as OrganizationsService,
);

await expect(
resolver.organizationCheckAllowance(
{ userId: 'member-1' } as JwtUser,
'org-1',
),
).resolves.toEqual({
used: 3,
limit: 10,
remaining: 7,
});
expect(
organizationsService.organizationCheckAllowance,
).toHaveBeenCalledWith('member-1', 'org-1');
});
});
34 changes: 33 additions & 1 deletion api/src/organizations/organizations.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { Args, ID, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
Args,
Field,
ID,
Int,
Mutation,
ObjectType,
Query,
Resolver,
} from '@nestjs/graphql';
import { UseGuards } from '@nestjs/common';
import { ApiAuthGuard } from '../tokens/api-auth.guard';
import { CurrentUser } from '../common/current-user.decorator';
Expand All @@ -7,6 +16,18 @@ import { PrismaService } from '../prisma/prisma.service';
import { UserModel, OrganizationModel } from '../common/models';
import { OrganizationsService } from './organizations.service';

@ObjectType()
export class OrganizationCheckAllowance {
@Field(() => Int)
used!: number;

@Field(() => Int)
limit!: number;

@Field(() => Int)
remaining!: number;
}

@Resolver(() => UserModel)
@UseGuards(ApiAuthGuard)
export class OrganizationsResolver {
Expand Down Expand Up @@ -58,6 +79,17 @@ export class OrganizationsResolver {
};
}

@Query(() => OrganizationCheckAllowance)
organizationCheckAllowance(
@CurrentUser() user: JwtUser,
@Args('organizationId', { type: () => ID }) organizationId: string,
): Promise<OrganizationCheckAllowance> {
return this.organizationsService.organizationCheckAllowance(
user.userId,
organizationId,
);
}

@Mutation(() => OrganizationModel)
createOrganization(@CurrentUser() user: JwtUser, @Args('name') name: string) {
return this.organizationsService.create(user.userId, name);
Expand Down
91 changes: 91 additions & 0 deletions api/src/organizations/organizations.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,97 @@ function makeService(prisma: ReturnType<typeof makePrisma>) {
);
}

describe('OrganizationsService.organizationCheckAllowance', () => {
function setupAllowance(options?: {
creatorUserId?: string;
member?: boolean;
checkCount?: number;
maxChecks?: number;
}) {
const prisma = makePrisma();
prisma.tx.membership.findUnique.mockResolvedValue(
options?.member === false
? null
: {
organization: {
creatorUserId: options?.creatorUserId ?? 'creator-1',
},
},
);
const entitlements = {
lockUsers: jest.fn(),
forUser: jest.fn().mockResolvedValue({
plan: 'SIGNAL',
limits: {
maxChecks: options?.maxChecks ?? 12,
minIntervalSeconds: 10,
},
checkCount: options?.checkCount ?? 8,
organizationCount: 2,
}),
assertCanAddOrganization: jest.fn(),
};
const service = new OrganizationsService(
prisma as unknown as PrismaService,
entitlements as unknown as AccountEntitlementsService,
);
return { prisma, entitlements, service };
}

it('returns the organization creator account allowance to a member', async () => {
const h = setupAllowance();

await expect(
h.service.organizationCheckAllowance('member-1', 'org-1'),
).resolves.toEqual({
used: 8,
limit: 12,
remaining: 4,
});

expect(h.prisma.$transaction).toHaveBeenCalledTimes(1);
expect(h.prisma.tx.membership.findUnique).toHaveBeenCalledWith({
where: {
userId_organizationId: {
userId: 'member-1',
organizationId: 'org-1',
},
},
select: {
organization: {
select: { creatorUserId: true },
},
},
});
expect(h.entitlements.forUser).toHaveBeenCalledWith(
h.prisma.tx,
'creator-1',
);
});

it('clamps the remaining allowance at zero when usage exceeds the limit', async () => {
const h = setupAllowance({ checkCount: 15, maxChecks: 10 });

await expect(
h.service.organizationCheckAllowance('member-1', 'org-1'),
).resolves.toEqual({
used: 15,
limit: 10,
remaining: 0,
});
});

it('rejects a non-member before resolving creator entitlements', async () => {
const h = setupAllowance({ member: false });

await expect(
h.service.organizationCheckAllowance('outsider', 'org-1'),
).rejects.toBeInstanceOf(ForbiddenException);

expect(h.entitlements.forUser).not.toHaveBeenCalled();
});
});

describe('OrganizationsService.create', () => {
function serviceWithTx(
prisma: ReturnType<typeof makePrisma>,
Expand Down
42 changes: 42 additions & 0 deletions api/src/organizations/organizations.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,55 @@ export interface UpdateOrganizationInput {
slug?: string | null;
}

export interface OrganizationCheckAllowance {
used: number;
limit: number;
remaining: number;
}

@Injectable()
export class OrganizationsService {
constructor(
private readonly prisma: PrismaService,
private readonly entitlements: AccountEntitlementsService,
) {}

async organizationCheckAllowance(
userId: string,
organizationId: string,
): Promise<OrganizationCheckAllowance> {
return this.prisma.$transaction(async (tx) => {
const membership = await tx.membership.findUnique({
where: {
userId_organizationId: {
userId,
organizationId,
},
},
select: {
organization: {
select: { creatorUserId: true },
},
},
});
if (!membership) {
throw new ForbiddenException('Not a member of this organization');
}

const account = await this.entitlements.forUser(
tx,
membership.organization.creatorUserId,
);
const limit = account.limits.maxChecks;
const used = account.checkCount;
return {
used,
limit,
remaining: Math.max(0, limit - used),
};
});
}

async create(userId: string, name: string): Promise<OrgRow> {
const trimmed = name.trim();
if (!trimmed) {
Expand Down
7 changes: 7 additions & 0 deletions api/src/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,12 @@ type Mutation {
verifyEmailChannel(token: String!): EmailVerificationConfirmationModel!
}

type OrganizationCheckAllowance {
limit: Int!
remaining: Int!
used: Int!
}

type OrganizationModel {
creatorLabel: String!
creatorUserId: ID!
Expand Down Expand Up @@ -301,6 +307,7 @@ type Query {
managedTelegramBot: ManagedTelegramBotModel!
me: UserModel!
mySubscription: SubscriptionStatus!
organizationCheckAllowance(organizationId: ID!): OrganizationCheckAllowance!
organizationInvites(organizationId: ID!): [InviteModel!]!
organizationMembers(organizationId: ID!): [MemberModel!]!
projects: [ProjectModel!]! @deprecated(reason: "Organizations now contain one implicit workspace.")
Expand Down
21 changes: 18 additions & 3 deletions api/src/tokens/token-policy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,12 @@ describe('requireOperationAccess', () => {
).not.toThrow();
});

it.each(['telegramConnectionPreview', 'connectTelegramChannel', 'moveCheck'])(
it.each([
'telegramConnectionPreview',
'connectTelegramChannel',
'moveCheck',
'organizationCheckAllowance',
])(
'allows sessions to resolve the session-only operation %s',
(operationName) => {
expect(() =>
Expand All @@ -124,7 +129,12 @@ describe('requireOperationAccess', () => {
},
);

it.each(['telegramConnectionPreview', 'connectTelegramChannel', 'moveCheck'])(
it.each([
'telegramConnectionPreview',
'connectTelegramChannel',
'moveCheck',
'organizationCheckAllowance',
])(
'denies scoped API tokens from the session-only operation %s',
(operationName) => {
expect(() => {
Expand All @@ -133,7 +143,12 @@ describe('requireOperationAccess', () => {
},
);

it.each(['telegramConnectionPreview', 'connectTelegramChannel', 'moveCheck'])(
it.each([
'telegramConnectionPreview',
'connectTelegramChannel',
'moveCheck',
'organizationCheckAllowance',
])(
'denies legacy-broad API tokens from the session-only operation %s',
(operationName) => {
expect(() => {
Expand Down
1 change: 1 addition & 0 deletions api/src/tokens/token-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const SESSION_ONLY_OPERATIONS = new Set([
'telegramConnectionPreview',
'connectTelegramChannel',
'moveCheck',
'organizationCheckAllowance',
]);

export function requireOperationAccess(
Expand Down
1 change: 1 addition & 0 deletions frontend/app/(app)/billing/page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ describe("BillingPage", () => {
expect(
await screen.findByText("42 / 137 checks across 4 organizations")
).toBeInTheDocument();
expect(screen.getByText("95 checks left")).toBeInTheDocument();
});

it.each(["SIGNAL", "FLEET"])(
Expand Down
4 changes: 4 additions & 0 deletions frontend/app/(app)/billing/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export default function BillingPage() {
const planInfo = currentPlan ? PLAN_LIMITS[currentPlan] : undefined;
const checkCount = subscription?.checkCount ?? 0;
const maxChecks = subscription?.maxChecks ?? 0;
const remainingChecks = Math.max(0, maxChecks - checkCount);
const organizationCount = subscription?.organizationCount ?? 0;
const usageLabel = planUsageLabel(checkCount, maxChecks);
const actionsDisabled = !subscription || loadingAction !== null;
Expand Down Expand Up @@ -160,6 +161,9 @@ export default function BillingPage() {
{usageLabel} across {organizationCount}{" "}
{organizationCount === 1 ? "organization" : "organizations"}
</p>
<p className="font-medium text-foreground">
{remainingChecks} {remainingChecks === 1 ? "check" : "checks"} left
</p>
<p>
<span className="font-medium text-foreground">Min interval:</span>{" "}
<span className="font-mono">{planInfo.minIntervalSeconds}s</span> between checks
Expand Down
Loading
Loading