Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(admin): add an admin route to revoke unredeemed gift codes (#3829)

Hampus2ef00900964b
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.json
index 181bc1c22..635b1cfdf 100644
--- a/fluxer_admin/openapi-admin.json
+++ b/fluxer_admin/openapi-admin.json
@@ -4216,6 +4216,65 @@
}
}
},
+ "/admin/gift-codes/{code}": {
+ "delete": {
+ "operationId": "revoke_admin_gift_code",
+ "summary": "Revoke gift code",
+ "tags": ["Admin"],
+ "responses": {
+ "204": {"description": "No Content"},
+ "400": {
+ "description": "Bad Request - The request was malformed or contained invalid data",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "401": {
+ "description": "Unauthorized - Authentication is required or the token is invalid",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "403": {
+ "description": "Forbidden - You do not have permission to perform this action",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "429": {
+ "description": "Too Many Requests - You are being rate limited",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},
+ "headers": {
+ "Retry-After": {
+ "description": "Number of seconds to wait before retrying (only on 429)",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Limit": {
+ "description": "The number of requests that can be made in the current window",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Remaining": {
+ "description": "The number of remaining requests that can be made",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Reset": {
+ "description": "Unix timestamp when the rate limit resets",
+ "schema": {"type": "integer"}
+ }
+ }
+ },
+ "500": {
+ "description": "Internal Server Error - An unexpected error occurred",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ }
+ },
+ "description": "Revoke a gift code that nobody has redeemed, so it can no longer be redeemed. Pass the code, which is the last part of the redemption link. Returns 404 when the code is unknown or already revoked, and 400 when it was redeemed, in which case Remove user premium ends the premium it gave, or when a customer bought it. Creates audit log entry. Requires GIFT_CODES_GENERATE permission.",
+ "security": [{"adminApiKey": []}],
+ "parameters": [
+ {
+ "name": "code",
+ "in": "path",
+ "required": true,
+ "schema": {"description": "The gift code", "type": "string"},
+ "description": "The gift code"
+ }
+ ]
+ }
+ },
"/admin/guilds": {
"get": {
"operationId": "list_admin_guilds",
diff --git a/fluxer_api/src/api/admin/AdminService.ts b/fluxer_api/src/api/admin/AdminService.ts
index 255c642ce..833ba0a0b 100644
--- a/fluxer_api/src/api/admin/AdminService.ts
+++ b/fluxer_api/src/api/admin/AdminService.ts
@@ -256,7 +256,7 @@ export class AdminService {
guildRepository: this.guildRepository,
auditService: this.auditService,
});
- this.codeGenerationService = new AdminCodeGenerationService(users);
+ this.codeGenerationService = new AdminCodeGenerationService(users, this.apiContext.services.cache);
this.applicationService = new AdminApplicationService({
apiContext: this.apiContext,
applicationRepository: this.applicationRepository,
diff --git a/fluxer_api/src/api/admin/controllers/CodesAdminController.ts b/fluxer_api/src/api/admin/controllers/CodesAdminController.ts
index 81ab1cf16..c4b20560a 100644
--- a/fluxer_api/src/api/admin/controllers/CodesAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/CodesAdminController.ts
@@ -14,6 +14,7 @@ import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {FeatureNotAvailableSelfHostedError} from '@fluxer/errors/src/domains/core/FeatureNotAvailableSelfHostedError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {CodesResponse, GenerateGiftCodesRequest} from '@fluxer/schema/src/domains/admin/AdminSchemas';
+import {GiftCodeParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';
function trimTrailingSlash(value: string): string {
return value.endsWith('/') ? value.slice(0, -1) : value;
@@ -66,4 +67,34 @@ export function CodesAdminController(app: HonoApp) {
});
},
);
+ app.delete(
+ '/admin/gift-codes/:code',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_CODE_GENERATION),
+ requireAdminACL(AdminACLs.GIFT_CODES_GENERATE),
+ Validator('param', GiftCodeParam),
+ OpenAPI({
+ operationId: 'revoke_admin_gift_code',
+ summary: 'Revoke gift code',
+ description:
+ 'Revoke a gift code that nobody has redeemed, so it can no longer be redeemed. Pass the code, which is the last part of the redemption link. Returns 404 when the code is unknown or already revoked, and 400 when it was redeemed, in which case Remove user premium ends the premium it gave, or when a customer bought it. Creates audit log entry. Requires GIFT_CODES_GENERATE permission.',
+ responseSchema: null,
+ statusCode: 204,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ }),
+ async (ctx) => {
+ const giftCode = await ctx.get('adminService').codeGenerationService.revokeGiftCode(ctx.req.valid('param').code);
+ await recordAdminWrite(ctx, {
+ targetType: 'gift_code',
+ targetId: BigInt(0),
+ action: 'revoke_gift_code',
+ metadata: {
+ code: giftCode.code,
+ duration_type: giftCode.durationType,
+ duration_quantity: giftCode.durationQuantity.toString(),
+ },
+ });
+ return ctx.body(null, 204);
+ },
+ );
}
diff --git a/fluxer_api/src/api/admin/services/AdminCodeGenerationService.ts b/fluxer_api/src/api/admin/services/AdminCodeGenerationService.ts
index e1fda4297..ef3dcc3ef 100644
--- a/fluxer_api/src/api/admin/services/AdminCodeGenerationService.ts
+++ b/fluxer_api/src/api/admin/services/AdminCodeGenerationService.ts
@@ -1,9 +1,21 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
+import {SYSTEM_USER_ID} from '@app/api/constants/Core';
import type {GiftCodeDurationType, GiftCodeRow} from '@app/api/database/types/PaymentTypes';
-import {createGiftCodeRow, generateUniqueGiftCode, mapGiftCodeDurationToMonths} from '@app/api/models/GiftCode';
+import {
+ createGiftCodeRow,
+ type GiftCode,
+ generateUniqueGiftCode,
+ mapGiftCodeDurationToMonths,
+} from '@app/api/models/GiftCode';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {StripeGiftRedemptionInProgressError} from '@fluxer/errors/src/domains/payment/StripeGiftRedemptionInProgressError';
+import {UnknownGiftCodeError} from '@fluxer/errors/src/domains/payment/UnknownGiftCodeError';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
+import {seconds} from 'itty-time';
const MAX_CODES_PER_REQUEST = 100;
const DURATION_TYPES = new Set<GiftCodeDurationType>(['days', 'weeks', 'months', 'years']);
@@ -16,7 +28,10 @@ interface GenerateGiftCodesOptions {
}
export class AdminCodeGenerationService {
- constructor(private readonly userRepository: UserRepository) {}
+ constructor(
+ private readonly userRepository: UserRepository,
+ private readonly cacheService: ICacheService,
+ ) {}
async generateGiftCodes(options: GenerateGiftCodesOptions): Promise<Array<string>> {
const {count, createdByUserId} = this.validateOptions(options);
@@ -41,6 +56,41 @@ export class AdminCodeGenerationService {
return codes;
}
+ async revokeGiftCode(code: string): Promise<GiftCode> {
+ const lockKey = `gift_redeem_lock:${code}`;
+ const lockToken = await this.cacheService.acquireLock(lockKey, seconds('2 minutes'));
+ if (!lockToken) {
+ throw new StripeGiftRedemptionInProgressError();
+ }
+ try {
+ const giftCode = await this.userRepository.findGiftCode(code);
+ if (!giftCode || giftCode.revokedAt) {
+ throw new UnknownGiftCodeError();
+ }
+ if (giftCode.redeemedByUserId) {
+ throw InputValidationError.create(
+ 'code',
+ `This gift code was already redeemed by account ${giftCode.redeemedByUserId}. Use Remove premium on that account instead.`,
+ );
+ }
+ if (
+ giftCode.stripePaymentIntentId ||
+ giftCode.checkoutSessionId ||
+ giftCode.visionarySequenceNumber !== null ||
+ (!Config.instance.selfHosted && giftCode.createdByUserId !== SYSTEM_USER_ID)
+ ) {
+ throw InputValidationError.create(
+ 'code',
+ 'This gift code was bought by a customer. Refund the purchase instead, which revokes the code.',
+ );
+ }
+ await this.userRepository.revokeGiftCode(code);
+ return giftCode;
+ } finally {
+ await this.cacheService.releaseLock(lockKey, lockToken);
+ }
+ }
+
private validateOptions(options: GenerateGiftCodesOptions): GenerateGiftCodesOptions {
if (!Number.isInteger(options.count) || options.count < 1 || options.count > MAX_CODES_PER_REQUEST) {
throw new Error(`Gift code count must be between 1 and ${MAX_CODES_PER_REQUEST}`);
diff --git a/fluxer_api/src/api/admin/tests/AdminGiftCodeRevoke.test.ts b/fluxer_api/src/api/admin/tests/AdminGiftCodeRevoke.test.ts
new file mode 100644
index 000000000..4bdfcfa6c
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/AdminGiftCodeRevoke.test.ts
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
+import {getAdminRepository, getCacheService, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {createGiftCodeRow} from '@app/api/models/GiftCode';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+const REASON = 'Codes posted in a public channel';
+
+interface ErrorBody {
+ code?: string;
+ errors?: Array<{path: string; message: string}>;
+}
+
+describe('admin gift code revoke', () => {
+ let harness: ApiTestHarness;
+ let admin: TestAccount;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ admin = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.GIFT_CODES_GENERATE,
+ ]);
+ });
+
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+
+ async function generateCode(): Promise<string> {
+ const {codes} = await createBuilder<{codes: Array<string>}>(harness, admin.token)
+ .post('/admin/gift-codes')
+ .body({count: 1, duration_type: 'months', duration_quantity: 1})
+ .execute();
+ return codes[0]!.split('/').pop()!;
+ }
+
+ function revoke(code: string) {
+ return createBuilder<ErrorBody>(harness, admin.token)
+ .delete(`/admin/gift-codes/${code}`)
+ .header('X-Audit-Log-Reason', REASON)
+ .executeRaw();
+ }
+
+ async function redeem(account: TestAccount, code: string) {
+ return createBuilder<ErrorBody>(harness, account.token).post(`/gifts/${code}/redeem`).executeRaw();
+ }
+
+ it('revokes an unredeemed code so it can no longer be redeemed, and records it', async () => {
+ const code = await generateCode();
+ expect((await revoke(code)).response.status).toBe(204);
+ const account = await createTestAccount(harness);
+ const attempt = await redeem(account, code);
+ expect(attempt.response.status).toBe(404);
+ expect(attempt.json.code).toBe(APIErrorCodes.UNKNOWN_GIFT_CODE);
+ expect((await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)))).isPremium()).toBe(false);
+ expect((await getUserRepository().findGiftCode(code))?.revokedAt).not.toBeNull();
+ const entries = (await getAdminRepository().listAllAuditLogsPaginated(100)).filter(
+ (entry) => entry.action === 'revoke_gift_code',
+ );
+ expect(entries).toHaveLength(1);
+ expect(entries[0]!.auditLogReason).toBe(REASON);
+ expect(Object.fromEntries(entries[0]!.metadata)).toEqual({
+ code,
+ duration_type: 'months',
+ duration_quantity: '1',
+ });
+ });
+
+ it('refuses a redeemed code and points to Remove premium', async () => {
+ const code = await generateCode();
+ const account = await createTestAccount(harness);
+ expect((await redeem(account, code)).response.status).toBe(204);
+ const {response, json} = await revoke(code);
+ expect(response.status).toBe(400);
+ expect(json.errors).toEqual([
+ {
+ path: 'code',
+ message: `This gift code was already redeemed by account ${account.userId}. Use Remove premium on that account instead.`,
+ },
+ ]);
+ expect((await getUserRepository().findGiftCode(code))?.revokedAt).toBeNull();
+ expect((await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)))).isPremium()).toBe(true);
+ });
+
+ it('refuses a code a customer bought', async () => {
+ const buyer = await createTestAccount(harness);
+ await getUserRepository().createGiftCode(
+ createGiftCodeRow({
+ code: 'boughtgiftcode0000000000000000aa',
+ durationType: 'months',
+ durationQuantity: 1,
+ createdAt: new Date(),
+ createdByUserId: createUserID(BigInt(buyer.userId)),
+ paymentIntentId: 'pi_bought_gift',
+ }),
+ );
+ const {response, json} = await revoke('boughtgiftcode0000000000000000aa');
+ expect(response.status).toBe(400);
+ expect(json.errors?.[0]?.message).toBe(
+ 'This gift code was bought by a customer. Refund the purchase instead, which revokes the code.',
+ );
+ });
+
+ it('returns 404 for an unknown or already revoked code', async () => {
+ const code = await generateCode();
+ expect((await revoke(code)).response.status).toBe(204);
+ expect((await revoke(code)).response.status).toBe(404);
+ expect((await revoke('nosuchgiftcode')).response.status).toBe(404);
+ });
+
+ it('waits for a redemption that is in progress', async () => {
+ const code = await generateCode();
+ const token = await getCacheService().acquireLock(`gift_redeem_lock:${code}`, 60);
+ try {
+ const {response, json} = await revoke(code);
+ expect(response.status).toBe(400);
+ expect(json.code).toBe(APIErrorCodes.STRIPE_GIFT_REDEMPTION_IN_PROGRESS);
+ } finally {
+ await getCacheService().releaseLock(`gift_redeem_lock:${code}`, token!);
+ }
+ expect((await getUserRepository().findGiftCode(code))?.revokedAt).toBeNull();
+ });
+
+ it('requires the gift code permission', async () => {
+ const code = await generateCode();
+ const viewer = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.AUTHENTICATE]);
+ await createBuilder(harness, viewer.token).delete(`/admin/gift-codes/${code}`).expect(403).execute();
+ });
+});
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/CodesAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/CodesAdminAuditCases.ts
index 7a01424d0..ab412b7e4 100644
--- a/fluxer_api/src/api/admin/tests/audit_coverage/CodesAdminAuditCases.ts
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/CodesAdminAuditCases.ts
@@ -1,6 +1,18 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {AdminAuditCoverageCase} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import type {
+ AdminAuditCoverageCase,
+ AdminAuditCoverageContext,
+} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+
+async function generateCode({harness, admin}: AdminAuditCoverageContext): Promise<string> {
+ const {codes} = await createBuilder<{codes: Array<string>}>(harness, admin.token)
+ .post('/admin/gift-codes')
+ .body({count: 1, duration_type: 'weeks', duration_quantity: 2})
+ .execute();
+ return codes[0]!.split('/').pop()!;
+}
export const CodesAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
{
@@ -21,4 +33,20 @@ export const CodesAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
};
},
},
+ {
+ method: 'DELETE',
+ route: '/admin/gift-codes/:code',
+ async prepare(context) {
+ const code = await generateCode(context);
+ return {
+ request: {path: `/admin/gift-codes/${code}`, expectStatus: 204},
+ expected: {
+ action: 'revoke_gift_code',
+ targetType: 'gift_code',
+ targetId: '0',
+ metadata: {code, duration_type: 'weeks', duration_quantity: '2'},
+ },
+ };
+ },
+ },
];
diff --git a/fluxer_docs/src/content/docs/admin-api/gift-codes.mdx b/fluxer_docs/src/content/docs/admin-api/gift-codes.mdx
index 82312f652..c6a01859c 100644
--- a/fluxer_docs/src/content/docs/admin-api/gift-codes.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/gift-codes.mdx
@@ -1,7 +1,7 @@
---
# SPDX-License-Identifier: AGPL-3.0-or-later
title: Gift codes
-description: Generate one-use premium gift codes.
+description: Generate and revoke one-use premium gift codes.
---
import RouteHeader from '@/components/RouteHeader.astro';
@@ -52,5 +52,29 @@ The request records a `generate_gift_codes` [audit entry](/admin-api/#admin-audi
The rate limit is 30 requests per minute, on the `admin:code:generation` bucket.
:::caution[The codes are returned once]
-Save the response. No Admin API route lists or revokes the codes later. If a request fails partway, codes generated before the failure stay redeemable but aren't returned, so a retry creates additional codes.
+Save the response. No Admin API route lists the codes later. If a request fails partway, codes generated before the failure stay redeemable but aren't returned, so a retry creates additional codes. To stop a code you still have from working, [revoke it](#revoke-a-gift-code).
:::
+
+## Revoke a gift code
+
+<RouteHeader method="DELETE" path="/v1/admin/gift-codes/{code}" auditReason />
+
+Revokes a gift code that nobody has redeemed, so it can't be redeemed anymore. You need `gift_codes:generate`. Pass the code itself, which is the last part of the redemption link.
+
+A redeemed code can't be revoked, because the premium it gave already belongs to the account that redeemed it. To take that premium back, use [Remove user premium](/admin-api/users/#remove-user-premium) on that account. The error message names the account.
+
+A code a customer bought can't be revoked here either. Refund the purchase instead, which revokes the code.
+
+### Response
+
+| Status | Body | Condition |
+| --- | --- | --- |
+| 204 | none | The code was revoked |
+| 400 | [error response](/admin-api/#error-response) | `INVALID_FORM_BODY` when the code was redeemed or a customer bought it |
+| 400 | [error response](/admin-api/#error-response) | `STRIPE_GIFT_REDEMPTION_IN_PROGRESS` when someone is redeeming the code right now |
+| 404 | [error response](/admin-api/#error-response) | `UNKNOWN_GIFT_CODE` when the code doesn't exist or was already revoked |
+
+The request records a `revoke_gift_code` [audit entry](/admin-api/#admin-audit-entry-object) with the code and its duration. A revoked code can't be redeemed, so the entry doesn't give premium to anyone who reads it.
+
+The rate limit is 30 requests per minute, on the `admin:code:generation` bucket.
+
diff --git a/fluxer_docs/src/content/docs/admin-api/index.mdx b/fluxer_docs/src/content/docs/admin-api/index.mdx
index 937914eb9..2554b19b9 100644
--- a/fluxer_docs/src/content/docs/admin-api/index.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/index.mdx
@@ -89,7 +89,7 @@ Each route needs one or more ACLs, and the caller needs at least one of them. Th
| enforcement:view | Reads [enforcement decisions](/admin-api/enforcement/). Ending one needs this ACL plus the ACL for its kind |
| gateway:memory_stats | Reads main [Gateway](/admin-api/gateway/) statistics, memory statistics and voice state counts |
| gateway:reload_all | Reloads guilds across the main Gateway |
-| gift_codes:generate | Generates [gift codes](/admin-api/gift-codes/) |
+| gift_codes:generate | Generates and revokes [gift codes](/admin-api/gift-codes/) |
| guild:audit_log:view | Reads a guild's ordinary audit log |
| guild:ban_member | Bans a guild member and removes a guild ban |
| guild:delete | Deletes a guild |
@@ -274,7 +274,7 @@ Expect values that aren't in this table.
| report | User report |
| search_index | Search index |
| system_dm | System DM broadcast |
-| gift_code | Batch of generated gift codes |
+| gift_code | Batch of generated gift codes, or one revoked gift code |
| bulk_job | Background job |
| admin_api_key | Admin API key |
| audit_log | Admin audit entry |
@@ -459,6 +459,7 @@ These entries have `access` set to `write`.
| reset_built_in_badge_image | A built-in badge went back to its built-in image |
| resolve_report | A report was updated or resolved |
| revoke_admin_api_key | An Admin API key was revoked |
+| revoke_gift_code | A gift code nobody had redeemed was revoked |
| revoke_recovery_kit | The recovery kit of an account was revoked |
| revoke_registration_url | A registration URL was revoked |
| revoke_voice_join_token | A voice join token was revoked |
diff --git a/fluxer_docs/src/content/docs/http-api/gifts.mdx b/fluxer_docs/src/content/docs/http-api/gifts.mdx
index 459da56d6..658ff4bdb 100644
--- a/fluxer_docs/src/content/docs/http-api/gifts.mdx
+++ b/fluxer_docs/src/content/docs/http-api/gifts.mdx
@@ -72,7 +72,7 @@ Returns a [gift](#gift-object).
| Status | Body | Condition |
| --- | --- | --- |
| 200 | [gift](#gift-object) object | The gift was returned |
-| 404 | [error response](/http-api/#error-response) | `UNKNOWN_GIFT_CODE` when the code does not exist or was revoked after a refund |
+| 404 | [error response](/http-api/#error-response) | `UNKNOWN_GIFT_CODE` when the code does not exist or was revoked, after a refund or by an instance admin |
The rate limit is 60 requests per 10 seconds, on the `gift:get` bucket.